three.webgpu.nodes.js 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032
  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, 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, CubeDepthTexture, 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, IdentityDepthPacking, 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.ao || 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 byte boundary for the given data type.
  551. *
  552. * @private
  553. * @method
  554. * @param {string} type - The data type.
  555. * @return {number} The byte boundary.
  556. */
  557. function getByteBoundaryFromType( type ) {
  558. if ( /float|int|uint/.test( type ) ) return 4;
  559. if ( /vec2/.test( type ) ) return 8;
  560. if ( /vec3/.test( type ) ) return 16;
  561. if ( /vec4/.test( type ) ) return 16;
  562. if ( /mat2/.test( type ) ) return 8;
  563. if ( /mat3/.test( type ) ) return 48;
  564. if ( /mat4/.test( type ) ) return 64;
  565. error( 'TSL: Unsupported type:', type );
  566. }
  567. /**
  568. * Returns the data type for the given value.
  569. *
  570. * @private
  571. * @method
  572. * @param {any} value - The value.
  573. * @return {?string} The data type.
  574. */
  575. function getValueType( value ) {
  576. if ( value === undefined || value === null ) return null;
  577. const typeOf = typeof value;
  578. if ( value.isNode === true ) {
  579. return 'node';
  580. } else if ( typeOf === 'number' ) {
  581. return 'float';
  582. } else if ( typeOf === 'boolean' ) {
  583. return 'bool';
  584. } else if ( typeOf === 'string' ) {
  585. return 'string';
  586. } else if ( typeOf === 'function' ) {
  587. return 'shader';
  588. } else if ( value.isVector2 === true ) {
  589. return 'vec2';
  590. } else if ( value.isVector3 === true ) {
  591. return 'vec3';
  592. } else if ( value.isVector4 === true ) {
  593. return 'vec4';
  594. } else if ( value.isMatrix2 === true ) {
  595. return 'mat2';
  596. } else if ( value.isMatrix3 === true ) {
  597. return 'mat3';
  598. } else if ( value.isMatrix4 === true ) {
  599. return 'mat4';
  600. } else if ( value.isColor === true ) {
  601. return 'color';
  602. } else if ( value instanceof ArrayBuffer ) {
  603. return 'ArrayBuffer';
  604. }
  605. return null;
  606. }
  607. /**
  608. * Returns the value/object for the given data type and parameters.
  609. *
  610. * @private
  611. * @method
  612. * @param {string} type - The given type.
  613. * @param {...any} params - A parameter list.
  614. * @return {any} The value/object.
  615. */
  616. function getValueFromType( type, ...params ) {
  617. const last4 = type ? type.slice( -4 ) : undefined;
  618. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  619. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  620. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  621. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  622. }
  623. if ( type === 'color' ) {
  624. return new Color( ...params );
  625. } else if ( last4 === 'vec2' ) {
  626. return new Vector2( ...params );
  627. } else if ( last4 === 'vec3' ) {
  628. return new Vector3( ...params );
  629. } else if ( last4 === 'vec4' ) {
  630. return new Vector4( ...params );
  631. } else if ( last4 === 'mat2' ) {
  632. return new Matrix2( ...params );
  633. } else if ( last4 === 'mat3' ) {
  634. return new Matrix3( ...params );
  635. } else if ( last4 === 'mat4' ) {
  636. return new Matrix4( ...params );
  637. } else if ( type === 'bool' ) {
  638. return params[ 0 ] || false;
  639. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  640. return params[ 0 ] || 0;
  641. } else if ( type === 'string' ) {
  642. return params[ 0 ] || '';
  643. } else if ( type === 'ArrayBuffer' ) {
  644. return base64ToArrayBuffer( params[ 0 ] );
  645. }
  646. return null;
  647. }
  648. /**
  649. * Gets the object data that can be shared between different rendering steps.
  650. *
  651. * @private
  652. * @param {Object} object - The object to get the data for.
  653. * @return {Object} The object data.
  654. */
  655. function getDataFromObject( object ) {
  656. let data = dataFromObject.get( object );
  657. if ( data === undefined ) {
  658. data = {};
  659. dataFromObject.set( object, data );
  660. }
  661. return data;
  662. }
  663. /**
  664. * Converts the given array buffer to a Base64 string.
  665. *
  666. * @private
  667. * @method
  668. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  669. * @return {string} The Base64 string.
  670. */
  671. function arrayBufferToBase64( arrayBuffer ) {
  672. let chars = '';
  673. const array = new Uint8Array( arrayBuffer );
  674. for ( let i = 0; i < array.length; i ++ ) {
  675. chars += String.fromCharCode( array[ i ] );
  676. }
  677. return btoa( chars );
  678. }
  679. /**
  680. * Converts the given Base64 string to an array buffer.
  681. *
  682. * @private
  683. * @method
  684. * @param {string} base64 - The Base64 string.
  685. * @return {ArrayBuffer} The array buffer.
  686. */
  687. function base64ToArrayBuffer( base64 ) {
  688. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  689. }
  690. var NodeUtils = /*#__PURE__*/Object.freeze({
  691. __proto__: null,
  692. arrayBufferToBase64: arrayBufferToBase64,
  693. base64ToArrayBuffer: base64ToArrayBuffer,
  694. getByteBoundaryFromType: getByteBoundaryFromType,
  695. getDataFromObject: getDataFromObject,
  696. getLengthFromType: getLengthFromType,
  697. getMemoryLengthFromType: getMemoryLengthFromType,
  698. getTypeFromLength: getTypeFromLength,
  699. getTypedArrayFromType: getTypedArrayFromType,
  700. getValueFromType: getValueFromType,
  701. getValueType: getValueType,
  702. hash: hash$1,
  703. hashArray: hashArray,
  704. hashString: hashString
  705. });
  706. /**
  707. * Possible shader stages.
  708. *
  709. * @property {string} VERTEX The vertex shader stage.
  710. * @property {string} FRAGMENT The fragment shader stage.
  711. */
  712. const NodeShaderStage = {
  713. VERTEX: 'vertex',
  714. FRAGMENT: 'fragment'
  715. };
  716. /**
  717. * Update types of a node.
  718. *
  719. * @property {string} NONE The update method is not executed.
  720. * @property {string} FRAME The update method is executed per frame.
  721. * @property {string} RENDER The update method is executed per render. A frame might be produced by multiple render calls so this value allows more detailed updates than FRAME.
  722. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  723. */
  724. const NodeUpdateType = {
  725. NONE: 'none',
  726. FRAME: 'frame',
  727. RENDER: 'render',
  728. OBJECT: 'object'
  729. };
  730. /**
  731. * Data types of a node.
  732. *
  733. * @property {string} BOOLEAN Boolean type.
  734. * @property {string} INTEGER Integer type.
  735. * @property {string} FLOAT Float type.
  736. * @property {string} VECTOR2 Two-dimensional vector type.
  737. * @property {string} VECTOR3 Three-dimensional vector type.
  738. * @property {string} VECTOR4 Four-dimensional vector type.
  739. * @property {string} MATRIX2 2x2 matrix type.
  740. * @property {string} MATRIX3 3x3 matrix type.
  741. * @property {string} MATRIX4 4x4 matrix type.
  742. */
  743. const NodeType = {
  744. BOOLEAN: 'bool',
  745. INTEGER: 'int',
  746. FLOAT: 'float',
  747. VECTOR2: 'vec2',
  748. VECTOR3: 'vec3',
  749. VECTOR4: 'vec4',
  750. MATRIX2: 'mat2',
  751. MATRIX3: 'mat3',
  752. MATRIX4: 'mat4'
  753. };
  754. /**
  755. * Access types of a node. These are relevant for compute and storage usage.
  756. *
  757. * @property {string} READ_ONLY Read-only access
  758. * @property {string} WRITE_ONLY Write-only access.
  759. * @property {string} READ_WRITE Read and write access.
  760. */
  761. const NodeAccess = {
  762. READ_ONLY: 'readOnly',
  763. WRITE_ONLY: 'writeOnly',
  764. READ_WRITE: 'readWrite',
  765. };
  766. const defaultShaderStages = [ 'fragment', 'vertex' ];
  767. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  768. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  769. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  770. const _parentBuildStage = {
  771. analyze: 'setup',
  772. generate: 'analyze'
  773. };
  774. let _nodeId = 0;
  775. /**
  776. * Base class for all nodes.
  777. *
  778. * @augments EventDispatcher
  779. */
  780. class Node extends EventDispatcher {
  781. static get type() {
  782. return 'Node';
  783. }
  784. /**
  785. * Constructs a new node.
  786. *
  787. * @param {?string} nodeType - The node type.
  788. */
  789. constructor( nodeType = null ) {
  790. super();
  791. /**
  792. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  793. *
  794. * @type {?string}
  795. * @default null
  796. */
  797. this.nodeType = nodeType;
  798. /**
  799. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  800. *
  801. * @type {string}
  802. * @default 'none'
  803. */
  804. this.updateType = NodeUpdateType.NONE;
  805. /**
  806. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  807. *
  808. * @type {string}
  809. * @default 'none'
  810. */
  811. this.updateBeforeType = NodeUpdateType.NONE;
  812. /**
  813. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  814. *
  815. * @type {string}
  816. * @default 'none'
  817. */
  818. this.updateAfterType = NodeUpdateType.NONE;
  819. /**
  820. * The UUID of the node.
  821. *
  822. * @type {string}
  823. * @readonly
  824. */
  825. this.uuid = MathUtils.generateUUID();
  826. /**
  827. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  828. *
  829. * @type {number}
  830. * @readonly
  831. * @default 0
  832. */
  833. this.version = 0;
  834. /**
  835. * The name of the node.
  836. *
  837. * @type {string}
  838. * @default ''
  839. */
  840. this.name = '';
  841. /**
  842. * Whether this node is global or not. This property is relevant for the internal
  843. * node caching system. All nodes which should be declared just once should
  844. * set this flag to `true` (a typical example is {@link AttributeNode}).
  845. *
  846. * @type {boolean}
  847. * @default false
  848. */
  849. this.global = false;
  850. /**
  851. * Create a list of parents for this node during the build process.
  852. *
  853. * @type {boolean}
  854. * @default false
  855. */
  856. this.parents = false;
  857. /**
  858. * This flag can be used for type testing.
  859. *
  860. * @type {boolean}
  861. * @readonly
  862. * @default true
  863. */
  864. this.isNode = true;
  865. // private
  866. this._beforeNodes = null;
  867. /**
  868. * The cache key of this node.
  869. *
  870. * @private
  871. * @type {?number}
  872. * @default null
  873. */
  874. this._cacheKey = null;
  875. /**
  876. * The cache key 's version.
  877. *
  878. * @private
  879. * @type {number}
  880. * @default 0
  881. */
  882. this._cacheKeyVersion = 0;
  883. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  884. }
  885. /**
  886. * Set this property to `true` when the node should be regenerated.
  887. *
  888. * @type {boolean}
  889. * @default false
  890. * @param {boolean} value
  891. */
  892. set needsUpdate( value ) {
  893. if ( value === true ) {
  894. this.version ++;
  895. }
  896. }
  897. /**
  898. * The type of the class. The value is usually the constructor name.
  899. *
  900. * @type {string}
  901. * @readonly
  902. */
  903. get type() {
  904. return this.constructor.type;
  905. }
  906. /**
  907. * Convenient method for defining {@link Node#update}.
  908. *
  909. * @param {Function} callback - The update method.
  910. * @param {string} updateType - The update type.
  911. * @return {Node} A reference to this node.
  912. */
  913. onUpdate( callback, updateType ) {
  914. this.updateType = updateType;
  915. this.update = callback.bind( this );
  916. return this;
  917. }
  918. /**
  919. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  920. * this method automatically sets the update type to `FRAME`.
  921. *
  922. * @param {Function} callback - The update method.
  923. * @return {Node} A reference to this node.
  924. */
  925. onFrameUpdate( callback ) {
  926. return this.onUpdate( callback, NodeUpdateType.FRAME );
  927. }
  928. /**
  929. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  930. * this method automatically sets the update type to `RENDER`.
  931. *
  932. * @param {Function} callback - The update method.
  933. * @return {Node} A reference to this node.
  934. */
  935. onRenderUpdate( callback ) {
  936. return this.onUpdate( callback, NodeUpdateType.RENDER );
  937. }
  938. /**
  939. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  940. * this method automatically sets the update type to `OBJECT`.
  941. *
  942. * @param {Function} callback - The update method.
  943. * @return {Node} A reference to this node.
  944. */
  945. onObjectUpdate( callback ) {
  946. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  947. }
  948. /**
  949. * Convenient method for defining {@link Node#updateReference}.
  950. *
  951. * @param {Function} callback - The update method.
  952. * @return {Node} A reference to this node.
  953. */
  954. onReference( callback ) {
  955. this.updateReference = callback.bind( this );
  956. return this;
  957. }
  958. /**
  959. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  960. * to such objects based on a given state (e.g. the current node frame or builder).
  961. *
  962. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  963. * @return {any} The updated reference.
  964. */
  965. updateReference( /*state*/ ) {
  966. return this;
  967. }
  968. /**
  969. * By default this method returns the value of the {@link Node#global} flag. This method
  970. * can be overwritten in derived classes if an analytical way is required to determine the
  971. * global cache referring to the current shader-stage.
  972. *
  973. * @param {NodeBuilder} builder - The current node builder.
  974. * @return {boolean} Whether this node is global or not.
  975. */
  976. isGlobal( /*builder*/ ) {
  977. return this.global;
  978. }
  979. /**
  980. * Generator function that can be used to iterate over the child nodes.
  981. *
  982. * @generator
  983. * @yields {Node} A child node.
  984. */
  985. * getChildren() {
  986. for ( const { childNode } of this._getChildren() ) {
  987. yield childNode;
  988. }
  989. }
  990. /**
  991. * Calling this method dispatches the `dispose` event. This event can be used
  992. * to register event listeners for clean up tasks.
  993. */
  994. dispose() {
  995. this.dispatchEvent( { type: 'dispose' } );
  996. }
  997. /**
  998. * Callback for {@link Node#traverse}.
  999. *
  1000. * @callback traverseCallback
  1001. * @param {Node} node - The current node.
  1002. */
  1003. /**
  1004. * Can be used to traverse through the node's hierarchy.
  1005. *
  1006. * @param {traverseCallback} callback - A callback that is executed per node.
  1007. */
  1008. traverse( callback ) {
  1009. callback( this );
  1010. for ( const childNode of this.getChildren() ) {
  1011. childNode.traverse( callback );
  1012. }
  1013. }
  1014. /**
  1015. * Returns the child nodes of this node.
  1016. *
  1017. * @private
  1018. * @param {Set<Node>} [ignores=new Set()] - A set of nodes to ignore during the search to avoid circular references.
  1019. * @returns {Array<Object>} An array of objects describing the child nodes.
  1020. */
  1021. _getChildren( ignores = new Set() ) {
  1022. const children = [];
  1023. // avoid circular references
  1024. ignores.add( this );
  1025. for ( const property of Object.getOwnPropertyNames( this ) ) {
  1026. const object = this[ property ];
  1027. // Ignore private properties and ignored nodes.
  1028. if ( property.startsWith( '_' ) === true || ignores.has( object ) ) continue;
  1029. if ( Array.isArray( object ) === true ) {
  1030. for ( let i = 0; i < object.length; i ++ ) {
  1031. const child = object[ i ];
  1032. if ( child && child.isNode === true ) {
  1033. children.push( { property, index: i, childNode: child } );
  1034. }
  1035. }
  1036. } else if ( object && object.isNode === true ) {
  1037. children.push( { property, childNode: object } );
  1038. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  1039. for ( const subProperty in object ) {
  1040. // Ignore private sub-properties.
  1041. if ( subProperty.startsWith( '_' ) === true ) continue;
  1042. const child = object[ subProperty ];
  1043. if ( child && child.isNode === true ) {
  1044. children.push( { property, index: subProperty, childNode: child } );
  1045. }
  1046. }
  1047. }
  1048. }
  1049. //
  1050. return children;
  1051. }
  1052. /**
  1053. * Returns the cache key for this node.
  1054. *
  1055. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1056. * @param {Set<Node>} [ignores=null] - A set of nodes to ignore during the computation of the cache key.
  1057. * @return {number} The cache key of the node.
  1058. */
  1059. getCacheKey( force = false, ignores = null ) {
  1060. force = force || this.version !== this._cacheKeyVersion;
  1061. if ( force === true || this._cacheKey === null ) {
  1062. if ( ignores === null ) ignores = new Set();
  1063. //
  1064. const values = [];
  1065. for ( const { property, childNode } of this._getChildren( ignores ) ) {
  1066. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey( force, ignores ) );
  1067. }
  1068. //
  1069. this._cacheKey = hash$1( hashArray( values ), this.customCacheKey() );
  1070. this._cacheKeyVersion = this.version;
  1071. }
  1072. return this._cacheKey;
  1073. }
  1074. /**
  1075. * Generate a custom cache key for this node.
  1076. *
  1077. * @return {number} The cache key of the node.
  1078. */
  1079. customCacheKey() {
  1080. return this.id;
  1081. }
  1082. /**
  1083. * Returns the references to this node which is by default `this`.
  1084. *
  1085. * @return {Node} A reference to this node.
  1086. */
  1087. getScope() {
  1088. return this;
  1089. }
  1090. /**
  1091. * Returns the hash of the node which is used to identify the node. By default it's
  1092. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1093. * depending on their implementation.
  1094. *
  1095. * @param {NodeBuilder} builder - The current node builder.
  1096. * @return {string} The hash.
  1097. */
  1098. getHash( /*builder*/ ) {
  1099. return this.uuid;
  1100. }
  1101. /**
  1102. * Returns the update type of {@link Node#update}.
  1103. *
  1104. * @return {NodeUpdateType} The update type.
  1105. */
  1106. getUpdateType() {
  1107. return this.updateType;
  1108. }
  1109. /**
  1110. * Returns the update type of {@link Node#updateBefore}.
  1111. *
  1112. * @return {NodeUpdateType} The update type.
  1113. */
  1114. getUpdateBeforeType() {
  1115. return this.updateBeforeType;
  1116. }
  1117. /**
  1118. * Returns the update type of {@link Node#updateAfter}.
  1119. *
  1120. * @return {NodeUpdateType} The update type.
  1121. */
  1122. getUpdateAfterType() {
  1123. return this.updateAfterType;
  1124. }
  1125. /**
  1126. * Certain types are composed of multiple elements. For example a `vec3`
  1127. * is composed of three `float` values. This method returns the type of
  1128. * these elements.
  1129. *
  1130. * @param {NodeBuilder} builder - The current node builder.
  1131. * @return {string} The type of the node.
  1132. */
  1133. getElementType( builder ) {
  1134. const type = this.getNodeType( builder );
  1135. const elementType = builder.getElementType( type );
  1136. return elementType;
  1137. }
  1138. /**
  1139. * Returns the node member type for the given name.
  1140. *
  1141. * @param {NodeBuilder} builder - The current node builder.
  1142. * @param {string} name - The name of the member.
  1143. * @return {string} The type of the node.
  1144. */
  1145. getMemberType( /*builder, name*/ ) {
  1146. return 'void';
  1147. }
  1148. /**
  1149. * Returns the node's type.
  1150. *
  1151. * @param {NodeBuilder} builder - The current node builder.
  1152. * @return {string} The type of the node.
  1153. */
  1154. getNodeType( builder ) {
  1155. const nodeProperties = builder.getNodeProperties( this );
  1156. if ( nodeProperties.outputNode ) {
  1157. return nodeProperties.outputNode.getNodeType( builder );
  1158. }
  1159. return this.nodeType;
  1160. }
  1161. /**
  1162. * This method is used during the build process of a node and ensures
  1163. * equal nodes are not built multiple times but just once. For example if
  1164. * `attribute( 'uv' )` is used multiple times by the user, the build
  1165. * process makes sure to process just the first node.
  1166. *
  1167. * @param {NodeBuilder} builder - The current node builder.
  1168. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1169. */
  1170. getShared( builder ) {
  1171. const hash = this.getHash( builder );
  1172. const nodeFromHash = builder.getNodeFromHash( hash );
  1173. return nodeFromHash || this;
  1174. }
  1175. /**
  1176. * Returns the number of elements in the node array.
  1177. *
  1178. * @param {NodeBuilder} builder - The current node builder.
  1179. * @return {?number} The number of elements in the node array.
  1180. */
  1181. getArrayCount( /*builder*/ ) {
  1182. return null;
  1183. }
  1184. /**
  1185. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1186. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1187. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1188. *
  1189. * @param {NodeBuilder} builder - The current node builder.
  1190. * @return {?Node} The output node.
  1191. */
  1192. setup( builder ) {
  1193. const nodeProperties = builder.getNodeProperties( this );
  1194. let index = 0;
  1195. for ( const childNode of this.getChildren() ) {
  1196. nodeProperties[ 'node' + index ++ ] = childNode;
  1197. }
  1198. // return a outputNode if exists or null
  1199. return nodeProperties.outputNode || null;
  1200. }
  1201. /**
  1202. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1203. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1204. *
  1205. * @param {NodeBuilder} builder - The current node builder.
  1206. * @param {?Node} output - The target output node.
  1207. */
  1208. analyze( builder, output = null ) {
  1209. const usageCount = builder.increaseUsage( this );
  1210. if ( this.parents === true ) {
  1211. const nodeData = builder.getDataFromNode( this, 'any' );
  1212. nodeData.stages = nodeData.stages || {};
  1213. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1214. nodeData.stages[ builder.shaderStage ].push( output );
  1215. }
  1216. if ( usageCount === 1 ) {
  1217. // node flow children
  1218. const nodeProperties = builder.getNodeProperties( this );
  1219. for ( const childNode of Object.values( nodeProperties ) ) {
  1220. if ( childNode && childNode.isNode === true ) {
  1221. childNode.build( builder, this );
  1222. }
  1223. }
  1224. }
  1225. }
  1226. /**
  1227. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1228. * This state builds the output node and returns the resulting shader string.
  1229. *
  1230. * @param {NodeBuilder} builder - The current node builder.
  1231. * @param {?string} [output] - Can be used to define the output type.
  1232. * @return {?string} The generated shader string.
  1233. */
  1234. generate( builder, output ) {
  1235. const { outputNode } = builder.getNodeProperties( this );
  1236. if ( outputNode && outputNode.isNode === true ) {
  1237. return outputNode.build( builder, output );
  1238. }
  1239. }
  1240. /**
  1241. * The method can be implemented to update the node's internal state before it is used to render an object.
  1242. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1243. *
  1244. * @abstract
  1245. * @param {NodeFrame} frame - A reference to the current node frame.
  1246. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1247. */
  1248. updateBefore( /*frame*/ ) {
  1249. warn( 'Abstract function.' );
  1250. }
  1251. /**
  1252. * The method can be implemented to update the node's internal state after it was used to render an object.
  1253. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1254. *
  1255. * @abstract
  1256. * @param {NodeFrame} frame - A reference to the current node frame.
  1257. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1258. */
  1259. updateAfter( /*frame*/ ) {
  1260. warn( 'Abstract function.' );
  1261. }
  1262. /**
  1263. * The method can be implemented to update the node's internal state when it is used to render an object.
  1264. * The {@link Node#updateType} property defines how often the update is executed.
  1265. *
  1266. * @abstract
  1267. * @param {NodeFrame} frame - A reference to the current node frame.
  1268. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1269. */
  1270. update( /*frame*/ ) {
  1271. warn( 'Abstract function.' );
  1272. }
  1273. before( node ) {
  1274. if ( this._beforeNodes === null ) this._beforeNodes = [];
  1275. this._beforeNodes.push( node );
  1276. return this;
  1277. }
  1278. /**
  1279. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1280. * - **setup**: Prepares the node and its children for the build process. This process can also create new nodes. Returns the node itself or a variant.
  1281. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1282. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1283. *
  1284. * @param {NodeBuilder} builder - The current node builder.
  1285. * @param {?(string|Node)} [output=null] - Can be used to define the output type.
  1286. * @return {?(Node|string)} The result of the build process, depending on the build stage.
  1287. */
  1288. build( builder, output = null ) {
  1289. const refNode = this.getShared( builder );
  1290. if ( this !== refNode ) {
  1291. return refNode.build( builder, output );
  1292. }
  1293. //
  1294. if ( this._beforeNodes !== null ) {
  1295. const currentBeforeNodes = this._beforeNodes;
  1296. this._beforeNodes = null;
  1297. for ( const beforeNode of currentBeforeNodes ) {
  1298. beforeNode.build( builder, output );
  1299. }
  1300. this._beforeNodes = currentBeforeNodes;
  1301. }
  1302. //
  1303. const nodeData = builder.getDataFromNode( this );
  1304. nodeData.buildStages = nodeData.buildStages || {};
  1305. nodeData.buildStages[ builder.buildStage ] = true;
  1306. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1307. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1308. // force parent build stage (setup or analyze)
  1309. const previousBuildStage = builder.getBuildStage();
  1310. builder.setBuildStage( parentBuildStage );
  1311. this.build( builder );
  1312. builder.setBuildStage( previousBuildStage );
  1313. }
  1314. //
  1315. builder.addNode( this );
  1316. builder.addChain( this );
  1317. /* Build stages expected results:
  1318. - "setup" -> Node
  1319. - "analyze" -> null
  1320. - "generate" -> String
  1321. */
  1322. let result = null;
  1323. const buildStage = builder.getBuildStage();
  1324. if ( buildStage === 'setup' ) {
  1325. this.updateReference( builder );
  1326. const properties = builder.getNodeProperties( this );
  1327. if ( properties.initialized !== true ) {
  1328. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1329. properties.initialized = true;
  1330. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1331. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1332. // !! no outputNode !!
  1333. //outputNode = builder.stack;
  1334. }*/
  1335. for ( const childNode of Object.values( properties ) ) {
  1336. if ( childNode && childNode.isNode === true ) {
  1337. if ( childNode.parents === true ) {
  1338. const childProperties = builder.getNodeProperties( childNode );
  1339. childProperties.parents = childProperties.parents || [];
  1340. childProperties.parents.push( this );
  1341. }
  1342. childNode.build( builder );
  1343. }
  1344. }
  1345. }
  1346. result = properties.outputNode;
  1347. } else if ( buildStage === 'analyze' ) {
  1348. this.analyze( builder, output );
  1349. } else if ( buildStage === 'generate' ) {
  1350. // If generate has just one argument, it means the output type is not required.
  1351. // This means that the node does not handle output conversions internally,
  1352. // so the value is stored in a cache and the builder handles the conversion
  1353. // for all requested output types.
  1354. const isGenerateOnce = this.generate.length < 2;
  1355. if ( isGenerateOnce ) {
  1356. const type = this.getNodeType( builder );
  1357. const nodeData = builder.getDataFromNode( this );
  1358. result = nodeData.snippet;
  1359. if ( result === undefined ) {
  1360. if ( nodeData.generated === undefined ) {
  1361. nodeData.generated = true;
  1362. result = this.generate( builder ) || '';
  1363. nodeData.snippet = result;
  1364. } else {
  1365. warn( 'Node: Recursion detected.', this );
  1366. result = '/* Recursion detected. */';
  1367. }
  1368. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1369. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1370. }
  1371. result = builder.format( result, type, output );
  1372. } else {
  1373. result = this.generate( builder, output ) || '';
  1374. }
  1375. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1376. // if no snippet is generated, return a default value
  1377. error( `TSL: Invalid generated code, expected a "${ output }".` );
  1378. result = builder.generateConst( output );
  1379. }
  1380. }
  1381. builder.removeChain( this );
  1382. builder.addSequentialNode( this );
  1383. return result;
  1384. }
  1385. /**
  1386. * Returns the child nodes as a JSON object.
  1387. *
  1388. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1389. */
  1390. getSerializeChildren() {
  1391. return this._getChildren();
  1392. }
  1393. /**
  1394. * Serializes the node to JSON.
  1395. *
  1396. * @param {Object} json - The output JSON object.
  1397. */
  1398. serialize( json ) {
  1399. const nodeChildren = this.getSerializeChildren();
  1400. const inputNodes = {};
  1401. for ( const { property, index, childNode } of nodeChildren ) {
  1402. if ( index !== undefined ) {
  1403. if ( inputNodes[ property ] === undefined ) {
  1404. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1405. }
  1406. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1407. } else {
  1408. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1409. }
  1410. }
  1411. if ( Object.keys( inputNodes ).length > 0 ) {
  1412. json.inputNodes = inputNodes;
  1413. }
  1414. }
  1415. /**
  1416. * Deserializes the node from the given JSON.
  1417. *
  1418. * @param {Object} json - The JSON object.
  1419. */
  1420. deserialize( json ) {
  1421. if ( json.inputNodes !== undefined ) {
  1422. const nodes = json.meta.nodes;
  1423. for ( const property in json.inputNodes ) {
  1424. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1425. const inputArray = [];
  1426. for ( const uuid of json.inputNodes[ property ] ) {
  1427. inputArray.push( nodes[ uuid ] );
  1428. }
  1429. this[ property ] = inputArray;
  1430. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1431. const inputObject = {};
  1432. for ( const subProperty in json.inputNodes[ property ] ) {
  1433. const uuid = json.inputNodes[ property ][ subProperty ];
  1434. inputObject[ subProperty ] = nodes[ uuid ];
  1435. }
  1436. this[ property ] = inputObject;
  1437. } else {
  1438. const uuid = json.inputNodes[ property ];
  1439. this[ property ] = nodes[ uuid ];
  1440. }
  1441. }
  1442. }
  1443. }
  1444. /**
  1445. * Serializes the node into the three.js JSON Object/Scene format.
  1446. *
  1447. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1448. * @return {Object} The serialized node.
  1449. */
  1450. toJSON( meta ) {
  1451. const { uuid, type } = this;
  1452. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1453. if ( isRoot ) {
  1454. meta = {
  1455. textures: {},
  1456. images: {},
  1457. nodes: {}
  1458. };
  1459. }
  1460. // serialize
  1461. let data = meta.nodes[ uuid ];
  1462. if ( data === undefined ) {
  1463. data = {
  1464. uuid,
  1465. type,
  1466. meta,
  1467. metadata: {
  1468. version: 4.7,
  1469. type: 'Node',
  1470. generator: 'Node.toJSON'
  1471. }
  1472. };
  1473. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1474. this.serialize( data );
  1475. delete data.meta;
  1476. }
  1477. // TODO: Copied from Object3D.toJSON
  1478. function extractFromCache( cache ) {
  1479. const values = [];
  1480. for ( const key in cache ) {
  1481. const data = cache[ key ];
  1482. delete data.metadata;
  1483. values.push( data );
  1484. }
  1485. return values;
  1486. }
  1487. if ( isRoot ) {
  1488. const textures = extractFromCache( meta.textures );
  1489. const images = extractFromCache( meta.images );
  1490. const nodes = extractFromCache( meta.nodes );
  1491. if ( textures.length > 0 ) data.textures = textures;
  1492. if ( images.length > 0 ) data.images = images;
  1493. if ( nodes.length > 0 ) data.nodes = nodes;
  1494. }
  1495. return data;
  1496. }
  1497. }
  1498. /**
  1499. * Base class for representing element access on an array-like
  1500. * node data structures.
  1501. *
  1502. * @augments Node
  1503. */
  1504. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1505. static get type() {
  1506. return 'ArrayElementNode';
  1507. }
  1508. /**
  1509. * Constructs an array element node.
  1510. *
  1511. * @param {Node} node - The array-like node.
  1512. * @param {Node} indexNode - The index node that defines the element access.
  1513. */
  1514. constructor( node, indexNode ) {
  1515. super();
  1516. /**
  1517. * The array-like node.
  1518. *
  1519. * @type {Node}
  1520. */
  1521. this.node = node;
  1522. /**
  1523. * The index node that defines the element access.
  1524. *
  1525. * @type {Node}
  1526. */
  1527. this.indexNode = indexNode;
  1528. /**
  1529. * This flag can be used for type testing.
  1530. *
  1531. * @type {boolean}
  1532. * @readonly
  1533. * @default true
  1534. */
  1535. this.isArrayElementNode = true;
  1536. }
  1537. /**
  1538. * This method is overwritten since the node type is inferred from the array-like node.
  1539. *
  1540. * @param {NodeBuilder} builder - The current node builder.
  1541. * @return {string} The node type.
  1542. */
  1543. getNodeType( builder ) {
  1544. return this.node.getElementType( builder );
  1545. }
  1546. generate( builder ) {
  1547. const indexType = this.indexNode.getNodeType( builder );
  1548. const nodeSnippet = this.node.build( builder );
  1549. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1550. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1551. }
  1552. }
  1553. /**
  1554. * This module is part of the TSL core and usually not used in app level code.
  1555. * It represents a convert operation during the shader generation process
  1556. * meaning it converts the data type of a node to a target data type.
  1557. *
  1558. * @augments Node
  1559. */
  1560. class ConvertNode extends Node {
  1561. static get type() {
  1562. return 'ConvertNode';
  1563. }
  1564. /**
  1565. * Constructs a new convert node.
  1566. *
  1567. * @param {Node} node - The node which type should be converted.
  1568. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1569. */
  1570. constructor( node, convertTo ) {
  1571. super();
  1572. /**
  1573. * The node which type should be converted.
  1574. *
  1575. * @type {Node}
  1576. */
  1577. this.node = node;
  1578. /**
  1579. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1580. *
  1581. * @type {string}
  1582. */
  1583. this.convertTo = convertTo;
  1584. }
  1585. /**
  1586. * This method is overwritten since the implementation tries to infer the best
  1587. * matching type from the {@link ConvertNode#convertTo} property.
  1588. *
  1589. * @param {NodeBuilder} builder - The current node builder.
  1590. * @return {string} The node type.
  1591. */
  1592. getNodeType( builder ) {
  1593. const requestType = this.node.getNodeType( builder );
  1594. let convertTo = null;
  1595. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1596. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1597. convertTo = overloadingType;
  1598. }
  1599. }
  1600. return convertTo;
  1601. }
  1602. serialize( data ) {
  1603. super.serialize( data );
  1604. data.convertTo = this.convertTo;
  1605. }
  1606. deserialize( data ) {
  1607. super.deserialize( data );
  1608. this.convertTo = data.convertTo;
  1609. }
  1610. generate( builder, output ) {
  1611. const node = this.node;
  1612. const type = this.getNodeType( builder );
  1613. const snippet = node.build( builder, type );
  1614. return builder.format( snippet, type, output );
  1615. }
  1616. }
  1617. /**
  1618. * This module uses cache management to create temporary variables
  1619. * if the node is used more than once to prevent duplicate calculations.
  1620. *
  1621. * The class acts as a base class for many other nodes types.
  1622. *
  1623. * @augments Node
  1624. */
  1625. class TempNode extends Node {
  1626. static get type() {
  1627. return 'TempNode';
  1628. }
  1629. /**
  1630. * Constructs a temp node.
  1631. *
  1632. * @param {?string} nodeType - The node type.
  1633. */
  1634. constructor( nodeType = null ) {
  1635. super( nodeType );
  1636. /**
  1637. * This flag can be used for type testing.
  1638. *
  1639. * @type {boolean}
  1640. * @readonly
  1641. * @default true
  1642. */
  1643. this.isTempNode = true;
  1644. }
  1645. /**
  1646. * Whether this node is used more than once in context of other nodes.
  1647. *
  1648. * @param {NodeBuilder} builder - The node builder.
  1649. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1650. */
  1651. hasDependencies( builder ) {
  1652. return builder.getDataFromNode( this ).usageCount > 1;
  1653. }
  1654. build( builder, output ) {
  1655. const buildStage = builder.getBuildStage();
  1656. if ( buildStage === 'generate' ) {
  1657. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1658. const nodeData = builder.getDataFromNode( this );
  1659. if ( nodeData.propertyName !== undefined ) {
  1660. return builder.format( nodeData.propertyName, type, output );
  1661. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1662. const snippet = super.build( builder, type );
  1663. const nodeVar = builder.getVarFromNode( this, null, type );
  1664. const propertyName = builder.getPropertyName( nodeVar );
  1665. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1666. nodeData.snippet = snippet;
  1667. nodeData.propertyName = propertyName;
  1668. return builder.format( nodeData.propertyName, type, output );
  1669. }
  1670. }
  1671. return super.build( builder, output );
  1672. }
  1673. }
  1674. /**
  1675. * This module is part of the TSL core and usually not used in app level code.
  1676. * It represents a join operation during the shader generation process.
  1677. * For example in can compose/join two single floats into a `vec2` type.
  1678. *
  1679. * @augments TempNode
  1680. */
  1681. class JoinNode extends TempNode {
  1682. static get type() {
  1683. return 'JoinNode';
  1684. }
  1685. /**
  1686. * Constructs a new join node.
  1687. *
  1688. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1689. * @param {?string} [nodeType=null] - The node type.
  1690. */
  1691. constructor( nodes = [], nodeType = null ) {
  1692. super( nodeType );
  1693. /**
  1694. * An array of nodes that should be joined.
  1695. *
  1696. * @type {Array<Node>}
  1697. */
  1698. this.nodes = nodes;
  1699. }
  1700. /**
  1701. * This method is overwritten since the node type must be inferred from the
  1702. * joined data length if not explicitly defined.
  1703. *
  1704. * @param {NodeBuilder} builder - The current node builder.
  1705. * @return {string} The node type.
  1706. */
  1707. getNodeType( builder ) {
  1708. if ( this.nodeType !== null ) {
  1709. return builder.getVectorType( this.nodeType );
  1710. }
  1711. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1712. }
  1713. generate( builder, output ) {
  1714. const type = this.getNodeType( builder );
  1715. const maxLength = builder.getTypeLength( type );
  1716. const nodes = this.nodes;
  1717. const primitiveType = builder.getComponentType( type );
  1718. const snippetValues = [];
  1719. let length = 0;
  1720. for ( const input of nodes ) {
  1721. if ( length >= maxLength ) {
  1722. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1723. break;
  1724. }
  1725. let inputType = input.getNodeType( builder );
  1726. let inputTypeLength = builder.getTypeLength( inputType );
  1727. let inputSnippet;
  1728. if ( length + inputTypeLength > maxLength ) {
  1729. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1730. inputTypeLength = maxLength - length;
  1731. inputType = builder.getTypeFromLength( inputTypeLength );
  1732. }
  1733. length += inputTypeLength;
  1734. inputSnippet = input.build( builder, inputType );
  1735. const inputPrimitiveType = builder.getComponentType( inputType );
  1736. if ( inputPrimitiveType !== primitiveType ) {
  1737. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  1738. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  1739. }
  1740. snippetValues.push( inputSnippet );
  1741. }
  1742. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1743. return builder.format( snippet, type, output );
  1744. }
  1745. }
  1746. const _stringVectorComponents = vectorComponents.join( '' );
  1747. /**
  1748. * This module is part of the TSL core and usually not used in app level code.
  1749. * `SplitNode` represents a property access operation which means it is
  1750. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1751. * For example:
  1752. * ```js
  1753. * const redValue = color.r;
  1754. * ```
  1755. *
  1756. * @augments Node
  1757. */
  1758. class SplitNode extends Node {
  1759. static get type() {
  1760. return 'SplitNode';
  1761. }
  1762. /**
  1763. * Constructs a new split node.
  1764. *
  1765. * @param {Node} node - The node that should be accessed.
  1766. * @param {string} [components='x'] - The components that should be accessed.
  1767. */
  1768. constructor( node, components = 'x' ) {
  1769. super();
  1770. /**
  1771. * The node that should be accessed.
  1772. *
  1773. * @type {Node}
  1774. */
  1775. this.node = node;
  1776. /**
  1777. * The components that should be accessed.
  1778. *
  1779. * @type {string}
  1780. */
  1781. this.components = components;
  1782. /**
  1783. * This flag can be used for type testing.
  1784. *
  1785. * @type {boolean}
  1786. * @readonly
  1787. * @default true
  1788. */
  1789. this.isSplitNode = true;
  1790. }
  1791. /**
  1792. * Returns the vector length which is computed based on the requested components.
  1793. *
  1794. * @return {number} The vector length.
  1795. */
  1796. getVectorLength() {
  1797. let vectorLength = this.components.length;
  1798. for ( const c of this.components ) {
  1799. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1800. }
  1801. return vectorLength;
  1802. }
  1803. /**
  1804. * Returns the component type of the node's type.
  1805. *
  1806. * @param {NodeBuilder} builder - The current node builder.
  1807. * @return {string} The component type.
  1808. */
  1809. getComponentType( builder ) {
  1810. return builder.getComponentType( this.node.getNodeType( builder ) );
  1811. }
  1812. /**
  1813. * This method is overwritten since the node type is inferred from requested components.
  1814. *
  1815. * @param {NodeBuilder} builder - The current node builder.
  1816. * @return {string} The node type.
  1817. */
  1818. getNodeType( builder ) {
  1819. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1820. }
  1821. /**
  1822. * Returns the scope of the node.
  1823. *
  1824. * @return {Node} The scope of the node.
  1825. */
  1826. getScope() {
  1827. return this.node.getScope();
  1828. }
  1829. generate( builder, output ) {
  1830. const node = this.node;
  1831. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1832. let snippet = null;
  1833. if ( nodeTypeLength > 1 ) {
  1834. let type = null;
  1835. const componentsLength = this.getVectorLength();
  1836. if ( componentsLength >= nodeTypeLength ) {
  1837. // needed expand the input node
  1838. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1839. }
  1840. const nodeSnippet = node.build( builder, type );
  1841. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1842. // unnecessary swizzle
  1843. snippet = builder.format( nodeSnippet, type, output );
  1844. } else {
  1845. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1846. }
  1847. } else {
  1848. // ignore .components if .node returns float/integer
  1849. snippet = node.build( builder, output );
  1850. }
  1851. return snippet;
  1852. }
  1853. serialize( data ) {
  1854. super.serialize( data );
  1855. data.components = this.components;
  1856. }
  1857. deserialize( data ) {
  1858. super.deserialize( data );
  1859. this.components = data.components;
  1860. }
  1861. }
  1862. /**
  1863. * This module is part of the TSL core and usually not used in app level code.
  1864. * `SetNode` represents a set operation which means it is used to implement any
  1865. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1866. * For example:
  1867. * ```js
  1868. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1869. * ```
  1870. *
  1871. * @augments TempNode
  1872. */
  1873. class SetNode extends TempNode {
  1874. static get type() {
  1875. return 'SetNode';
  1876. }
  1877. /**
  1878. * Constructs a new set node.
  1879. *
  1880. * @param {Node} sourceNode - The node that should be updated.
  1881. * @param {string} components - The components that should be updated.
  1882. * @param {Node} targetNode - The value node.
  1883. */
  1884. constructor( sourceNode, components, targetNode ) {
  1885. super();
  1886. /**
  1887. * The node that should be updated.
  1888. *
  1889. * @type {Node}
  1890. */
  1891. this.sourceNode = sourceNode;
  1892. /**
  1893. * The components that should be updated.
  1894. *
  1895. * @type {string}
  1896. */
  1897. this.components = components;
  1898. /**
  1899. * The value node.
  1900. *
  1901. * @type {Node}
  1902. */
  1903. this.targetNode = targetNode;
  1904. }
  1905. /**
  1906. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1907. *
  1908. * @param {NodeBuilder} builder - The current node builder.
  1909. * @return {string} The node type.
  1910. */
  1911. getNodeType( builder ) {
  1912. return this.sourceNode.getNodeType( builder );
  1913. }
  1914. generate( builder ) {
  1915. const { sourceNode, components, targetNode } = this;
  1916. const sourceType = this.getNodeType( builder );
  1917. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1918. const targetType = builder.getTypeFromLength( components.length, componentType );
  1919. const targetSnippet = targetNode.build( builder, targetType );
  1920. const sourceSnippet = sourceNode.build( builder, sourceType );
  1921. const length = builder.getTypeLength( sourceType );
  1922. const snippetValues = [];
  1923. for ( let i = 0; i < length; i ++ ) {
  1924. const component = vectorComponents[ i ];
  1925. if ( component === components[ 0 ] ) {
  1926. snippetValues.push( targetSnippet );
  1927. i += components.length - 1;
  1928. } else {
  1929. snippetValues.push( sourceSnippet + '.' + component );
  1930. }
  1931. }
  1932. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1933. }
  1934. }
  1935. /**
  1936. * This module is part of the TSL core and usually not used in app level code.
  1937. * It represents a flip operation during the shader generation process
  1938. * meaning it flips normalized values with the following formula:
  1939. * ```
  1940. * x = 1 - x;
  1941. * ```
  1942. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1943. * `flipSTPQ()` method invocations on node objects. For example:
  1944. * ```js
  1945. * uvNode = uvNode.flipY();
  1946. * ```
  1947. *
  1948. * @augments TempNode
  1949. */
  1950. class FlipNode extends TempNode {
  1951. static get type() {
  1952. return 'FlipNode';
  1953. }
  1954. /**
  1955. * Constructs a new flip node.
  1956. *
  1957. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1958. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1959. */
  1960. constructor( sourceNode, components ) {
  1961. super();
  1962. /**
  1963. * The node which component(s) should be flipped.
  1964. *
  1965. * @type {Node}
  1966. */
  1967. this.sourceNode = sourceNode;
  1968. /**
  1969. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1970. *
  1971. * @type {string}
  1972. */
  1973. this.components = components;
  1974. }
  1975. /**
  1976. * This method is overwritten since the node type is inferred from the source node.
  1977. *
  1978. * @param {NodeBuilder} builder - The current node builder.
  1979. * @return {string} The node type.
  1980. */
  1981. getNodeType( builder ) {
  1982. return this.sourceNode.getNodeType( builder );
  1983. }
  1984. generate( builder ) {
  1985. const { components, sourceNode } = this;
  1986. const sourceType = this.getNodeType( builder );
  1987. const sourceSnippet = sourceNode.build( builder );
  1988. const sourceCache = builder.getVarFromNode( this );
  1989. const sourceProperty = builder.getPropertyName( sourceCache );
  1990. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1991. const length = builder.getTypeLength( sourceType );
  1992. const snippetValues = [];
  1993. let componentIndex = 0;
  1994. for ( let i = 0; i < length; i ++ ) {
  1995. const component = vectorComponents[ i ];
  1996. if ( component === components[ componentIndex ] ) {
  1997. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1998. componentIndex ++;
  1999. } else {
  2000. snippetValues.push( sourceProperty + '.' + component );
  2001. }
  2002. }
  2003. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2004. }
  2005. }
  2006. /**
  2007. * Base class for representing data input nodes.
  2008. *
  2009. * @augments Node
  2010. */
  2011. class InputNode extends Node {
  2012. static get type() {
  2013. return 'InputNode';
  2014. }
  2015. /**
  2016. * Constructs a new input node.
  2017. *
  2018. * @param {any} value - The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2019. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2020. */
  2021. constructor( value, nodeType = null ) {
  2022. super( nodeType );
  2023. /**
  2024. * This flag can be used for type testing.
  2025. *
  2026. * @type {boolean}
  2027. * @readonly
  2028. * @default true
  2029. */
  2030. this.isInputNode = true;
  2031. /**
  2032. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2033. *
  2034. * @type {any}
  2035. */
  2036. this.value = value;
  2037. /**
  2038. * The precision of the value in the shader.
  2039. *
  2040. * @type {?('low'|'medium'|'high')}
  2041. * @default null
  2042. */
  2043. this.precision = null;
  2044. }
  2045. getNodeType( /*builder*/ ) {
  2046. if ( this.nodeType === null ) {
  2047. return getValueType( this.value );
  2048. }
  2049. return this.nodeType;
  2050. }
  2051. /**
  2052. * Returns the input type of the node which is by default the node type. Derived modules
  2053. * might overwrite this method and use a fixed type or compute one analytically.
  2054. *
  2055. * A typical example for different input and node types are textures. The input type of a
  2056. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2057. *
  2058. * @param {NodeBuilder} builder - The current node builder.
  2059. * @return {string} The input type.
  2060. */
  2061. getInputType( builder ) {
  2062. return this.getNodeType( builder );
  2063. }
  2064. /**
  2065. * Sets the precision to the given value. The method can be
  2066. * overwritten in derived classes if the final precision must be computed
  2067. * analytically.
  2068. *
  2069. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2070. * @return {InputNode} A reference to this node.
  2071. */
  2072. setPrecision( precision ) {
  2073. this.precision = precision;
  2074. return this;
  2075. }
  2076. serialize( data ) {
  2077. super.serialize( data );
  2078. data.value = this.value;
  2079. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2080. data.valueType = getValueType( this.value );
  2081. data.nodeType = this.nodeType;
  2082. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2083. data.precision = this.precision;
  2084. }
  2085. deserialize( data ) {
  2086. super.deserialize( data );
  2087. this.nodeType = data.nodeType;
  2088. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2089. this.precision = data.precision || null;
  2090. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2091. }
  2092. generate( /*builder, output*/ ) {
  2093. warn( 'Abstract function.' );
  2094. }
  2095. }
  2096. const _regNum = /float|u?int/;
  2097. /**
  2098. * Class for representing a constant value in the shader.
  2099. *
  2100. * @augments InputNode
  2101. */
  2102. class ConstNode extends InputNode {
  2103. static get type() {
  2104. return 'ConstNode';
  2105. }
  2106. /**
  2107. * Constructs a new input node.
  2108. *
  2109. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2110. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2111. */
  2112. constructor( value, nodeType = null ) {
  2113. super( value, nodeType );
  2114. /**
  2115. * This flag can be used for type testing.
  2116. *
  2117. * @type {boolean}
  2118. * @readonly
  2119. * @default true
  2120. */
  2121. this.isConstNode = true;
  2122. }
  2123. /**
  2124. * Generates the shader string of the value with the current node builder.
  2125. *
  2126. * @param {NodeBuilder} builder - The current node builder.
  2127. * @return {string} The generated value as a shader string.
  2128. */
  2129. generateConst( builder ) {
  2130. return builder.generateConst( this.getNodeType( builder ), this.value );
  2131. }
  2132. generate( builder, output ) {
  2133. const type = this.getNodeType( builder );
  2134. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2135. return builder.generateConst( output, this.value );
  2136. }
  2137. return builder.format( this.generateConst( builder ), type, output );
  2138. }
  2139. }
  2140. /**
  2141. * Base class for representing member access on an object-like
  2142. * node data structures.
  2143. *
  2144. * @augments Node
  2145. */
  2146. class MemberNode extends Node {
  2147. static get type() {
  2148. return 'MemberNode';
  2149. }
  2150. /**
  2151. * Constructs a member node.
  2152. *
  2153. * @param {Node} structNode - The struct node.
  2154. * @param {string} property - The property name.
  2155. */
  2156. constructor( structNode, property ) {
  2157. super();
  2158. /**
  2159. * The struct node.
  2160. *
  2161. * @type {Node}
  2162. */
  2163. this.structNode = structNode;
  2164. /**
  2165. * The property name.
  2166. *
  2167. * @type {Node}
  2168. */
  2169. this.property = property;
  2170. /**
  2171. * This flag can be used for type testing.
  2172. *
  2173. * @type {boolean}
  2174. * @readonly
  2175. * @default true
  2176. */
  2177. this.isMemberNode = true;
  2178. }
  2179. hasMember( builder ) {
  2180. if ( this.structNode.isMemberNode ) {
  2181. if ( this.structNode.hasMember( builder ) === false ) {
  2182. return false;
  2183. }
  2184. }
  2185. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2186. }
  2187. getNodeType( builder ) {
  2188. if ( this.hasMember( builder ) === false ) {
  2189. // default type if member does not exist
  2190. return 'float';
  2191. }
  2192. return this.structNode.getMemberType( builder, this.property );
  2193. }
  2194. getMemberType( builder, name ) {
  2195. if ( this.hasMember( builder ) === false ) {
  2196. // default type if member does not exist
  2197. return 'float';
  2198. }
  2199. const type = this.getNodeType( builder );
  2200. const struct = builder.getStructTypeNode( type );
  2201. return struct.getMemberType( builder, name );
  2202. }
  2203. generate( builder ) {
  2204. if ( this.hasMember( builder ) === false ) {
  2205. warn( `TSL: Member "${ this.property }" does not exist in struct.` );
  2206. const type = this.getNodeType( builder );
  2207. return builder.generateConst( type );
  2208. }
  2209. const propertyName = this.structNode.build( builder );
  2210. return propertyName + '.' + this.property;
  2211. }
  2212. }
  2213. let currentStack = null;
  2214. const NodeElements = new Map();
  2215. // Extend Node Class for TSL using prototype
  2216. function addMethodChaining( name, nodeElement ) {
  2217. if ( NodeElements.has( name ) ) {
  2218. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2219. return;
  2220. }
  2221. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2222. NodeElements.set( name, nodeElement );
  2223. if ( name !== 'assign' ) {
  2224. // Changing Node prototype to add method chaining
  2225. Node.prototype[ name ] = function ( ...params ) {
  2226. //if ( name === 'toVarIntent' ) return this;
  2227. return this.isStackNode ? this.addToStack( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2228. };
  2229. // Adding assign method chaining
  2230. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2231. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2232. };
  2233. }
  2234. }
  2235. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2236. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2237. Node.prototype.assign = function ( ...params ) {
  2238. if ( this.isStackNode !== true ) {
  2239. if ( currentStack !== null ) {
  2240. currentStack.assign( this, ...params );
  2241. } else {
  2242. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().' );
  2243. }
  2244. return this;
  2245. } else {
  2246. const nodeElement = NodeElements.get( 'assign' );
  2247. return this.addToStack( nodeElement( ...params ) );
  2248. }
  2249. };
  2250. Node.prototype.toVarIntent = function () {
  2251. return this;
  2252. };
  2253. Node.prototype.get = function ( value ) {
  2254. return new MemberNode( this, value );
  2255. };
  2256. // Cache prototype for TSL
  2257. const proto = {};
  2258. // Set swizzle properties for xyzw, rgba, and stpq.
  2259. function setProtoSwizzle( property, altA, altB ) {
  2260. // swizzle properties
  2261. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2262. get() {
  2263. this._cache = this._cache || {};
  2264. //
  2265. let split = this._cache[ property ];
  2266. if ( split === undefined ) {
  2267. split = new SplitNode( this, property );
  2268. this._cache[ property ] = split;
  2269. }
  2270. return split;
  2271. },
  2272. set( value ) {
  2273. this[ property ].assign( nodeObject( value ) );
  2274. }
  2275. };
  2276. // set properties ( swizzle ) and sort to xyzw sequence
  2277. const propUpper = property.toUpperCase();
  2278. const altAUpper = altA.toUpperCase();
  2279. const altBUpper = altB.toUpperCase();
  2280. // Set methods for swizzle properties
  2281. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2282. const swizzle = parseSwizzleAndSort( property );
  2283. return new SetNode( this, swizzle, nodeObject( value ) );
  2284. };
  2285. // Set methods for flip properties
  2286. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2287. const swizzle = parseSwizzleAndSort( property );
  2288. return new FlipNode( this, swizzle );
  2289. };
  2290. }
  2291. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2292. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2293. const swizzleC = [ 's', 't', 'p', 'q' ];
  2294. for ( let a = 0; a < 4; a ++ ) {
  2295. let prop = swizzleA[ a ];
  2296. let altA = swizzleB[ a ];
  2297. let altB = swizzleC[ a ];
  2298. setProtoSwizzle( prop, altA, altB );
  2299. for ( let b = 0; b < 4; b ++ ) {
  2300. prop = swizzleA[ a ] + swizzleA[ b ];
  2301. altA = swizzleB[ a ] + swizzleB[ b ];
  2302. altB = swizzleC[ a ] + swizzleC[ b ];
  2303. setProtoSwizzle( prop, altA, altB );
  2304. for ( let c = 0; c < 4; c ++ ) {
  2305. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2306. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2307. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2308. setProtoSwizzle( prop, altA, altB );
  2309. for ( let d = 0; d < 4; d ++ ) {
  2310. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2311. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2312. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2313. setProtoSwizzle( prop, altA, altB );
  2314. }
  2315. }
  2316. }
  2317. }
  2318. // Set/get static properties for array elements (0-31).
  2319. for ( let i = 0; i < 32; i ++ ) {
  2320. proto[ i ] = {
  2321. get() {
  2322. this._cache = this._cache || {};
  2323. //
  2324. let element = this._cache[ i ];
  2325. if ( element === undefined ) {
  2326. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2327. this._cache[ i ] = element;
  2328. }
  2329. return element;
  2330. },
  2331. set( value ) {
  2332. this[ i ].assign( nodeObject( value ) );
  2333. }
  2334. };
  2335. }
  2336. /*
  2337. // Set properties for width, height, and depth.
  2338. function setProtoProperty( property, target ) {
  2339. proto[ property ] = {
  2340. get() {
  2341. this._cache = this._cache || {};
  2342. //
  2343. let split = this._cache[ target ];
  2344. if ( split === undefined ) {
  2345. split = new SplitNode( this, target );
  2346. this._cache[ target ] = split;
  2347. }
  2348. return split;
  2349. },
  2350. set( value ) {
  2351. this[ target ].assign( nodeObject( value ) );
  2352. }
  2353. };
  2354. }
  2355. setProtoProperty( 'width', 'x' );
  2356. setProtoProperty( 'height', 'y' );
  2357. setProtoProperty( 'depth', 'z' );
  2358. */
  2359. Object.defineProperties( Node.prototype, proto );
  2360. // --- FINISH ---
  2361. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2362. const ShaderNodeObject = function ( obj, altType = null ) {
  2363. const type = getValueType( obj );
  2364. if ( type === 'node' ) {
  2365. return obj;
  2366. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2367. return nodeObject( getConstNode( obj, altType ) );
  2368. } else if ( type === 'shader' ) {
  2369. return obj.isFn ? obj : Fn( obj );
  2370. }
  2371. return obj;
  2372. };
  2373. const ShaderNodeObjects = function ( objects, altType = null ) {
  2374. for ( const name in objects ) {
  2375. objects[ name ] = nodeObject( objects[ name ], altType );
  2376. }
  2377. return objects;
  2378. };
  2379. const ShaderNodeArray = function ( array, altType = null ) {
  2380. const len = array.length;
  2381. for ( let i = 0; i < len; i ++ ) {
  2382. array[ i ] = nodeObject( array[ i ], altType );
  2383. }
  2384. return array;
  2385. };
  2386. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2387. function assignNode( node ) {
  2388. if ( settings !== null ) {
  2389. node = nodeObject( Object.assign( node, settings ) );
  2390. if ( settings.intent === true ) {
  2391. node = node.toVarIntent();
  2392. }
  2393. } else {
  2394. node = nodeObject( node );
  2395. }
  2396. return node;
  2397. }
  2398. let fn, name = scope, minParams, maxParams;
  2399. function verifyParamsLimit( params ) {
  2400. let tslName;
  2401. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2402. else tslName = NodeClass.type;
  2403. if ( minParams !== undefined && params.length < minParams ) {
  2404. error( `TSL: "${ tslName }" parameter length is less than minimum required.` );
  2405. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2406. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2407. error( `TSL: "${ tslName }" parameter length exceeds limit.` );
  2408. return params.slice( 0, maxParams );
  2409. }
  2410. return params;
  2411. }
  2412. if ( scope === null ) {
  2413. fn = ( ...params ) => {
  2414. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2415. };
  2416. } else if ( factor !== null ) {
  2417. factor = nodeObject( factor );
  2418. fn = ( ...params ) => {
  2419. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2420. };
  2421. } else {
  2422. fn = ( ...params ) => {
  2423. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2424. };
  2425. }
  2426. fn.setParameterLength = ( ...params ) => {
  2427. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2428. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2429. return fn;
  2430. };
  2431. fn.setName = ( value ) => {
  2432. name = value;
  2433. return fn;
  2434. };
  2435. return fn;
  2436. };
  2437. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2438. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2439. };
  2440. class ShaderCallNodeInternal extends Node {
  2441. constructor( shaderNode, rawInputs ) {
  2442. super();
  2443. this.shaderNode = shaderNode;
  2444. this.rawInputs = rawInputs;
  2445. this.isShaderCallNodeInternal = true;
  2446. }
  2447. getNodeType( builder ) {
  2448. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2449. }
  2450. getElementType( builder ) {
  2451. return this.getOutputNode( builder ).getElementType( builder );
  2452. }
  2453. getMemberType( builder, name ) {
  2454. return this.getOutputNode( builder ).getMemberType( builder, name );
  2455. }
  2456. call( builder ) {
  2457. const { shaderNode, rawInputs } = this;
  2458. const properties = builder.getNodeProperties( shaderNode );
  2459. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2460. const subBuildProperty = subBuild || 'default';
  2461. if ( properties[ subBuildProperty ] ) {
  2462. return properties[ subBuildProperty ];
  2463. }
  2464. //
  2465. const previousSubBuildFn = builder.subBuildFn;
  2466. const previousFnCall = builder.fnCall;
  2467. builder.subBuildFn = subBuild;
  2468. builder.fnCall = this;
  2469. let result = null;
  2470. if ( shaderNode.layout ) {
  2471. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2472. if ( functionNodesCacheMap === undefined ) {
  2473. functionNodesCacheMap = new WeakMap();
  2474. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2475. }
  2476. let functionNode = functionNodesCacheMap.get( shaderNode );
  2477. if ( functionNode === undefined ) {
  2478. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2479. functionNodesCacheMap.set( shaderNode, functionNode );
  2480. }
  2481. builder.addInclude( functionNode );
  2482. //
  2483. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2484. result = nodeObject( functionNode.call( inputs ) );
  2485. } else {
  2486. const secureNodeBuilder = new Proxy( builder, {
  2487. get: ( target, property, receiver ) => {
  2488. let value;
  2489. if ( Symbol.iterator === property ) {
  2490. value = function* () {
  2491. yield undefined;
  2492. };
  2493. } else {
  2494. value = Reflect.get( target, property, receiver );
  2495. }
  2496. return value;
  2497. }
  2498. } );
  2499. //
  2500. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2501. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2502. const jsFunc = shaderNode.jsFunc;
  2503. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2504. result = nodeObject( outputNode );
  2505. }
  2506. builder.subBuildFn = previousSubBuildFn;
  2507. builder.fnCall = previousFnCall;
  2508. if ( shaderNode.once ) {
  2509. properties[ subBuildProperty ] = result;
  2510. }
  2511. return result;
  2512. }
  2513. setupOutput( builder ) {
  2514. builder.addStack();
  2515. builder.stack.outputNode = this.call( builder );
  2516. return builder.removeStack();
  2517. }
  2518. getOutputNode( builder ) {
  2519. const properties = builder.getNodeProperties( this );
  2520. const subBuildOutput = builder.getSubBuildOutput( this );
  2521. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2522. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2523. return properties[ subBuildOutput ];
  2524. }
  2525. build( builder, output = null ) {
  2526. let result = null;
  2527. const buildStage = builder.getBuildStage();
  2528. const properties = builder.getNodeProperties( this );
  2529. const subBuildOutput = builder.getSubBuildOutput( this );
  2530. const outputNode = this.getOutputNode( builder );
  2531. const previousFnCall = builder.fnCall;
  2532. builder.fnCall = this;
  2533. if ( buildStage === 'setup' ) {
  2534. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2535. if ( properties[ subBuildInitialized ] !== true ) {
  2536. properties[ subBuildInitialized ] = true;
  2537. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2538. properties[ subBuildOutput ].build( builder );
  2539. // If the shaderNode has subBuilds, add them to the chaining nodes
  2540. // so they can be built later in the build process.
  2541. if ( this.shaderNode.subBuilds ) {
  2542. for ( const node of builder.chaining ) {
  2543. const nodeData = builder.getDataFromNode( node, 'any' );
  2544. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2545. for ( const subBuild of this.shaderNode.subBuilds ) {
  2546. nodeData.subBuilds.add( subBuild );
  2547. }
  2548. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2549. }
  2550. }
  2551. }
  2552. result = properties[ subBuildOutput ];
  2553. } else if ( buildStage === 'analyze' ) {
  2554. outputNode.build( builder, output );
  2555. } else if ( buildStage === 'generate' ) {
  2556. result = outputNode.build( builder, output ) || '';
  2557. }
  2558. builder.fnCall = previousFnCall;
  2559. return result;
  2560. }
  2561. }
  2562. function getLayoutParameters( params ) {
  2563. let output;
  2564. nodeObjects( params );
  2565. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2566. if ( isArrayAsParameter ) {
  2567. output = [ ...params ];
  2568. } else {
  2569. output = params[ 0 ];
  2570. }
  2571. return output;
  2572. }
  2573. function getProxyParameters( params ) {
  2574. let index = 0;
  2575. nodeObjects( params );
  2576. return new Proxy( params, {
  2577. get: ( target, property, receiver ) => {
  2578. let value;
  2579. if ( property === 'length' ) {
  2580. value = params.length;
  2581. return value;
  2582. }
  2583. if ( Symbol.iterator === property ) {
  2584. value = function* () {
  2585. for ( const inputNode of params ) {
  2586. yield nodeObject( inputNode );
  2587. }
  2588. };
  2589. } else {
  2590. if ( params.length > 0 ) {
  2591. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2592. const objectTarget = params[ 0 ];
  2593. if ( objectTarget[ property ] === undefined ) {
  2594. value = objectTarget[ index ++ ];
  2595. } else {
  2596. value = Reflect.get( objectTarget, property, receiver );
  2597. }
  2598. } else if ( params[ 0 ] instanceof Node ) {
  2599. if ( params[ property ] === undefined ) {
  2600. value = params[ index ++ ];
  2601. } else {
  2602. value = Reflect.get( params, property, receiver );
  2603. }
  2604. }
  2605. } else {
  2606. value = Reflect.get( target, property, receiver );
  2607. }
  2608. value = nodeObject( value );
  2609. }
  2610. return value;
  2611. }
  2612. } );
  2613. }
  2614. class ShaderNodeInternal extends Node {
  2615. constructor( jsFunc, nodeType ) {
  2616. super( nodeType );
  2617. this.jsFunc = jsFunc;
  2618. this.layout = null;
  2619. this.global = true;
  2620. this.once = false;
  2621. }
  2622. setLayout( layout ) {
  2623. this.layout = layout;
  2624. return this;
  2625. }
  2626. getLayout() {
  2627. return this.layout;
  2628. }
  2629. call( rawInputs = null ) {
  2630. return new ShaderCallNodeInternal( this, rawInputs );
  2631. }
  2632. setup() {
  2633. return this.call();
  2634. }
  2635. }
  2636. const bools = [ false, true ];
  2637. const uints = [ 0, 1, 2, 3 ];
  2638. const ints = [ -1, -2 ];
  2639. const floats = [ 0.5, 1.5, 1 / 3, 1e-6, 1e6, Math.PI, Math.PI * 2, 1 / Math.PI, 2 / Math.PI, 1 / ( Math.PI * 2 ), Math.PI / 2 ];
  2640. const boolsCacheMap = new Map();
  2641. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2642. const uintsCacheMap = new Map();
  2643. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2644. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2645. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2646. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2647. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2648. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2649. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2650. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2651. const getConstNode = ( value, type ) => {
  2652. if ( constNodesCacheMap.has( value ) ) {
  2653. return constNodesCacheMap.get( value );
  2654. } else if ( value.isNode === true ) {
  2655. return value;
  2656. } else {
  2657. return new ConstNode( value, type );
  2658. }
  2659. };
  2660. const ConvertType = function ( type, cacheMap = null ) {
  2661. return ( ...params ) => {
  2662. for ( const param of params ) {
  2663. if ( param === undefined ) {
  2664. error( `TSL: Invalid parameter for the type "${ type }".` );
  2665. return nodeObject( new ConstNode( 0, type ) );
  2666. }
  2667. }
  2668. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2669. const paramType = typeof param;
  2670. return paramType !== 'object' && paramType !== 'function';
  2671. } ) ) ) {
  2672. params = [ getValueFromType( type, ...params ) ];
  2673. }
  2674. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2675. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2676. }
  2677. if ( params.length === 1 ) {
  2678. const node = getConstNode( params[ 0 ], type );
  2679. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2680. return nodeObjectIntent( new ConvertNode( node, type ) );
  2681. }
  2682. const nodes = params.map( param => getConstNode( param ) );
  2683. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2684. };
  2685. };
  2686. // exports
  2687. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2688. // utils
  2689. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2690. // shader node base
  2691. function ShaderNode( jsFunc, nodeType ) {
  2692. return new ShaderNodeInternal( jsFunc, nodeType );
  2693. }
  2694. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2695. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2696. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2697. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2698. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2699. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2700. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { ...settings, intent: true } );
  2701. let fnId = 0;
  2702. class FnNode extends Node {
  2703. constructor( jsFunc, layout = null ) {
  2704. super();
  2705. let nodeType = null;
  2706. if ( layout !== null ) {
  2707. if ( typeof layout === 'object' ) {
  2708. nodeType = layout.return;
  2709. } else {
  2710. if ( typeof layout === 'string' ) {
  2711. nodeType = layout;
  2712. } else {
  2713. error( 'TSL: Invalid layout type.' );
  2714. }
  2715. layout = null;
  2716. }
  2717. }
  2718. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2719. if ( layout !== null ) {
  2720. this.setLayout( layout );
  2721. }
  2722. this.isFn = true;
  2723. }
  2724. setLayout( layout ) {
  2725. const nodeType = this.shaderNode.nodeType;
  2726. if ( typeof layout.inputs !== 'object' ) {
  2727. const fullLayout = {
  2728. name: 'fn' + fnId ++,
  2729. type: nodeType,
  2730. inputs: []
  2731. };
  2732. for ( const name in layout ) {
  2733. if ( name === 'return' ) continue;
  2734. fullLayout.inputs.push( {
  2735. name: name,
  2736. type: layout[ name ]
  2737. } );
  2738. }
  2739. layout = fullLayout;
  2740. }
  2741. this.shaderNode.setLayout( layout );
  2742. return this;
  2743. }
  2744. getNodeType( builder ) {
  2745. return this.shaderNode.getNodeType( builder ) || 'float';
  2746. }
  2747. call( ...params ) {
  2748. const fnCall = this.shaderNode.call( params );
  2749. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2750. return fnCall.toVarIntent();
  2751. }
  2752. once( subBuilds = null ) {
  2753. this.shaderNode.once = true;
  2754. this.shaderNode.subBuilds = subBuilds;
  2755. return this;
  2756. }
  2757. generate( builder ) {
  2758. const type = this.getNodeType( builder );
  2759. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2760. return builder.generateConst( type );
  2761. }
  2762. }
  2763. function Fn( jsFunc, layout = null ) {
  2764. const instance = new FnNode( jsFunc, layout );
  2765. return new Proxy( () => {}, {
  2766. apply( target, thisArg, params ) {
  2767. return instance.call( ...params );
  2768. },
  2769. get( target, prop, receiver ) {
  2770. return Reflect.get( instance, prop, receiver );
  2771. },
  2772. set( target, prop, value, receiver ) {
  2773. return Reflect.set( instance, prop, value, receiver );
  2774. }
  2775. } );
  2776. }
  2777. //
  2778. const setCurrentStack = ( stack ) => {
  2779. currentStack = stack;
  2780. };
  2781. const getCurrentStack = () => currentStack;
  2782. /**
  2783. * Represent a conditional node using if/else statements.
  2784. *
  2785. * ```js
  2786. * If( condition, function )
  2787. * .ElseIf( condition, function )
  2788. * .Else( function )
  2789. * ```
  2790. * @tsl
  2791. * @function
  2792. * @param {...any} params - The parameters for the conditional node.
  2793. * @returns {StackNode} The conditional node.
  2794. */
  2795. const If = ( ...params ) => currentStack.If( ...params );
  2796. /**
  2797. * Represent a conditional node using switch/case statements.
  2798. *
  2799. * ```js
  2800. * Switch( value )
  2801. * .Case( 1, function )
  2802. * .Case( 2, 3, 4, function )
  2803. * .Default( function )
  2804. * ```
  2805. * @tsl
  2806. * @function
  2807. * @param {...any} params - The parameters for the conditional node.
  2808. * @returns {StackNode} The conditional node.
  2809. */
  2810. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2811. /**
  2812. * Add the given node to the current stack.
  2813. *
  2814. * @param {Node} node - The node to add.
  2815. * @returns {Node} The node that was added to the stack.
  2816. */
  2817. function Stack( node ) {
  2818. if ( currentStack ) currentStack.addToStack( node );
  2819. return node;
  2820. }
  2821. addMethodChaining( 'toStack', Stack );
  2822. // types
  2823. const color = new ConvertType( 'color' );
  2824. const float = new ConvertType( 'float', cacheMaps.float );
  2825. const int = new ConvertType( 'int', cacheMaps.ints );
  2826. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2827. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2828. const vec2 = new ConvertType( 'vec2' );
  2829. const ivec2 = new ConvertType( 'ivec2' );
  2830. const uvec2 = new ConvertType( 'uvec2' );
  2831. const bvec2 = new ConvertType( 'bvec2' );
  2832. const vec3 = new ConvertType( 'vec3' );
  2833. const ivec3 = new ConvertType( 'ivec3' );
  2834. const uvec3 = new ConvertType( 'uvec3' );
  2835. const bvec3 = new ConvertType( 'bvec3' );
  2836. const vec4 = new ConvertType( 'vec4' );
  2837. const ivec4 = new ConvertType( 'ivec4' );
  2838. const uvec4 = new ConvertType( 'uvec4' );
  2839. const bvec4 = new ConvertType( 'bvec4' );
  2840. const mat2 = new ConvertType( 'mat2' );
  2841. const mat3 = new ConvertType( 'mat3' );
  2842. const mat4 = new ConvertType( 'mat4' );
  2843. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2844. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2845. addMethodChaining( 'toColor', color );
  2846. addMethodChaining( 'toFloat', float );
  2847. addMethodChaining( 'toInt', int );
  2848. addMethodChaining( 'toUint', uint );
  2849. addMethodChaining( 'toBool', bool );
  2850. addMethodChaining( 'toVec2', vec2 );
  2851. addMethodChaining( 'toIVec2', ivec2 );
  2852. addMethodChaining( 'toUVec2', uvec2 );
  2853. addMethodChaining( 'toBVec2', bvec2 );
  2854. addMethodChaining( 'toVec3', vec3 );
  2855. addMethodChaining( 'toIVec3', ivec3 );
  2856. addMethodChaining( 'toUVec3', uvec3 );
  2857. addMethodChaining( 'toBVec3', bvec3 );
  2858. addMethodChaining( 'toVec4', vec4 );
  2859. addMethodChaining( 'toIVec4', ivec4 );
  2860. addMethodChaining( 'toUVec4', uvec4 );
  2861. addMethodChaining( 'toBVec4', bvec4 );
  2862. addMethodChaining( 'toMat2', mat2 );
  2863. addMethodChaining( 'toMat3', mat3 );
  2864. addMethodChaining( 'toMat4', mat4 );
  2865. // basic nodes
  2866. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2867. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2868. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2869. addMethodChaining( 'element', element );
  2870. addMethodChaining( 'convert', convert );
  2871. // deprecated
  2872. /**
  2873. * @tsl
  2874. * @function
  2875. * @deprecated since r176. Use {@link Stack} instead.
  2876. *
  2877. * @param {Node} node - The node to add.
  2878. * @returns {Function}
  2879. */
  2880. const append = ( node ) => { // @deprecated, r176
  2881. warn( 'TSL: append() has been renamed to Stack().' );
  2882. return Stack( node );
  2883. };
  2884. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2885. warn( 'TSL: .append() has been renamed to .toStack().' );
  2886. return Stack( node );
  2887. } );
  2888. /**
  2889. * This class represents a shader property. It can be used
  2890. * to explicitly define a property and assign a value to it.
  2891. *
  2892. * ```js
  2893. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2894. *```
  2895. * `PropertyNode` is used by the engine to predefined common material properties
  2896. * for TSL code.
  2897. *
  2898. * @augments Node
  2899. */
  2900. class PropertyNode extends Node {
  2901. static get type() {
  2902. return 'PropertyNode';
  2903. }
  2904. /**
  2905. * Constructs a new property node.
  2906. *
  2907. * @param {string} nodeType - The type of the node.
  2908. * @param {?string} [name=null] - The name of the property in the shader.
  2909. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2910. */
  2911. constructor( nodeType, name = null, varying = false ) {
  2912. super( nodeType );
  2913. /**
  2914. * The name of the property in the shader. If no name is defined,
  2915. * the node system auto-generates one.
  2916. *
  2917. * @type {?string}
  2918. * @default null
  2919. */
  2920. this.name = name;
  2921. /**
  2922. * Whether this property is a varying or not.
  2923. *
  2924. * @type {boolean}
  2925. * @default false
  2926. */
  2927. this.varying = varying;
  2928. /**
  2929. * This flag can be used for type testing.
  2930. *
  2931. * @type {boolean}
  2932. * @readonly
  2933. * @default true
  2934. */
  2935. this.isPropertyNode = true;
  2936. /**
  2937. * This flag is used for global cache.
  2938. *
  2939. * @type {boolean}
  2940. * @default true
  2941. */
  2942. this.global = true;
  2943. }
  2944. customCacheKey() {
  2945. return hashString( this.type + ':' + ( this.name || '' ) + ':' + ( this.varying ? '1' : '0' ) );
  2946. }
  2947. getHash( builder ) {
  2948. return this.name || super.getHash( builder );
  2949. }
  2950. generate( builder ) {
  2951. let nodeVar;
  2952. if ( this.varying === true ) {
  2953. nodeVar = builder.getVaryingFromNode( this, this.name );
  2954. nodeVar.needsInterpolation = true;
  2955. } else {
  2956. nodeVar = builder.getVarFromNode( this, this.name );
  2957. }
  2958. return builder.getPropertyName( nodeVar );
  2959. }
  2960. }
  2961. /**
  2962. * TSL function for creating a property node.
  2963. *
  2964. * @tsl
  2965. * @function
  2966. * @param {string} type - The type of the node.
  2967. * @param {?string} [name=null] - The name of the property in the shader.
  2968. * @returns {PropertyNode}
  2969. */
  2970. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2971. /**
  2972. * TSL function for creating a varying property node.
  2973. *
  2974. * @tsl
  2975. * @function
  2976. * @param {string} type - The type of the node.
  2977. * @param {?string} [name=null] - The name of the varying in the shader.
  2978. * @returns {PropertyNode}
  2979. */
  2980. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2981. /**
  2982. * TSL object that represents the shader variable `DiffuseColor`.
  2983. *
  2984. * @tsl
  2985. * @type {PropertyNode<vec4>}
  2986. */
  2987. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2988. /**
  2989. * TSL object that represents the shader variable `DiffuseContribution`.
  2990. *
  2991. * @tsl
  2992. * @type {PropertyNode<vec3>}
  2993. */
  2994. const diffuseContribution = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'DiffuseContribution' );
  2995. /**
  2996. * TSL object that represents the shader variable `EmissiveColor`.
  2997. *
  2998. * @tsl
  2999. * @type {PropertyNode<vec3>}
  3000. */
  3001. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  3002. /**
  3003. * TSL object that represents the shader variable `Roughness`.
  3004. *
  3005. * @tsl
  3006. * @type {PropertyNode<float>}
  3007. */
  3008. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  3009. /**
  3010. * TSL object that represents the shader variable `Metalness`.
  3011. *
  3012. * @tsl
  3013. * @type {PropertyNode<float>}
  3014. */
  3015. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  3016. /**
  3017. * TSL object that represents the shader variable `Clearcoat`.
  3018. *
  3019. * @tsl
  3020. * @type {PropertyNode<float>}
  3021. */
  3022. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  3023. /**
  3024. * TSL object that represents the shader variable `ClearcoatRoughness`.
  3025. *
  3026. * @tsl
  3027. * @type {PropertyNode<float>}
  3028. */
  3029. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3030. /**
  3031. * TSL object that represents the shader variable `Sheen`.
  3032. *
  3033. * @tsl
  3034. * @type {PropertyNode<vec3>}
  3035. */
  3036. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3037. /**
  3038. * TSL object that represents the shader variable `SheenRoughness`.
  3039. *
  3040. * @tsl
  3041. * @type {PropertyNode<float>}
  3042. */
  3043. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3044. /**
  3045. * TSL object that represents the shader variable `Iridescence`.
  3046. *
  3047. * @tsl
  3048. * @type {PropertyNode<float>}
  3049. */
  3050. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3051. /**
  3052. * TSL object that represents the shader variable `IridescenceIOR`.
  3053. *
  3054. * @tsl
  3055. * @type {PropertyNode<float>}
  3056. */
  3057. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3058. /**
  3059. * TSL object that represents the shader variable `IridescenceThickness`.
  3060. *
  3061. * @tsl
  3062. * @type {PropertyNode<float>}
  3063. */
  3064. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3065. /**
  3066. * TSL object that represents the shader variable `AlphaT`.
  3067. *
  3068. * @tsl
  3069. * @type {PropertyNode<float>}
  3070. */
  3071. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3072. /**
  3073. * TSL object that represents the shader variable `Anisotropy`.
  3074. *
  3075. * @tsl
  3076. * @type {PropertyNode<float>}
  3077. */
  3078. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3079. /**
  3080. * TSL object that represents the shader variable `AnisotropyT`.
  3081. *
  3082. * @tsl
  3083. * @type {PropertyNode<vec3>}
  3084. */
  3085. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3086. /**
  3087. * TSL object that represents the shader variable `AnisotropyB`.
  3088. *
  3089. * @tsl
  3090. * @type {PropertyNode<vec3>}
  3091. */
  3092. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3093. /**
  3094. * TSL object that represents the shader variable `SpecularColor`.
  3095. *
  3096. * @tsl
  3097. * @type {PropertyNode<color>}
  3098. */
  3099. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3100. /**
  3101. * TSL object that represents the shader variable `SpecularColorBlended`.
  3102. *
  3103. * @tsl
  3104. * @type {PropertyNode<color>}
  3105. */
  3106. const specularColorBlended = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColorBlended' );
  3107. /**
  3108. * TSL object that represents the shader variable `SpecularF90`.
  3109. *
  3110. * @tsl
  3111. * @type {PropertyNode<float>}
  3112. */
  3113. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3114. /**
  3115. * TSL object that represents the shader variable `Shininess`.
  3116. *
  3117. * @tsl
  3118. * @type {PropertyNode<float>}
  3119. */
  3120. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3121. /**
  3122. * TSL object that represents the shader variable `Output`.
  3123. *
  3124. * @tsl
  3125. * @type {PropertyNode<vec4>}
  3126. */
  3127. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3128. /**
  3129. * TSL object that represents the shader variable `dashSize`.
  3130. *
  3131. * @tsl
  3132. * @type {PropertyNode<float>}
  3133. */
  3134. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3135. /**
  3136. * TSL object that represents the shader variable `gapSize`.
  3137. *
  3138. * @tsl
  3139. * @type {PropertyNode<float>}
  3140. */
  3141. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3142. /**
  3143. * TSL object that represents the shader variable `pointWidth`.
  3144. *
  3145. * @tsl
  3146. * @type {PropertyNode<float>}
  3147. */
  3148. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3149. /**
  3150. * TSL object that represents the shader variable `IOR`.
  3151. *
  3152. * @tsl
  3153. * @type {PropertyNode<float>}
  3154. */
  3155. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3156. /**
  3157. * TSL object that represents the shader variable `Transmission`.
  3158. *
  3159. * @tsl
  3160. * @type {PropertyNode<float>}
  3161. */
  3162. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3163. /**
  3164. * TSL object that represents the shader variable `Thickness`.
  3165. *
  3166. * @tsl
  3167. * @type {PropertyNode<float>}
  3168. */
  3169. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3170. /**
  3171. * TSL object that represents the shader variable `AttenuationDistance`.
  3172. *
  3173. * @tsl
  3174. * @type {PropertyNode<float>}
  3175. */
  3176. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3177. /**
  3178. * TSL object that represents the shader variable `AttenuationColor`.
  3179. *
  3180. * @tsl
  3181. * @type {PropertyNode<color>}
  3182. */
  3183. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3184. /**
  3185. * TSL object that represents the shader variable `Dispersion`.
  3186. *
  3187. * @tsl
  3188. * @type {PropertyNode<float>}
  3189. */
  3190. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3191. /**
  3192. * This node can be used to group single instances of {@link UniformNode}
  3193. * and manage them as a uniform buffer.
  3194. *
  3195. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3196. * will be used when defining the {@link UniformNode#groupNode} property.
  3197. *
  3198. * - `objectGroup`: Uniform buffer per object.
  3199. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3200. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3201. *
  3202. * @augments Node
  3203. */
  3204. class UniformGroupNode extends Node {
  3205. static get type() {
  3206. return 'UniformGroupNode';
  3207. }
  3208. /**
  3209. * Constructs a new uniform group node.
  3210. *
  3211. * @param {string} name - The name of the uniform group node.
  3212. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3213. * @param {number} [order=1] - Influences the internal sorting.
  3214. */
  3215. constructor( name, shared = false, order = 1 ) {
  3216. super( 'string' );
  3217. /**
  3218. * The name of the uniform group node.
  3219. *
  3220. * @type {string}
  3221. */
  3222. this.name = name;
  3223. /**
  3224. * Whether this uniform group node is shared or not.
  3225. *
  3226. * @type {boolean}
  3227. * @default false
  3228. */
  3229. this.shared = shared;
  3230. /**
  3231. * Influences the internal sorting.
  3232. * TODO: Add details when this property should be changed.
  3233. *
  3234. * @type {number}
  3235. * @default 1
  3236. */
  3237. this.order = order;
  3238. /**
  3239. * This flag can be used for type testing.
  3240. *
  3241. * @type {boolean}
  3242. * @readonly
  3243. * @default true
  3244. */
  3245. this.isUniformGroup = true;
  3246. }
  3247. serialize( data ) {
  3248. super.serialize( data );
  3249. data.name = this.name;
  3250. data.version = this.version;
  3251. data.shared = this.shared;
  3252. }
  3253. deserialize( data ) {
  3254. super.deserialize( data );
  3255. this.name = data.name;
  3256. this.version = data.version;
  3257. this.shared = data.shared;
  3258. }
  3259. }
  3260. /**
  3261. * TSL function for creating a uniform group node with the given name.
  3262. *
  3263. * @tsl
  3264. * @function
  3265. * @param {string} name - The name of the uniform group node.
  3266. * @returns {UniformGroupNode}
  3267. */
  3268. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3269. /**
  3270. * TSL function for creating a shared uniform group node with the given name and order.
  3271. *
  3272. * @tsl
  3273. * @function
  3274. * @param {string} name - The name of the uniform group node.
  3275. * @param {number} [order=0] - Influences the internal sorting.
  3276. * @returns {UniformGroupNode}
  3277. */
  3278. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3279. /**
  3280. * TSL object that represents a shared uniform group node which is updated once per frame.
  3281. *
  3282. * @tsl
  3283. * @type {UniformGroupNode}
  3284. */
  3285. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3286. /**
  3287. * TSL object that represents a shared uniform group node which is updated once per render.
  3288. *
  3289. * @tsl
  3290. * @type {UniformGroupNode}
  3291. */
  3292. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3293. /**
  3294. * TSL object that represents a uniform group node which is updated once per object.
  3295. *
  3296. * @tsl
  3297. * @type {UniformGroupNode}
  3298. */
  3299. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3300. /**
  3301. * Class for representing a uniform.
  3302. *
  3303. * @augments InputNode
  3304. */
  3305. class UniformNode extends InputNode {
  3306. static get type() {
  3307. return 'UniformNode';
  3308. }
  3309. /**
  3310. * Constructs a new uniform node.
  3311. *
  3312. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3313. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3314. */
  3315. constructor( value, nodeType = null ) {
  3316. super( value, nodeType );
  3317. /**
  3318. * This flag can be used for type testing.
  3319. *
  3320. * @type {boolean}
  3321. * @readonly
  3322. * @default true
  3323. */
  3324. this.isUniformNode = true;
  3325. /**
  3326. * The name or label of the uniform.
  3327. *
  3328. * @type {string}
  3329. * @default ''
  3330. */
  3331. this.name = '';
  3332. /**
  3333. * The uniform group of this uniform. By default, uniforms are
  3334. * managed per object but they might belong to a shared group
  3335. * which is updated per frame or render call.
  3336. *
  3337. * @type {UniformGroupNode}
  3338. */
  3339. this.groupNode = objectGroup;
  3340. }
  3341. /**
  3342. * Sets the {@link UniformNode#name} property.
  3343. *
  3344. * @param {string} name - The name of the uniform.
  3345. * @return {UniformNode} A reference to this node.
  3346. */
  3347. setName( name ) {
  3348. this.name = name;
  3349. return this;
  3350. }
  3351. /**
  3352. * Sets the {@link UniformNode#name} property.
  3353. *
  3354. * @deprecated
  3355. * @param {string} name - The name of the uniform.
  3356. * @return {UniformNode} A reference to this node.
  3357. */
  3358. label( name ) {
  3359. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3360. return this.setName( name );
  3361. }
  3362. /**
  3363. * Sets the {@link UniformNode#groupNode} property.
  3364. *
  3365. * @param {UniformGroupNode} group - The uniform group.
  3366. * @return {UniformNode} A reference to this node.
  3367. */
  3368. setGroup( group ) {
  3369. this.groupNode = group;
  3370. return this;
  3371. }
  3372. /**
  3373. * Returns the {@link UniformNode#groupNode}.
  3374. *
  3375. * @return {UniformGroupNode} The uniform group.
  3376. */
  3377. getGroup() {
  3378. return this.groupNode;
  3379. }
  3380. /**
  3381. * By default, this method returns the result of {@link Node#getHash} but derived
  3382. * classes might overwrite this method with a different implementation.
  3383. *
  3384. * @param {NodeBuilder} builder - The current node builder.
  3385. * @return {string} The uniform hash.
  3386. */
  3387. getUniformHash( builder ) {
  3388. return this.getHash( builder );
  3389. }
  3390. onUpdate( callback, updateType ) {
  3391. callback = callback.bind( this );
  3392. return super.onUpdate( ( frame ) => {
  3393. const value = callback( frame, this );
  3394. if ( value !== undefined ) {
  3395. this.value = value;
  3396. }
  3397. }, updateType );
  3398. }
  3399. getInputType( builder ) {
  3400. let type = super.getInputType( builder );
  3401. if ( type === 'bool' ) {
  3402. type = 'uint';
  3403. }
  3404. return type;
  3405. }
  3406. generate( builder, output ) {
  3407. const type = this.getNodeType( builder );
  3408. const hash = this.getUniformHash( builder );
  3409. let sharedNode = builder.getNodeFromHash( hash );
  3410. if ( sharedNode === undefined ) {
  3411. builder.setHashNode( this, hash );
  3412. sharedNode = this;
  3413. }
  3414. const sharedNodeType = sharedNode.getInputType( builder );
  3415. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3416. const uniformName = builder.getPropertyName( nodeUniform );
  3417. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3418. //
  3419. let snippet = uniformName;
  3420. if ( type === 'bool' ) {
  3421. // cache to variable
  3422. const nodeData = builder.getDataFromNode( this );
  3423. let propertyName = nodeData.propertyName;
  3424. if ( propertyName === undefined ) {
  3425. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3426. propertyName = builder.getPropertyName( nodeVar );
  3427. nodeData.propertyName = propertyName;
  3428. snippet = builder.format( uniformName, sharedNodeType, type );
  3429. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3430. }
  3431. snippet = propertyName;
  3432. }
  3433. return builder.format( snippet, type, output );
  3434. }
  3435. }
  3436. /**
  3437. * TSL function for creating a uniform node.
  3438. *
  3439. * @tsl
  3440. * @function
  3441. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3442. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3443. * @returns {UniformNode}
  3444. */
  3445. const uniform = ( value, type ) => {
  3446. const nodeType = getConstNodeType( type || value );
  3447. if ( nodeType === value ) {
  3448. // if the value is a type but no having a value
  3449. value = getValueFromType( nodeType );
  3450. }
  3451. if ( value && value.isNode === true ) {
  3452. let v = value.value;
  3453. value.traverse( n => {
  3454. if ( n.isConstNode === true ) {
  3455. v = n.value;
  3456. }
  3457. } );
  3458. value = v;
  3459. }
  3460. return nodeObject( new UniformNode( value, nodeType ) );
  3461. };
  3462. /**
  3463. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3464. * ```js
  3465. * const colors = array( [
  3466. * vec3( 1, 0, 0 ),
  3467. * vec3( 0, 1, 0 ),
  3468. * vec3( 0, 0, 1 )
  3469. * ] );
  3470. *
  3471. * const redColor = tintColors.element( 0 );
  3472. * ```
  3473. *
  3474. * @augments TempNode
  3475. */
  3476. class ArrayNode extends TempNode {
  3477. static get type() {
  3478. return 'ArrayNode';
  3479. }
  3480. /**
  3481. * Constructs a new array node.
  3482. *
  3483. * @param {?string} nodeType - The data type of the elements.
  3484. * @param {number} count - Size of the array.
  3485. * @param {?Array<Node>} [values=null] - Array default values.
  3486. */
  3487. constructor( nodeType, count, values = null ) {
  3488. super( nodeType );
  3489. /**
  3490. * Array size.
  3491. *
  3492. * @type {number}
  3493. */
  3494. this.count = count;
  3495. /**
  3496. * Array default values.
  3497. *
  3498. * @type {?Array<Node>}
  3499. */
  3500. this.values = values;
  3501. /**
  3502. * This flag can be used for type testing.
  3503. *
  3504. * @type {boolean}
  3505. * @readonly
  3506. * @default true
  3507. */
  3508. this.isArrayNode = true;
  3509. }
  3510. /**
  3511. * Returns the number of elements in the node array.
  3512. *
  3513. * @param {NodeBuilder} builder - The current node builder.
  3514. * @return {number} The number of elements in the node array.
  3515. */
  3516. getArrayCount( /*builder*/ ) {
  3517. return this.count;
  3518. }
  3519. /**
  3520. * Returns the node's type.
  3521. *
  3522. * @param {NodeBuilder} builder - The current node builder.
  3523. * @return {string} The type of the node.
  3524. */
  3525. getNodeType( builder ) {
  3526. if ( this.nodeType === null ) {
  3527. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3528. }
  3529. return this.nodeType;
  3530. }
  3531. /**
  3532. * Returns the node's type.
  3533. *
  3534. * @param {NodeBuilder} builder - The current node builder.
  3535. * @return {string} The type of the node.
  3536. */
  3537. getElementType( builder ) {
  3538. return this.getNodeType( builder );
  3539. }
  3540. /**
  3541. * This method builds the output node and returns the resulting array as a shader string.
  3542. *
  3543. * @param {NodeBuilder} builder - The current node builder.
  3544. * @return {string} The generated shader string.
  3545. */
  3546. generate( builder ) {
  3547. const type = this.getNodeType( builder );
  3548. return builder.generateArray( type, this.count, this.values );
  3549. }
  3550. }
  3551. /**
  3552. * TSL function for creating an array node.
  3553. *
  3554. * @tsl
  3555. * @function
  3556. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3557. * or an array containing the default values (e.g., [ vec3() ]).
  3558. * @param {?number} [count] - Size of the array.
  3559. * @returns {ArrayNode}
  3560. */
  3561. const array = ( ...params ) => {
  3562. let node;
  3563. if ( params.length === 1 ) {
  3564. const values = params[ 0 ];
  3565. node = new ArrayNode( null, values.length, values );
  3566. } else {
  3567. const nodeType = params[ 0 ];
  3568. const count = params[ 1 ];
  3569. node = new ArrayNode( nodeType, count );
  3570. }
  3571. return nodeObject( node );
  3572. };
  3573. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3574. /**
  3575. * These node represents an assign operation. Meaning a node is assigned
  3576. * to another node.
  3577. *
  3578. * @augments TempNode
  3579. */
  3580. class AssignNode extends TempNode {
  3581. static get type() {
  3582. return 'AssignNode';
  3583. }
  3584. /**
  3585. * Constructs a new assign node.
  3586. *
  3587. * @param {Node} targetNode - The target node.
  3588. * @param {Node} sourceNode - The source type.
  3589. */
  3590. constructor( targetNode, sourceNode ) {
  3591. super();
  3592. /**
  3593. * The target node.
  3594. *
  3595. * @type {Node}
  3596. */
  3597. this.targetNode = targetNode;
  3598. /**
  3599. * The source node.
  3600. *
  3601. * @type {Node}
  3602. */
  3603. this.sourceNode = sourceNode;
  3604. /**
  3605. * This flag can be used for type testing.
  3606. *
  3607. * @type {boolean}
  3608. * @readonly
  3609. * @default true
  3610. */
  3611. this.isAssignNode = true;
  3612. }
  3613. /**
  3614. * Whether this node is used more than once in context of other nodes. This method
  3615. * is overwritten since it always returns `false` (assigns are unique).
  3616. *
  3617. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3618. */
  3619. hasDependencies() {
  3620. return false;
  3621. }
  3622. getNodeType( builder, output ) {
  3623. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3624. }
  3625. /**
  3626. * Whether a split is required when assigning source to target. This can happen when the component length of
  3627. * target and source data type does not match.
  3628. *
  3629. * @param {NodeBuilder} builder - The current node builder.
  3630. * @return {boolean} Whether a split is required when assigning source to target.
  3631. */
  3632. needsSplitAssign( builder ) {
  3633. const { targetNode } = this;
  3634. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3635. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3636. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3637. return assignDifferentVector;
  3638. }
  3639. return false;
  3640. }
  3641. setup( builder ) {
  3642. const { targetNode, sourceNode } = this;
  3643. const scope = targetNode.getScope();
  3644. const targetProperties = builder.getNodeProperties( scope );
  3645. targetProperties.assign = true;
  3646. const properties = builder.getNodeProperties( this );
  3647. properties.sourceNode = sourceNode;
  3648. properties.targetNode = targetNode.context( { assign: true } );
  3649. }
  3650. generate( builder, output ) {
  3651. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3652. const needsSplitAssign = this.needsSplitAssign( builder );
  3653. const target = targetNode.build( builder );
  3654. const targetType = targetNode.getNodeType( builder );
  3655. const source = sourceNode.build( builder, targetType );
  3656. const sourceType = sourceNode.getNodeType( builder );
  3657. const nodeData = builder.getDataFromNode( this );
  3658. //
  3659. let snippet;
  3660. if ( nodeData.initialized === true ) {
  3661. if ( output !== 'void' ) {
  3662. snippet = target;
  3663. }
  3664. } else if ( needsSplitAssign ) {
  3665. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3666. const sourceProperty = builder.getPropertyName( sourceVar );
  3667. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3668. const splitNode = targetNode.node;
  3669. const splitTargetNode = splitNode.node.context( { assign: true } );
  3670. const targetRoot = splitTargetNode.build( builder );
  3671. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3672. const component = splitNode.components[ i ];
  3673. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3674. }
  3675. if ( output !== 'void' ) {
  3676. snippet = target;
  3677. }
  3678. } else {
  3679. snippet = `${ target } = ${ source }`;
  3680. if ( output === 'void' || sourceType === 'void' ) {
  3681. builder.addLineFlowCode( snippet, this );
  3682. if ( output !== 'void' ) {
  3683. snippet = target;
  3684. }
  3685. }
  3686. }
  3687. nodeData.initialized = true;
  3688. return builder.format( snippet, targetType, output );
  3689. }
  3690. }
  3691. /**
  3692. * TSL function for creating an assign node.
  3693. *
  3694. * @tsl
  3695. * @function
  3696. * @param {Node} targetNode - The target node.
  3697. * @param {Node} sourceNode - The source type.
  3698. * @returns {AssignNode}
  3699. */
  3700. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3701. addMethodChaining( 'assign', assign );
  3702. /**
  3703. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3704. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3705. * this logic.
  3706. *
  3707. * @augments TempNode
  3708. */
  3709. class FunctionCallNode extends TempNode {
  3710. static get type() {
  3711. return 'FunctionCallNode';
  3712. }
  3713. /**
  3714. * Constructs a new function call node.
  3715. *
  3716. * @param {?FunctionNode} functionNode - The function node.
  3717. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3718. */
  3719. constructor( functionNode = null, parameters = {} ) {
  3720. super();
  3721. /**
  3722. * The function node.
  3723. *
  3724. * @type {?FunctionNode}
  3725. * @default null
  3726. */
  3727. this.functionNode = functionNode;
  3728. /**
  3729. * The parameters of the function call.
  3730. *
  3731. * @type {Object<string, Node>}
  3732. * @default {}
  3733. */
  3734. this.parameters = parameters;
  3735. }
  3736. /**
  3737. * Sets the parameters of the function call node.
  3738. *
  3739. * @param {Object<string, Node>} parameters - The parameters to set.
  3740. * @return {FunctionCallNode} A reference to this node.
  3741. */
  3742. setParameters( parameters ) {
  3743. this.parameters = parameters;
  3744. return this;
  3745. }
  3746. /**
  3747. * Returns the parameters of the function call node.
  3748. *
  3749. * @return {Object<string, Node>} The parameters of this node.
  3750. */
  3751. getParameters() {
  3752. return this.parameters;
  3753. }
  3754. /**
  3755. * Returns the type of this function call node.
  3756. *
  3757. * @param {NodeBuilder} builder - The current node builder.
  3758. * @returns {string} The type of this node.
  3759. */
  3760. getNodeType( builder ) {
  3761. return this.functionNode.getNodeType( builder );
  3762. }
  3763. /**
  3764. * Returns the function node of this function call node.
  3765. *
  3766. * @param {NodeBuilder} builder - The current node builder.
  3767. * @param {string} [name] - The name of the member.
  3768. * @returns {string} The type of the member.
  3769. */
  3770. getMemberType( builder, name ) {
  3771. return this.functionNode.getMemberType( builder, name );
  3772. }
  3773. generate( builder ) {
  3774. const params = [];
  3775. const functionNode = this.functionNode;
  3776. const inputs = functionNode.getInputs( builder );
  3777. const parameters = this.parameters;
  3778. const generateInput = ( node, inputNode ) => {
  3779. const type = inputNode.type;
  3780. const pointer = type === 'pointer';
  3781. let output;
  3782. if ( pointer ) output = '&' + node.build( builder );
  3783. else output = node.build( builder, type );
  3784. return output;
  3785. };
  3786. if ( Array.isArray( parameters ) ) {
  3787. if ( parameters.length > inputs.length ) {
  3788. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3789. parameters.length = inputs.length;
  3790. } else if ( parameters.length < inputs.length ) {
  3791. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3792. while ( parameters.length < inputs.length ) {
  3793. parameters.push( float( 0 ) );
  3794. }
  3795. }
  3796. for ( let i = 0; i < parameters.length; i ++ ) {
  3797. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3798. }
  3799. } else {
  3800. for ( const inputNode of inputs ) {
  3801. const node = parameters[ inputNode.name ];
  3802. if ( node !== undefined ) {
  3803. params.push( generateInput( node, inputNode ) );
  3804. } else {
  3805. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3806. params.push( generateInput( float( 0 ), inputNode ) );
  3807. }
  3808. }
  3809. }
  3810. const functionName = functionNode.build( builder, 'property' );
  3811. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3812. }
  3813. }
  3814. const call = ( func, ...params ) => {
  3815. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3816. return new FunctionCallNode( nodeObject( func ), params );
  3817. };
  3818. addMethodChaining( 'call', call );
  3819. const _vectorOperators = {
  3820. '==': 'equal',
  3821. '!=': 'notEqual',
  3822. '<': 'lessThan',
  3823. '>': 'greaterThan',
  3824. '<=': 'lessThanEqual',
  3825. '>=': 'greaterThanEqual',
  3826. '%': 'mod'
  3827. };
  3828. /**
  3829. * This node represents basic mathematical and logical operations like addition,
  3830. * subtraction or comparisons (e.g. `equal()`).
  3831. *
  3832. * @augments TempNode
  3833. */
  3834. class OperatorNode extends TempNode {
  3835. static get type() {
  3836. return 'OperatorNode';
  3837. }
  3838. /**
  3839. * Constructs a new operator node.
  3840. *
  3841. * @param {string} op - The operator.
  3842. * @param {Node} aNode - The first input.
  3843. * @param {Node} bNode - The second input.
  3844. * @param {...Node} params - Additional input parameters.
  3845. */
  3846. constructor( op, aNode, bNode, ...params ) {
  3847. super();
  3848. if ( params.length > 0 ) {
  3849. let finalOp = new OperatorNode( op, aNode, bNode );
  3850. for ( let i = 0; i < params.length - 1; i ++ ) {
  3851. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3852. }
  3853. aNode = finalOp;
  3854. bNode = params[ params.length - 1 ];
  3855. }
  3856. /**
  3857. * The operator.
  3858. *
  3859. * @type {string}
  3860. */
  3861. this.op = op;
  3862. /**
  3863. * The first input.
  3864. *
  3865. * @type {Node}
  3866. */
  3867. this.aNode = aNode;
  3868. /**
  3869. * The second input.
  3870. *
  3871. * @type {Node}
  3872. */
  3873. this.bNode = bNode;
  3874. /**
  3875. * This flag can be used for type testing.
  3876. *
  3877. * @type {boolean}
  3878. * @readonly
  3879. * @default true
  3880. */
  3881. this.isOperatorNode = true;
  3882. }
  3883. /**
  3884. * Returns the operator method name.
  3885. *
  3886. * @param {NodeBuilder} builder - The current node builder.
  3887. * @param {string} output - The output type.
  3888. * @returns {string} The operator method name.
  3889. */
  3890. getOperatorMethod( builder, output ) {
  3891. return builder.getMethod( _vectorOperators[ this.op ], output );
  3892. }
  3893. /**
  3894. * This method is overwritten since the node type is inferred from the operator
  3895. * and the input node types.
  3896. *
  3897. * @param {NodeBuilder} builder - The current node builder.
  3898. * @param {?string} [output=null] - The output type.
  3899. * @return {string} The node type.
  3900. */
  3901. getNodeType( builder, output = null ) {
  3902. const op = this.op;
  3903. const aNode = this.aNode;
  3904. const bNode = this.bNode;
  3905. const typeA = aNode.getNodeType( builder );
  3906. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3907. if ( typeA === 'void' || typeB === 'void' ) {
  3908. return output || 'void';
  3909. } else if ( op === '%' ) {
  3910. return typeA;
  3911. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3912. return builder.getIntegerType( typeA );
  3913. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3914. return 'bool';
  3915. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3916. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3917. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3918. } else {
  3919. // Handle matrix operations
  3920. if ( builder.isMatrix( typeA ) ) {
  3921. if ( typeB === 'float' ) {
  3922. return typeA; // matrix * scalar = matrix
  3923. } else if ( builder.isVector( typeB ) ) {
  3924. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3925. } else if ( builder.isMatrix( typeB ) ) {
  3926. return typeA; // matrix * matrix
  3927. }
  3928. } else if ( builder.isMatrix( typeB ) ) {
  3929. if ( typeA === 'float' ) {
  3930. return typeB; // scalar * matrix = matrix
  3931. } else if ( builder.isVector( typeA ) ) {
  3932. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3933. }
  3934. }
  3935. // Handle non-matrix cases
  3936. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3937. // anytype x anytype: use the greater length vector
  3938. return typeB;
  3939. }
  3940. return typeA;
  3941. }
  3942. }
  3943. generate( builder, output ) {
  3944. const op = this.op;
  3945. const { aNode, bNode } = this;
  3946. const type = this.getNodeType( builder, output );
  3947. let typeA = null;
  3948. let typeB = null;
  3949. if ( type !== 'void' ) {
  3950. typeA = aNode.getNodeType( builder );
  3951. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3952. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3953. if ( builder.isVector( typeA ) ) {
  3954. typeB = typeA;
  3955. } else if ( builder.isVector( typeB ) ) {
  3956. typeA = typeB;
  3957. } else if ( typeA !== typeB ) {
  3958. typeA = typeB = 'float';
  3959. }
  3960. } else if ( op === '>>' || op === '<<' ) {
  3961. typeA = type;
  3962. typeB = builder.changeComponentType( typeB, 'uint' );
  3963. } else if ( op === '%' ) {
  3964. typeA = type;
  3965. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3966. } else if ( builder.isMatrix( typeA ) ) {
  3967. if ( typeB === 'float' ) {
  3968. // Keep matrix type for typeA, but ensure typeB stays float
  3969. typeB = 'float';
  3970. } else if ( builder.isVector( typeB ) ) {
  3971. // matrix x vector
  3972. typeB = builder.getVectorFromMatrix( typeA );
  3973. } else if ( builder.isMatrix( typeB ) ) ; else {
  3974. typeA = typeB = type;
  3975. }
  3976. } else if ( builder.isMatrix( typeB ) ) {
  3977. if ( typeA === 'float' ) {
  3978. // Keep matrix type for typeB, but ensure typeA stays float
  3979. typeA = 'float';
  3980. } else if ( builder.isVector( typeA ) ) {
  3981. // vector x matrix
  3982. typeA = builder.getVectorFromMatrix( typeB );
  3983. } else {
  3984. typeA = typeB = type;
  3985. }
  3986. } else {
  3987. // anytype x anytype
  3988. typeA = typeB = type;
  3989. }
  3990. } else {
  3991. typeA = typeB = type;
  3992. }
  3993. const a = aNode.build( builder, typeA );
  3994. const b = bNode ? bNode.build( builder, typeB ) : null;
  3995. const fnOpSnippet = builder.getFunctionOperator( op );
  3996. if ( output !== 'void' ) {
  3997. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3998. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3999. if ( isGLSL ) {
  4000. if ( builder.isVector( typeA ) ) {
  4001. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  4002. } else {
  4003. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4004. }
  4005. } else {
  4006. // WGSL
  4007. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4008. }
  4009. } else if ( op === '%' ) {
  4010. if ( builder.isInteger( typeB ) ) {
  4011. return builder.format( `( ${ a } % ${ b } )`, type, output );
  4012. } else {
  4013. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  4014. }
  4015. } else if ( op === '!' || op === '~' ) {
  4016. return builder.format( `(${op}${a})`, typeA, output );
  4017. } else if ( fnOpSnippet ) {
  4018. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4019. } else {
  4020. // Handle matrix operations
  4021. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4022. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  4023. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  4024. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4025. } else {
  4026. let snippet = `( ${ a } ${ op } ${ b } )`;
  4027. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  4028. snippet = `all${ snippet }`;
  4029. }
  4030. return builder.format( snippet, type, output );
  4031. }
  4032. }
  4033. } else if ( typeA !== 'void' ) {
  4034. if ( fnOpSnippet ) {
  4035. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4036. } else {
  4037. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4038. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  4039. } else {
  4040. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4041. }
  4042. }
  4043. }
  4044. }
  4045. serialize( data ) {
  4046. super.serialize( data );
  4047. data.op = this.op;
  4048. }
  4049. deserialize( data ) {
  4050. super.deserialize( data );
  4051. this.op = data.op;
  4052. }
  4053. }
  4054. /**
  4055. * Returns the addition of two or more value.
  4056. *
  4057. * @tsl
  4058. * @function
  4059. * @param {Node} a - The first input.
  4060. * @param {Node} b - The second input.
  4061. * @param {...Node} params - Additional input parameters.
  4062. * @returns {OperatorNode}
  4063. */
  4064. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4065. /**
  4066. * Returns the subtraction of two or more value.
  4067. *
  4068. * @tsl
  4069. * @function
  4070. * @param {Node} a - The first input.
  4071. * @param {Node} b - The second input.
  4072. * @param {...Node} params - Additional input parameters.
  4073. * @returns {OperatorNode}
  4074. */
  4075. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4076. /**
  4077. * Returns the multiplication of two or more value.
  4078. *
  4079. * @tsl
  4080. * @function
  4081. * @param {Node} a - The first input.
  4082. * @param {Node} b - The second input.
  4083. * @param {...Node} params - Additional input parameters.
  4084. * @returns {OperatorNode}
  4085. */
  4086. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4087. /**
  4088. * Returns the division of two or more value.
  4089. *
  4090. * @tsl
  4091. * @function
  4092. * @param {Node} a - The first input.
  4093. * @param {Node} b - The second input.
  4094. * @param {...Node} params - Additional input parameters.
  4095. * @returns {OperatorNode}
  4096. */
  4097. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4098. /**
  4099. * Computes the remainder of dividing the first node by the second one.
  4100. *
  4101. * @tsl
  4102. * @function
  4103. * @param {Node} a - The first input.
  4104. * @param {Node} b - The second input.
  4105. * @returns {OperatorNode}
  4106. */
  4107. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4108. /**
  4109. * Checks if two nodes are equal.
  4110. *
  4111. * @tsl
  4112. * @function
  4113. * @param {Node} a - The first input.
  4114. * @param {Node} b - The second input.
  4115. * @returns {OperatorNode}
  4116. */
  4117. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4118. /**
  4119. * Checks if two nodes are not equal.
  4120. *
  4121. * @tsl
  4122. * @function
  4123. * @param {Node} a - The first input.
  4124. * @param {Node} b - The second input.
  4125. * @returns {OperatorNode}
  4126. */
  4127. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4128. /**
  4129. * Checks if the first node is less than the second.
  4130. *
  4131. * @tsl
  4132. * @function
  4133. * @param {Node} a - The first input.
  4134. * @param {Node} b - The second input.
  4135. * @returns {OperatorNode}
  4136. */
  4137. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4138. /**
  4139. * Checks if the first node is greater than the second.
  4140. *
  4141. * @tsl
  4142. * @function
  4143. * @param {Node} a - The first input.
  4144. * @param {Node} b - The second input.
  4145. * @returns {OperatorNode}
  4146. */
  4147. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4148. /**
  4149. * Checks if the first node is less than or equal to the second.
  4150. *
  4151. * @tsl
  4152. * @function
  4153. * @param {Node} a - The first input.
  4154. * @param {Node} b - The second input.
  4155. * @returns {OperatorNode}
  4156. */
  4157. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4158. /**
  4159. * Checks if the first node is greater than or equal to the second.
  4160. *
  4161. * @tsl
  4162. * @function
  4163. * @param {Node} a - The first input.
  4164. * @param {Node} b - The second input.
  4165. * @returns {OperatorNode}
  4166. */
  4167. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4168. /**
  4169. * Performs a logical AND operation on multiple nodes.
  4170. *
  4171. * @tsl
  4172. * @function
  4173. * @param {...Node} nodes - The input nodes to be combined using AND.
  4174. * @returns {OperatorNode}
  4175. */
  4176. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4177. /**
  4178. * Performs a logical OR operation on multiple nodes.
  4179. *
  4180. * @tsl
  4181. * @function
  4182. * @param {...Node} nodes - The input nodes to be combined using OR.
  4183. * @returns {OperatorNode}
  4184. */
  4185. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4186. /**
  4187. * Performs logical NOT on a node.
  4188. *
  4189. * @tsl
  4190. * @function
  4191. * @param {Node} value - The value.
  4192. * @returns {OperatorNode}
  4193. */
  4194. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4195. /**
  4196. * Performs logical XOR on two nodes.
  4197. *
  4198. * @tsl
  4199. * @function
  4200. * @param {Node} a - The first input.
  4201. * @param {Node} b - The second input.
  4202. * @returns {OperatorNode}
  4203. */
  4204. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4205. /**
  4206. * Performs bitwise AND on two nodes.
  4207. *
  4208. * @tsl
  4209. * @function
  4210. * @param {Node} a - The first input.
  4211. * @param {Node} b - The second input.
  4212. * @returns {OperatorNode}
  4213. */
  4214. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4215. /**
  4216. * Performs bitwise NOT on a node.
  4217. *
  4218. * @tsl
  4219. * @function
  4220. * @param {Node} a - The first input.
  4221. * @param {Node} b - The second input.
  4222. * @returns {OperatorNode}
  4223. */
  4224. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4225. /**
  4226. * Performs bitwise OR on two nodes.
  4227. *
  4228. * @tsl
  4229. * @function
  4230. * @param {Node} a - The first input.
  4231. * @param {Node} b - The second input.
  4232. * @returns {OperatorNode}
  4233. */
  4234. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4235. /**
  4236. * Performs bitwise XOR on two nodes.
  4237. *
  4238. * @tsl
  4239. * @function
  4240. * @param {Node} a - The first input.
  4241. * @param {Node} b - The second input.
  4242. * @returns {OperatorNode}
  4243. */
  4244. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4245. /**
  4246. * Shifts a node to the left.
  4247. *
  4248. * @tsl
  4249. * @function
  4250. * @param {Node} a - The node to shift.
  4251. * @param {Node} b - The value to shift.
  4252. * @returns {OperatorNode}
  4253. */
  4254. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4255. /**
  4256. * Shifts a node to the right.
  4257. *
  4258. * @tsl
  4259. * @function
  4260. * @param {Node} a - The node to shift.
  4261. * @param {Node} b - The value to shift.
  4262. * @returns {OperatorNode}
  4263. */
  4264. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4265. /**
  4266. * Increments a node by 1.
  4267. *
  4268. * @tsl
  4269. * @function
  4270. * @param {Node} a - The node to increment.
  4271. * @returns {OperatorNode}
  4272. */
  4273. const incrementBefore = Fn( ( [ a ] ) => {
  4274. a.addAssign( 1 );
  4275. return a;
  4276. } );
  4277. /**
  4278. * Decrements a node by 1.
  4279. *
  4280. * @tsl
  4281. * @function
  4282. * @param {Node} a - The node to decrement.
  4283. * @returns {OperatorNode}
  4284. */
  4285. const decrementBefore = Fn( ( [ a ] ) => {
  4286. a.subAssign( 1 );
  4287. return a;
  4288. } );
  4289. /**
  4290. * Increments a node by 1 and returns the previous value.
  4291. *
  4292. * @tsl
  4293. * @function
  4294. * @param {Node} a - The node to increment.
  4295. * @returns {OperatorNode}
  4296. */
  4297. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4298. const temp = int( a ).toConst();
  4299. a.addAssign( 1 );
  4300. return temp;
  4301. } );
  4302. /**
  4303. * Decrements a node by 1 and returns the previous value.
  4304. *
  4305. * @tsl
  4306. * @function
  4307. * @param {Node} a - The node to decrement.
  4308. * @returns {OperatorNode}
  4309. */
  4310. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4311. const temp = int( a ).toConst();
  4312. a.subAssign( 1 );
  4313. return temp;
  4314. } );
  4315. addMethodChaining( 'add', add );
  4316. addMethodChaining( 'sub', sub );
  4317. addMethodChaining( 'mul', mul );
  4318. addMethodChaining( 'div', div );
  4319. addMethodChaining( 'mod', mod );
  4320. addMethodChaining( 'equal', equal );
  4321. addMethodChaining( 'notEqual', notEqual );
  4322. addMethodChaining( 'lessThan', lessThan );
  4323. addMethodChaining( 'greaterThan', greaterThan );
  4324. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4325. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4326. addMethodChaining( 'and', and );
  4327. addMethodChaining( 'or', or );
  4328. addMethodChaining( 'not', not );
  4329. addMethodChaining( 'xor', xor );
  4330. addMethodChaining( 'bitAnd', bitAnd );
  4331. addMethodChaining( 'bitNot', bitNot );
  4332. addMethodChaining( 'bitOr', bitOr );
  4333. addMethodChaining( 'bitXor', bitXor );
  4334. addMethodChaining( 'shiftLeft', shiftLeft );
  4335. addMethodChaining( 'shiftRight', shiftRight );
  4336. addMethodChaining( 'incrementBefore', incrementBefore );
  4337. addMethodChaining( 'decrementBefore', decrementBefore );
  4338. addMethodChaining( 'increment', increment );
  4339. addMethodChaining( 'decrement', decrement );
  4340. /**
  4341. * @tsl
  4342. * @function
  4343. * @deprecated since r175. Use {@link mod} instead.
  4344. *
  4345. * @param {Node} a - The first input.
  4346. * @param {Node} b - The second input.
  4347. * @returns {OperatorNode}
  4348. */
  4349. const modInt = ( a, b ) => { // @deprecated, r175
  4350. warn( 'TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4351. return mod( int( a ), int( b ) );
  4352. };
  4353. addMethodChaining( 'modInt', modInt );
  4354. /**
  4355. * This node represents a variety of mathematical methods available in shaders.
  4356. * They are divided into three categories:
  4357. *
  4358. * - Methods with one input like `sin`, `cos` or `normalize`.
  4359. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4360. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4361. *
  4362. * @augments TempNode
  4363. */
  4364. class MathNode extends TempNode {
  4365. static get type() {
  4366. return 'MathNode';
  4367. }
  4368. /**
  4369. * Constructs a new math node.
  4370. *
  4371. * @param {string} method - The method name.
  4372. * @param {Node} aNode - The first input.
  4373. * @param {?Node} [bNode=null] - The second input.
  4374. * @param {?Node} [cNode=null] - The third input.
  4375. */
  4376. constructor( method, aNode, bNode = null, cNode = null ) {
  4377. super();
  4378. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4379. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4380. let finalOp = new MathNode( method, aNode, bNode );
  4381. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4382. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4383. }
  4384. aNode = finalOp;
  4385. bNode = arguments[ arguments.length - 1 ];
  4386. cNode = null;
  4387. }
  4388. /**
  4389. * The method name.
  4390. *
  4391. * @type {string}
  4392. */
  4393. this.method = method;
  4394. /**
  4395. * The first input.
  4396. *
  4397. * @type {Node}
  4398. */
  4399. this.aNode = aNode;
  4400. /**
  4401. * The second input.
  4402. *
  4403. * @type {?Node}
  4404. * @default null
  4405. */
  4406. this.bNode = bNode;
  4407. /**
  4408. * The third input.
  4409. *
  4410. * @type {?Node}
  4411. * @default null
  4412. */
  4413. this.cNode = cNode;
  4414. /**
  4415. * This flag can be used for type testing.
  4416. *
  4417. * @type {boolean}
  4418. * @readonly
  4419. * @default true
  4420. */
  4421. this.isMathNode = true;
  4422. }
  4423. /**
  4424. * The input type is inferred from the node types of the input nodes.
  4425. *
  4426. * @param {NodeBuilder} builder - The current node builder.
  4427. * @return {string} The input type.
  4428. */
  4429. getInputType( builder ) {
  4430. const aType = this.aNode.getNodeType( builder );
  4431. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4432. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4433. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4434. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4435. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4436. if ( aLen > bLen && aLen > cLen ) {
  4437. return aType;
  4438. } else if ( bLen > cLen ) {
  4439. return bType;
  4440. } else if ( cLen > aLen ) {
  4441. return cType;
  4442. }
  4443. return aType;
  4444. }
  4445. /**
  4446. * The selected method as well as the input type determine the node type of this node.
  4447. *
  4448. * @param {NodeBuilder} builder - The current node builder.
  4449. * @return {string} The node type.
  4450. */
  4451. getNodeType( builder ) {
  4452. const method = this.method;
  4453. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4454. return 'float';
  4455. } else if ( method === MathNode.CROSS ) {
  4456. return 'vec3';
  4457. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4458. return 'bool';
  4459. } else if ( method === MathNode.EQUALS ) {
  4460. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4461. } else {
  4462. return this.getInputType( builder );
  4463. }
  4464. }
  4465. setup( builder ) {
  4466. const { aNode, bNode, method } = this;
  4467. let outputNode = null;
  4468. if ( method === MathNode.ONE_MINUS ) {
  4469. outputNode = sub( 1.0, aNode );
  4470. } else if ( method === MathNode.RECIPROCAL ) {
  4471. outputNode = div( 1.0, aNode );
  4472. } else if ( method === MathNode.DIFFERENCE ) {
  4473. outputNode = abs( sub( aNode, bNode ) );
  4474. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4475. // dir can be either a direction vector or a normal vector
  4476. // upper-left 3x3 of matrix is assumed to be orthogonal
  4477. let tA = aNode;
  4478. let tB = bNode;
  4479. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4480. tB = vec4( vec3( tB ), 0.0 );
  4481. } else {
  4482. tA = vec4( vec3( tA ), 0.0 );
  4483. }
  4484. const mulNode = mul( tA, tB ).xyz;
  4485. outputNode = normalize( mulNode );
  4486. }
  4487. if ( outputNode !== null ) {
  4488. return outputNode;
  4489. } else {
  4490. return super.setup( builder );
  4491. }
  4492. }
  4493. generate( builder, output ) {
  4494. const properties = builder.getNodeProperties( this );
  4495. if ( properties.outputNode ) {
  4496. return super.generate( builder, output );
  4497. }
  4498. let method = this.method;
  4499. const type = this.getNodeType( builder );
  4500. const inputType = this.getInputType( builder );
  4501. const a = this.aNode;
  4502. const b = this.bNode;
  4503. const c = this.cNode;
  4504. const coordinateSystem = builder.renderer.coordinateSystem;
  4505. if ( method === MathNode.NEGATE ) {
  4506. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4507. } else {
  4508. const params = [];
  4509. if ( method === MathNode.CROSS ) {
  4510. params.push(
  4511. a.build( builder, type ),
  4512. b.build( builder, type )
  4513. );
  4514. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4515. params.push(
  4516. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4517. b.build( builder, inputType )
  4518. );
  4519. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4520. params.push(
  4521. a.build( builder, inputType ),
  4522. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4523. );
  4524. } else if ( method === MathNode.REFRACT ) {
  4525. params.push(
  4526. a.build( builder, inputType ),
  4527. b.build( builder, inputType ),
  4528. c.build( builder, 'float' )
  4529. );
  4530. } else if ( method === MathNode.MIX ) {
  4531. params.push(
  4532. a.build( builder, inputType ),
  4533. b.build( builder, inputType ),
  4534. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4535. );
  4536. } else {
  4537. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4538. method = 'atan2';
  4539. }
  4540. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4541. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4542. method = '/*' + method + '*/';
  4543. }
  4544. params.push( a.build( builder, inputType ) );
  4545. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4546. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4547. }
  4548. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4549. }
  4550. }
  4551. serialize( data ) {
  4552. super.serialize( data );
  4553. data.method = this.method;
  4554. }
  4555. deserialize( data ) {
  4556. super.deserialize( data );
  4557. this.method = data.method;
  4558. }
  4559. }
  4560. // 1 input
  4561. MathNode.ALL = 'all';
  4562. MathNode.ANY = 'any';
  4563. MathNode.RADIANS = 'radians';
  4564. MathNode.DEGREES = 'degrees';
  4565. MathNode.EXP = 'exp';
  4566. MathNode.EXP2 = 'exp2';
  4567. MathNode.LOG = 'log';
  4568. MathNode.LOG2 = 'log2';
  4569. MathNode.SQRT = 'sqrt';
  4570. MathNode.INVERSE_SQRT = 'inversesqrt';
  4571. MathNode.FLOOR = 'floor';
  4572. MathNode.CEIL = 'ceil';
  4573. MathNode.NORMALIZE = 'normalize';
  4574. MathNode.FRACT = 'fract';
  4575. MathNode.SIN = 'sin';
  4576. MathNode.COS = 'cos';
  4577. MathNode.TAN = 'tan';
  4578. MathNode.ASIN = 'asin';
  4579. MathNode.ACOS = 'acos';
  4580. MathNode.ATAN = 'atan';
  4581. MathNode.ABS = 'abs';
  4582. MathNode.SIGN = 'sign';
  4583. MathNode.LENGTH = 'length';
  4584. MathNode.NEGATE = 'negate';
  4585. MathNode.ONE_MINUS = 'oneMinus';
  4586. MathNode.DFDX = 'dFdx';
  4587. MathNode.DFDY = 'dFdy';
  4588. MathNode.ROUND = 'round';
  4589. MathNode.RECIPROCAL = 'reciprocal';
  4590. MathNode.TRUNC = 'trunc';
  4591. MathNode.FWIDTH = 'fwidth';
  4592. MathNode.TRANSPOSE = 'transpose';
  4593. MathNode.DETERMINANT = 'determinant';
  4594. MathNode.INVERSE = 'inverse';
  4595. // 2 inputs
  4596. MathNode.EQUALS = 'equals';
  4597. MathNode.MIN = 'min';
  4598. MathNode.MAX = 'max';
  4599. MathNode.STEP = 'step';
  4600. MathNode.REFLECT = 'reflect';
  4601. MathNode.DISTANCE = 'distance';
  4602. MathNode.DIFFERENCE = 'difference';
  4603. MathNode.DOT = 'dot';
  4604. MathNode.CROSS = 'cross';
  4605. MathNode.POW = 'pow';
  4606. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4607. // 3 inputs
  4608. MathNode.MIX = 'mix';
  4609. MathNode.CLAMP = 'clamp';
  4610. MathNode.REFRACT = 'refract';
  4611. MathNode.SMOOTHSTEP = 'smoothstep';
  4612. MathNode.FACEFORWARD = 'faceforward';
  4613. // 1 inputs
  4614. /**
  4615. * A small value used to handle floating-point precision errors.
  4616. *
  4617. * @tsl
  4618. * @type {Node<float>}
  4619. */
  4620. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4621. /**
  4622. * Represents infinity.
  4623. *
  4624. * @tsl
  4625. * @type {Node<float>}
  4626. */
  4627. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4628. /**
  4629. * Represents PI.
  4630. *
  4631. * @tsl
  4632. * @type {Node<float>}
  4633. */
  4634. const PI = /*@__PURE__*/ float( Math.PI );
  4635. /**
  4636. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  4637. *
  4638. * @tsl
  4639. * @deprecated
  4640. * @type {Node<float>}
  4641. */
  4642. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  4643. /**
  4644. * Represents PI * 2.
  4645. *
  4646. * @tsl
  4647. * @type {Node<float>}
  4648. */
  4649. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  4650. /**
  4651. * Represents PI / 2.
  4652. *
  4653. * @tsl
  4654. * @type {Node<float>}
  4655. */
  4656. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  4657. /**
  4658. * Returns `true` if all components of `x` are `true`.
  4659. *
  4660. * @tsl
  4661. * @function
  4662. * @param {Node | number} x - The parameter.
  4663. * @returns {Node<bool>}
  4664. */
  4665. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4666. /**
  4667. * Returns `true` if any components of `x` are `true`.
  4668. *
  4669. * @tsl
  4670. * @function
  4671. * @param {Node | number} x - The parameter.
  4672. * @returns {Node<bool>}
  4673. */
  4674. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4675. /**
  4676. * Converts a quantity in degrees to radians.
  4677. *
  4678. * @tsl
  4679. * @function
  4680. * @param {Node | number} x - The input in degrees.
  4681. * @returns {Node}
  4682. */
  4683. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4684. /**
  4685. * Convert a quantity in radians to degrees.
  4686. *
  4687. * @tsl
  4688. * @function
  4689. * @param {Node | number} x - The input in radians.
  4690. * @returns {Node}
  4691. */
  4692. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4693. /**
  4694. * Returns the natural exponentiation of the parameter.
  4695. *
  4696. * @tsl
  4697. * @function
  4698. * @param {Node | number} x - The parameter.
  4699. * @returns {Node}
  4700. */
  4701. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4702. /**
  4703. * Returns 2 raised to the power of the parameter.
  4704. *
  4705. * @tsl
  4706. * @function
  4707. * @param {Node | number} x - The parameter.
  4708. * @returns {Node}
  4709. */
  4710. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4711. /**
  4712. * Returns the natural logarithm of the parameter.
  4713. *
  4714. * @tsl
  4715. * @function
  4716. * @param {Node | number} x - The parameter.
  4717. * @returns {Node}
  4718. */
  4719. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4720. /**
  4721. * Returns the base 2 logarithm of the parameter.
  4722. *
  4723. * @tsl
  4724. * @function
  4725. * @param {Node | number} x - The parameter.
  4726. * @returns {Node}
  4727. */
  4728. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4729. /**
  4730. * Returns the square root of the parameter.
  4731. *
  4732. * @tsl
  4733. * @function
  4734. * @param {Node | number} x - The parameter.
  4735. * @returns {Node}
  4736. */
  4737. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4738. /**
  4739. * Returns the inverse of the square root of the parameter.
  4740. *
  4741. * @tsl
  4742. * @function
  4743. * @param {Node | number} x - The parameter.
  4744. * @returns {Node}
  4745. */
  4746. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4747. /**
  4748. * Finds the nearest integer less than or equal to the parameter.
  4749. *
  4750. * @tsl
  4751. * @function
  4752. * @param {Node | number} x - The parameter.
  4753. * @returns {Node}
  4754. */
  4755. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4756. /**
  4757. * Finds the nearest integer that is greater than or equal to the parameter.
  4758. *
  4759. * @tsl
  4760. * @function
  4761. * @param {Node | number} x - The parameter.
  4762. * @returns {Node}
  4763. */
  4764. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4765. /**
  4766. * Calculates the unit vector in the same direction as the original vector.
  4767. *
  4768. * @tsl
  4769. * @function
  4770. * @param {Node} x - The input vector.
  4771. * @returns {Node}
  4772. */
  4773. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4774. /**
  4775. * Computes the fractional part of the parameter.
  4776. *
  4777. * @tsl
  4778. * @function
  4779. * @param {Node | number} x - The parameter.
  4780. * @returns {Node}
  4781. */
  4782. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4783. /**
  4784. * Returns the sine of the parameter.
  4785. *
  4786. * @tsl
  4787. * @function
  4788. * @param {Node | number} x - The parameter.
  4789. * @returns {Node}
  4790. */
  4791. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4792. /**
  4793. * Returns the cosine of the parameter.
  4794. *
  4795. * @tsl
  4796. * @function
  4797. * @param {Node | number} x - The parameter.
  4798. * @returns {Node}
  4799. */
  4800. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4801. /**
  4802. * Returns the tangent of the parameter.
  4803. *
  4804. * @tsl
  4805. * @function
  4806. * @param {Node | number} x - The parameter.
  4807. * @returns {Node}
  4808. */
  4809. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4810. /**
  4811. * Returns the arcsine of the parameter.
  4812. *
  4813. * @tsl
  4814. * @function
  4815. * @param {Node | number} x - The parameter.
  4816. * @returns {Node}
  4817. */
  4818. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4819. /**
  4820. * Returns the arccosine of the parameter.
  4821. *
  4822. * @tsl
  4823. * @function
  4824. * @param {Node | number} x - The parameter.
  4825. * @returns {Node}
  4826. */
  4827. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4828. /**
  4829. * Returns the arc-tangent of the parameter.
  4830. * If two parameters are provided, the result is `atan2(y/x)`.
  4831. *
  4832. * @tsl
  4833. * @function
  4834. * @param {Node | number} y - The y parameter.
  4835. * @param {?(Node | number)} x - The x parameter.
  4836. * @returns {Node}
  4837. */
  4838. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4839. /**
  4840. * Returns the absolute value of the parameter.
  4841. *
  4842. * @tsl
  4843. * @function
  4844. * @param {Node | number} x - The parameter.
  4845. * @returns {Node}
  4846. */
  4847. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4848. /**
  4849. * Extracts the sign of the parameter.
  4850. *
  4851. * @tsl
  4852. * @function
  4853. * @param {Node | number} x - The parameter.
  4854. * @returns {Node}
  4855. */
  4856. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4857. /**
  4858. * Calculates the length of a vector.
  4859. *
  4860. * @tsl
  4861. * @function
  4862. * @param {Node} x - The parameter.
  4863. * @returns {Node<float>}
  4864. */
  4865. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4866. /**
  4867. * Negates the value of the parameter (-x).
  4868. *
  4869. * @tsl
  4870. * @function
  4871. * @param {Node | number} x - The parameter.
  4872. * @returns {Node}
  4873. */
  4874. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4875. /**
  4876. * Return `1` minus the parameter.
  4877. *
  4878. * @tsl
  4879. * @function
  4880. * @param {Node | number} x - The parameter.
  4881. * @returns {Node}
  4882. */
  4883. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4884. /**
  4885. * Returns the partial derivative of the parameter with respect to x.
  4886. *
  4887. * @tsl
  4888. * @function
  4889. * @param {Node | number} x - The parameter.
  4890. * @returns {Node}
  4891. */
  4892. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4893. /**
  4894. * Returns the partial derivative of the parameter with respect to y.
  4895. *
  4896. * @tsl
  4897. * @function
  4898. * @param {Node | number} x - The parameter.
  4899. * @returns {Node}
  4900. */
  4901. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4902. /**
  4903. * Rounds the parameter to the nearest integer.
  4904. *
  4905. * @tsl
  4906. * @function
  4907. * @param {Node | number} x - The parameter.
  4908. * @returns {Node}
  4909. */
  4910. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4911. /**
  4912. * Returns the reciprocal of the parameter `(1/x)`.
  4913. *
  4914. * @tsl
  4915. * @function
  4916. * @param {Node | number} x - The parameter.
  4917. * @returns {Node}
  4918. */
  4919. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4920. /**
  4921. * Truncates the parameter, removing the fractional part.
  4922. *
  4923. * @tsl
  4924. * @function
  4925. * @param {Node | number} x - The parameter.
  4926. * @returns {Node}
  4927. */
  4928. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4929. /**
  4930. * Returns the sum of the absolute derivatives in x and y.
  4931. *
  4932. * @tsl
  4933. * @function
  4934. * @param {Node | number} x - The parameter.
  4935. * @returns {Node}
  4936. */
  4937. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4938. /**
  4939. * Returns the transpose of a matrix.
  4940. *
  4941. * @tsl
  4942. * @function
  4943. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4944. * @returns {Node}
  4945. */
  4946. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4947. /**
  4948. * Returns the determinant of a matrix.
  4949. *
  4950. * @tsl
  4951. * @function
  4952. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4953. * @returns {Node<float>}
  4954. */
  4955. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4956. /**
  4957. * Returns the inverse of a matrix.
  4958. *
  4959. * @tsl
  4960. * @function
  4961. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4962. * @returns {Node<mat2|mat3|mat4>}
  4963. */
  4964. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4965. // 2 inputs
  4966. /**
  4967. * Returns `true` if `x` equals `y`.
  4968. *
  4969. * @tsl
  4970. * @function
  4971. * @param {Node | number} x - The first parameter.
  4972. * @param {Node | number} y - The second parameter.
  4973. * @deprecated since r175. Use {@link equal} instead.
  4974. * @returns {Node<bool>}
  4975. */
  4976. const equals = ( x, y ) => { // @deprecated, r172
  4977. warn( 'TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4978. return equal( x, y );
  4979. };
  4980. /**
  4981. * Returns the least of the given values.
  4982. *
  4983. * @tsl
  4984. * @function
  4985. * @param {...(Node | number)} values - The values to compare.
  4986. * @returns {Node}
  4987. */
  4988. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4989. /**
  4990. * Returns the greatest of the given values.
  4991. *
  4992. * @tsl
  4993. * @function
  4994. * @param {...(Node | number)} values - The values to compare.
  4995. * @returns {Node}
  4996. */
  4997. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4998. /**
  4999. * Generate a step function by comparing two values.
  5000. *
  5001. * @tsl
  5002. * @function
  5003. * @param {Node | number} x - The y parameter.
  5004. * @param {Node | number} y - The x parameter.
  5005. * @returns {Node}
  5006. */
  5007. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  5008. /**
  5009. * Calculates the reflection direction for an incident vector.
  5010. *
  5011. * @tsl
  5012. * @function
  5013. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5014. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5015. * @returns {Node<vec2|vec3|vec4>}
  5016. */
  5017. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  5018. /**
  5019. * Calculates the distance between two points.
  5020. *
  5021. * @tsl
  5022. * @function
  5023. * @param {Node<vec2|vec3|vec4>} x - The first point.
  5024. * @param {Node<vec2|vec3|vec4>} y - The second point.
  5025. * @returns {Node<float>}
  5026. */
  5027. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  5028. /**
  5029. * Calculates the absolute difference between two values.
  5030. *
  5031. * @tsl
  5032. * @function
  5033. * @param {Node | number} x - The first parameter.
  5034. * @param {Node | number} y - The second parameter.
  5035. * @returns {Node}
  5036. */
  5037. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  5038. /**
  5039. * Calculates the dot product of two vectors.
  5040. *
  5041. * @tsl
  5042. * @function
  5043. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  5044. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5045. * @returns {Node<float>}
  5046. */
  5047. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5048. /**
  5049. * Calculates the cross product of two vectors.
  5050. *
  5051. * @tsl
  5052. * @function
  5053. * @param {Node<vec2|vec3>} x - The first vector.
  5054. * @param {Node<vec2|vec3>} y - The second vector.
  5055. * @returns {Node<float|vec3>}
  5056. */
  5057. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5058. /**
  5059. * Return the value of the first parameter raised to the power of the second one.
  5060. *
  5061. * @tsl
  5062. * @function
  5063. * @param {Node | number} x - The first parameter.
  5064. * @param {Node | number} y - The second parameter.
  5065. * @returns {Node}
  5066. */
  5067. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5068. /**
  5069. * Returns the square of the parameter.
  5070. *
  5071. * @tsl
  5072. * @function
  5073. * @param {Node | number} x - The first parameter.
  5074. * @returns {Node}
  5075. */
  5076. const pow2 = ( x ) => mul( x, x );
  5077. /**
  5078. * Returns the cube of the parameter.
  5079. *
  5080. * @tsl
  5081. * @function
  5082. * @param {Node | number} x - The first parameter.
  5083. * @returns {Node}
  5084. */
  5085. const pow3 = ( x ) => mul( x, x, x );
  5086. /**
  5087. * Returns the fourth power of the parameter.
  5088. *
  5089. * @tsl
  5090. * @function
  5091. * @param {Node | number} x - The first parameter.
  5092. * @returns {Node}
  5093. */
  5094. const pow4 = ( x ) => mul( x, x, x, x );
  5095. /**
  5096. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5097. *
  5098. * @tsl
  5099. * @function
  5100. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5101. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5102. * @returns {Node}
  5103. */
  5104. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5105. /**
  5106. * Returns the cube root of a number.
  5107. *
  5108. * @tsl
  5109. * @function
  5110. * @param {Node | number} a - The first parameter.
  5111. * @returns {Node}
  5112. */
  5113. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5114. /**
  5115. * Calculate the squared length of a vector.
  5116. *
  5117. * @tsl
  5118. * @function
  5119. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5120. * @returns {Node<float>}
  5121. */
  5122. const lengthSq = ( a ) => dot( a, a );
  5123. /**
  5124. * Linearly interpolates between two values.
  5125. *
  5126. * @tsl
  5127. * @function
  5128. * @param {Node | number} a - The first parameter.
  5129. * @param {Node | number} b - The second parameter.
  5130. * @param {Node | number} t - The interpolation value.
  5131. * @returns {Node}
  5132. */
  5133. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5134. /**
  5135. * Constrains a value to lie between two further values.
  5136. *
  5137. * @tsl
  5138. * @function
  5139. * @param {Node | number} value - The value to constrain.
  5140. * @param {Node | number} [low=0] - The lower bound.
  5141. * @param {Node | number} [high=1] - The upper bound.
  5142. * @returns {Node}
  5143. */
  5144. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  5145. /**
  5146. * Constrains a value between `0` and `1`.
  5147. *
  5148. * @tsl
  5149. * @function
  5150. * @param {Node | number} value - The value to constrain.
  5151. * @returns {Node}
  5152. */
  5153. const saturate = ( value ) => clamp( value );
  5154. /**
  5155. * Calculates the refraction direction for an incident vector.
  5156. *
  5157. * @tsl
  5158. * @function
  5159. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5160. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5161. * @param {Node<float>} eta - The ratio of indices of refraction.
  5162. * @returns {Node<vec2|vec3|vec4>}
  5163. */
  5164. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5165. /**
  5166. * Performs a Hermite interpolation between two values.
  5167. *
  5168. * @tsl
  5169. * @function
  5170. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5171. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5172. * @param {Node | number} x - The source value for interpolation.
  5173. * @returns {Node}
  5174. */
  5175. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5176. /**
  5177. * Returns a vector pointing in the same direction as another.
  5178. *
  5179. * @tsl
  5180. * @function
  5181. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5182. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5183. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5184. * @returns {Node<vec2|vec3|vec4>}
  5185. */
  5186. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5187. /**
  5188. * Returns a random value for the given uv.
  5189. *
  5190. * @tsl
  5191. * @function
  5192. * @param {Node<vec2>} uv - The uv node.
  5193. * @returns {Node<float>}
  5194. */
  5195. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5196. const a = 12.9898, b = 78.233, c = 43758.5453;
  5197. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5198. return fract( sin( sn ).mul( c ) );
  5199. } );
  5200. /**
  5201. * Alias for `mix()` with a different parameter order.
  5202. *
  5203. * @tsl
  5204. * @function
  5205. * @param {Node | number} t - The interpolation value.
  5206. * @param {Node | number} e1 - The first parameter.
  5207. * @param {Node | number} e2 - The second parameter.
  5208. * @returns {Node}
  5209. */
  5210. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5211. /**
  5212. * Alias for `smoothstep()` with a different parameter order.
  5213. *
  5214. * @tsl
  5215. * @function
  5216. * @param {Node | number} x - The source value for interpolation.
  5217. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5218. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5219. * @returns {Node}
  5220. */
  5221. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5222. /**
  5223. * Alias for `step()` with a different parameter order.
  5224. *
  5225. * @tsl
  5226. * @function
  5227. * @param {Node | number} x - The source value for interpolation.
  5228. * @param {Node | number} edge - The edge value.
  5229. * @returns {Node}
  5230. */
  5231. const stepElement = ( x, edge ) => step( edge, x );
  5232. /**
  5233. * Returns the arc-tangent of the quotient of its parameters.
  5234. *
  5235. * @tsl
  5236. * @function
  5237. * @deprecated since r172. Use {@link atan} instead.
  5238. *
  5239. * @param {Node | number} y - The y parameter.
  5240. * @param {Node | number} x - The x parameter.
  5241. * @returns {Node}
  5242. */
  5243. const atan2 = ( y, x ) => { // @deprecated, r172
  5244. warn( 'TSL: "atan2" is overloaded. Use "atan" instead.' );
  5245. return atan( y, x );
  5246. };
  5247. // GLSL alias function
  5248. const faceforward = faceForward;
  5249. const inversesqrt = inverseSqrt;
  5250. // Method chaining
  5251. addMethodChaining( 'all', all );
  5252. addMethodChaining( 'any', any );
  5253. addMethodChaining( 'equals', equals );
  5254. addMethodChaining( 'radians', radians );
  5255. addMethodChaining( 'degrees', degrees );
  5256. addMethodChaining( 'exp', exp );
  5257. addMethodChaining( 'exp2', exp2 );
  5258. addMethodChaining( 'log', log );
  5259. addMethodChaining( 'log2', log2 );
  5260. addMethodChaining( 'sqrt', sqrt );
  5261. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5262. addMethodChaining( 'floor', floor );
  5263. addMethodChaining( 'ceil', ceil );
  5264. addMethodChaining( 'normalize', normalize );
  5265. addMethodChaining( 'fract', fract );
  5266. addMethodChaining( 'sin', sin );
  5267. addMethodChaining( 'cos', cos );
  5268. addMethodChaining( 'tan', tan );
  5269. addMethodChaining( 'asin', asin );
  5270. addMethodChaining( 'acos', acos );
  5271. addMethodChaining( 'atan', atan );
  5272. addMethodChaining( 'abs', abs );
  5273. addMethodChaining( 'sign', sign );
  5274. addMethodChaining( 'length', length );
  5275. addMethodChaining( 'lengthSq', lengthSq );
  5276. addMethodChaining( 'negate', negate );
  5277. addMethodChaining( 'oneMinus', oneMinus );
  5278. addMethodChaining( 'dFdx', dFdx );
  5279. addMethodChaining( 'dFdy', dFdy );
  5280. addMethodChaining( 'round', round );
  5281. addMethodChaining( 'reciprocal', reciprocal );
  5282. addMethodChaining( 'trunc', trunc );
  5283. addMethodChaining( 'fwidth', fwidth );
  5284. addMethodChaining( 'atan2', atan2 );
  5285. addMethodChaining( 'min', min$1 );
  5286. addMethodChaining( 'max', max$1 );
  5287. addMethodChaining( 'step', stepElement );
  5288. addMethodChaining( 'reflect', reflect );
  5289. addMethodChaining( 'distance', distance );
  5290. addMethodChaining( 'dot', dot );
  5291. addMethodChaining( 'cross', cross );
  5292. addMethodChaining( 'pow', pow );
  5293. addMethodChaining( 'pow2', pow2 );
  5294. addMethodChaining( 'pow3', pow3 );
  5295. addMethodChaining( 'pow4', pow4 );
  5296. addMethodChaining( 'transformDirection', transformDirection );
  5297. addMethodChaining( 'mix', mixElement );
  5298. addMethodChaining( 'clamp', clamp );
  5299. addMethodChaining( 'refract', refract );
  5300. addMethodChaining( 'smoothstep', smoothstepElement );
  5301. addMethodChaining( 'faceForward', faceForward );
  5302. addMethodChaining( 'difference', difference );
  5303. addMethodChaining( 'saturate', saturate );
  5304. addMethodChaining( 'cbrt', cbrt );
  5305. addMethodChaining( 'transpose', transpose );
  5306. addMethodChaining( 'determinant', determinant );
  5307. addMethodChaining( 'inverse', inverse );
  5308. addMethodChaining( 'rand', rand );
  5309. /**
  5310. * Represents a logical `if/else` statement. Can be used as an alternative
  5311. * to the `If()`/`Else()` syntax.
  5312. *
  5313. * The corresponding TSL `select()` looks like so:
  5314. * ```js
  5315. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5316. * ```
  5317. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5318. * determine the outcome of the entire statement.
  5319. *
  5320. * @augments Node
  5321. */
  5322. class ConditionalNode extends Node {
  5323. static get type() {
  5324. return 'ConditionalNode';
  5325. }
  5326. /**
  5327. * Constructs a new conditional node.
  5328. *
  5329. * @param {Node} condNode - The node that defines the condition.
  5330. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5331. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5332. */
  5333. constructor( condNode, ifNode, elseNode = null ) {
  5334. super();
  5335. /**
  5336. * The node that defines the condition.
  5337. *
  5338. * @type {Node}
  5339. */
  5340. this.condNode = condNode;
  5341. /**
  5342. * The node that is evaluate when the condition ends up `true`.
  5343. *
  5344. * @type {Node}
  5345. */
  5346. this.ifNode = ifNode;
  5347. /**
  5348. * The node that is evaluate when the condition ends up `false`.
  5349. *
  5350. * @type {?Node}
  5351. * @default null
  5352. */
  5353. this.elseNode = elseNode;
  5354. }
  5355. /**
  5356. * This method is overwritten since the node type is inferred from the if/else
  5357. * nodes.
  5358. *
  5359. * @param {NodeBuilder} builder - The current node builder.
  5360. * @return {string} The node type.
  5361. */
  5362. getNodeType( builder ) {
  5363. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5364. if ( ifNode === undefined ) {
  5365. // fallback setup
  5366. builder.flowBuildStage( this, 'setup' );
  5367. return this.getNodeType( builder );
  5368. }
  5369. const ifType = ifNode.getNodeType( builder );
  5370. if ( elseNode !== null ) {
  5371. const elseType = elseNode.getNodeType( builder );
  5372. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5373. return elseType;
  5374. }
  5375. }
  5376. return ifType;
  5377. }
  5378. setup( builder ) {
  5379. const condNode = this.condNode;
  5380. const ifNode = this.ifNode.isolate();
  5381. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5382. //
  5383. const currentNodeBlock = builder.context.nodeBlock;
  5384. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5385. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5386. //
  5387. const isUniformFlow = builder.context.uniformFlow;
  5388. const properties = builder.getNodeProperties( this );
  5389. properties.condNode = condNode;
  5390. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5391. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5392. }
  5393. generate( builder, output ) {
  5394. const type = this.getNodeType( builder );
  5395. const nodeData = builder.getDataFromNode( this );
  5396. if ( nodeData.nodeProperty !== undefined ) {
  5397. return nodeData.nodeProperty;
  5398. }
  5399. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5400. const functionNode = builder.currentFunctionNode;
  5401. const needsOutput = output !== 'void';
  5402. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5403. nodeData.nodeProperty = nodeProperty;
  5404. const nodeSnippet = condNode.build( builder, 'bool' );
  5405. const isUniformFlow = builder.context.uniformFlow;
  5406. if ( isUniformFlow && elseNode !== null ) {
  5407. const ifSnippet = ifNode.build( builder, type );
  5408. const elseSnippet = elseNode.build( builder, type );
  5409. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5410. // TODO: If node property already exists return something else
  5411. return builder.format( mathSnippet, type, output );
  5412. }
  5413. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5414. let ifSnippet = ifNode.build( builder, type );
  5415. if ( ifSnippet ) {
  5416. if ( needsOutput ) {
  5417. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5418. } else {
  5419. ifSnippet = 'return ' + ifSnippet + ';';
  5420. if ( functionNode === null ) {
  5421. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5422. ifSnippet = '// ' + ifSnippet;
  5423. }
  5424. }
  5425. }
  5426. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5427. if ( elseNode !== null ) {
  5428. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5429. let elseSnippet = elseNode.build( builder, type );
  5430. if ( elseSnippet ) {
  5431. if ( needsOutput ) {
  5432. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5433. } else {
  5434. elseSnippet = 'return ' + elseSnippet + ';';
  5435. if ( functionNode === null ) {
  5436. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5437. elseSnippet = '// ' + elseSnippet;
  5438. }
  5439. }
  5440. }
  5441. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5442. } else {
  5443. builder.addFlowCode( '\n\n' );
  5444. }
  5445. return builder.format( nodeProperty, type, output );
  5446. }
  5447. }
  5448. /**
  5449. * TSL function for creating a conditional node.
  5450. *
  5451. * @tsl
  5452. * @function
  5453. * @param {Node} condNode - The node that defines the condition.
  5454. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5455. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5456. * @returns {ConditionalNode}
  5457. */
  5458. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5459. addMethodChaining( 'select', select );
  5460. /**
  5461. * This node can be used as a context management component for another node.
  5462. * {@link NodeBuilder} performs its node building process in a specific context and
  5463. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5464. *
  5465. * ```js
  5466. *node.context( { getUV: () => customCoord } );
  5467. *\// 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 label context value for a given node.
  5606. *
  5607. * @tsl
  5608. * @function
  5609. * @deprecated
  5610. * @param {Node} node - The node whose context should be modified.
  5611. * @param {string} name - The name/label to set.
  5612. * @returns {ContextNode}
  5613. */
  5614. function label( node, name ) {
  5615. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5616. return setName( node, name );
  5617. }
  5618. addMethodChaining( 'context', context );
  5619. addMethodChaining( 'label', label );
  5620. addMethodChaining( 'uniformFlow', uniformFlow );
  5621. addMethodChaining( 'setName', setName );
  5622. /**
  5623. * Class for representing shader variables as nodes. Variables are created from
  5624. * existing nodes like the following:
  5625. *
  5626. * ```js
  5627. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5628. * ```
  5629. *
  5630. * @augments Node
  5631. */
  5632. class VarNode extends Node {
  5633. static get type() {
  5634. return 'VarNode';
  5635. }
  5636. /**
  5637. * Constructs a new variable node.
  5638. *
  5639. * @param {Node} node - The node for which a variable should be created.
  5640. * @param {?string} [name=null] - The name of the variable in the shader.
  5641. * @param {boolean} [readOnly=false] - The read-only flag.
  5642. */
  5643. constructor( node, name = null, readOnly = false ) {
  5644. super();
  5645. /**
  5646. * The node for which a variable should be created.
  5647. *
  5648. * @type {Node}
  5649. */
  5650. this.node = node;
  5651. /**
  5652. * The name of the variable in the shader. If no name is defined,
  5653. * the node system auto-generates one.
  5654. *
  5655. * @type {?string}
  5656. * @default null
  5657. */
  5658. this.name = name;
  5659. /**
  5660. * `VarNode` sets this property to `true` by default.
  5661. *
  5662. * @type {boolean}
  5663. * @default true
  5664. */
  5665. this.global = true;
  5666. /**
  5667. * This flag can be used for type testing.
  5668. *
  5669. * @type {boolean}
  5670. * @readonly
  5671. * @default true
  5672. */
  5673. this.isVarNode = true;
  5674. /**
  5675. *
  5676. * The read-only flag.
  5677. *
  5678. * @type {boolean}
  5679. * @default false
  5680. */
  5681. this.readOnly = readOnly;
  5682. /**
  5683. *
  5684. * Add this flag to the node system to indicate that this node require parents.
  5685. *
  5686. * @type {boolean}
  5687. * @default true
  5688. */
  5689. this.parents = true;
  5690. /**
  5691. * This flag is used to indicate that this node is used for intent.
  5692. *
  5693. * @type {boolean}
  5694. * @default false
  5695. */
  5696. this.intent = false;
  5697. }
  5698. /**
  5699. * Sets the intent flag for this node.
  5700. *
  5701. * This flag is used to indicate that this node is used for intent
  5702. * and should not be built directly. Instead, it is used to indicate that
  5703. * the node should be treated as a variable intent.
  5704. *
  5705. * It's useful for assigning variables without needing creating a new variable node.
  5706. *
  5707. * @param {boolean} value - The value to set for the intent flag.
  5708. * @returns {VarNode} This node.
  5709. */
  5710. setIntent( value ) {
  5711. this.intent = value;
  5712. return this;
  5713. }
  5714. /**
  5715. * Returns the intent flag of this node.
  5716. *
  5717. * @return {boolean} The intent flag.
  5718. */
  5719. getIntent() {
  5720. return this.intent;
  5721. }
  5722. getMemberType( builder, name ) {
  5723. return this.node.getMemberType( builder, name );
  5724. }
  5725. getElementType( builder ) {
  5726. return this.node.getElementType( builder );
  5727. }
  5728. getNodeType( builder ) {
  5729. return this.node.getNodeType( builder );
  5730. }
  5731. getArrayCount( builder ) {
  5732. return this.node.getArrayCount( builder );
  5733. }
  5734. isAssign( builder ) {
  5735. const properties = builder.getNodeProperties( this );
  5736. let assign = properties.assign;
  5737. if ( assign !== true ) {
  5738. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  5739. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  5740. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  5741. if ( shaderNodeData.hasLoop ) {
  5742. assign = true;
  5743. }
  5744. }
  5745. }
  5746. }
  5747. return assign;
  5748. }
  5749. build( ...params ) {
  5750. const builder = params[ 0 ];
  5751. if ( this._hasStack( builder ) === false && builder.buildStage === 'setup' ) {
  5752. if ( builder.context.nodeLoop || builder.context.nodeBlock ) {
  5753. builder.getBaseStack().addToStack( this );
  5754. }
  5755. }
  5756. if ( this.intent === true ) {
  5757. if ( this.isAssign( builder ) !== true ) {
  5758. return this.node.build( ...params );
  5759. }
  5760. }
  5761. return super.build( ...params );
  5762. }
  5763. generate( builder ) {
  5764. const { node, name, readOnly } = this;
  5765. const { renderer } = builder;
  5766. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5767. let isDeterministic = false;
  5768. let shouldTreatAsReadOnly = false;
  5769. if ( readOnly ) {
  5770. isDeterministic = builder.isDeterministic( node );
  5771. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5772. }
  5773. const nodeType = this.getNodeType( builder );
  5774. if ( nodeType == 'void' ) {
  5775. if ( this.intent !== true ) {
  5776. error( 'TSL: ".toVar()" can not be used with void type.' );
  5777. }
  5778. const snippet = node.build( builder );
  5779. return snippet;
  5780. }
  5781. const vectorType = builder.getVectorType( nodeType );
  5782. const snippet = node.build( builder, vectorType );
  5783. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5784. const propertyName = builder.getPropertyName( nodeVar );
  5785. let declarationPrefix = propertyName;
  5786. if ( shouldTreatAsReadOnly ) {
  5787. if ( isWebGPUBackend ) {
  5788. declarationPrefix = isDeterministic
  5789. ? `const ${ propertyName }`
  5790. : `let ${ propertyName }`;
  5791. } else {
  5792. const count = node.getArrayCount( builder );
  5793. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5794. }
  5795. }
  5796. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5797. return propertyName;
  5798. }
  5799. _hasStack( builder ) {
  5800. const nodeData = builder.getDataFromNode( this );
  5801. return nodeData.stack !== undefined;
  5802. }
  5803. }
  5804. /**
  5805. * TSL function for creating a var node.
  5806. *
  5807. * @tsl
  5808. * @function
  5809. * @param {Node} node - The node for which a variable should be created.
  5810. * @param {?string} name - The name of the variable in the shader.
  5811. * @returns {VarNode}
  5812. */
  5813. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5814. /**
  5815. * TSL function for creating a var node.
  5816. *
  5817. * @tsl
  5818. * @function
  5819. * @param {Node} node - The node for which a variable should be created.
  5820. * @param {?string} name - The name of the variable in the shader.
  5821. * @returns {VarNode}
  5822. */
  5823. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5824. /**
  5825. * TSL function for creating a const node.
  5826. *
  5827. * @tsl
  5828. * @function
  5829. * @param {Node} node - The node for which a constant should be created.
  5830. * @param {?string} name - The name of the constant in the shader.
  5831. * @returns {VarNode}
  5832. */
  5833. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5834. //
  5835. //
  5836. /**
  5837. * TSL function for creating a var intent node.
  5838. *
  5839. * @tsl
  5840. * @function
  5841. * @param {Node} node - The node for which a variable should be created.
  5842. * @param {?string} name - The name of the variable in the shader.
  5843. * @returns {VarNode}
  5844. */
  5845. const VarIntent = ( node ) => {
  5846. return createVar( node ).setIntent( true ).toStack();
  5847. };
  5848. // Method chaining
  5849. addMethodChaining( 'toVar', Var );
  5850. addMethodChaining( 'toConst', Const );
  5851. addMethodChaining( 'toVarIntent', VarIntent );
  5852. /**
  5853. * This node is used to build a sub-build in the node system.
  5854. *
  5855. * @augments Node
  5856. * @param {Node} node - The node to be built in the sub-build.
  5857. * @param {string} name - The name of the sub-build.
  5858. * @param {?string} [nodeType=null] - The type of the node, if known.
  5859. */
  5860. class SubBuildNode extends Node {
  5861. static get type() {
  5862. return 'SubBuild';
  5863. }
  5864. constructor( node, name, nodeType = null ) {
  5865. super( nodeType );
  5866. /**
  5867. * The node to be built in the sub-build.
  5868. *
  5869. * @type {Node}
  5870. */
  5871. this.node = node;
  5872. /**
  5873. * The name of the sub-build.
  5874. *
  5875. * @type {string}
  5876. */
  5877. this.name = name;
  5878. /**
  5879. * This flag can be used for type testing.
  5880. *
  5881. * @type {boolean}
  5882. * @readonly
  5883. * @default true
  5884. */
  5885. this.isSubBuildNode = true;
  5886. }
  5887. getNodeType( builder ) {
  5888. if ( this.nodeType !== null ) return this.nodeType;
  5889. builder.addSubBuild( this.name );
  5890. const nodeType = this.node.getNodeType( builder );
  5891. builder.removeSubBuild();
  5892. return nodeType;
  5893. }
  5894. build( builder, ...params ) {
  5895. builder.addSubBuild( this.name );
  5896. const data = this.node.build( builder, ...params );
  5897. builder.removeSubBuild();
  5898. return data;
  5899. }
  5900. }
  5901. /**
  5902. * Creates a new sub-build node.
  5903. *
  5904. * @tsl
  5905. * @function
  5906. * @param {Node} node - The node to be built in the sub-build.
  5907. * @param {string} name - The name of the sub-build.
  5908. * @param {?string} [type=null] - The type of the node, if known.
  5909. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5910. */
  5911. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5912. /**
  5913. * Class for representing shader varyings as nodes. Varyings are create from
  5914. * existing nodes like the following:
  5915. *
  5916. * ```js
  5917. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5918. * ```
  5919. *
  5920. * @augments Node
  5921. */
  5922. class VaryingNode extends Node {
  5923. static get type() {
  5924. return 'VaryingNode';
  5925. }
  5926. /**
  5927. * Constructs a new varying node.
  5928. *
  5929. * @param {Node} node - The node for which a varying should be created.
  5930. * @param {?string} name - The name of the varying in the shader.
  5931. */
  5932. constructor( node, name = null ) {
  5933. super();
  5934. /**
  5935. * The node for which a varying should be created.
  5936. *
  5937. * @type {Node}
  5938. */
  5939. this.node = node;
  5940. /**
  5941. * The name of the varying in the shader. If no name is defined,
  5942. * the node system auto-generates one.
  5943. *
  5944. * @type {?string}
  5945. * @default null
  5946. */
  5947. this.name = name;
  5948. /**
  5949. * This flag can be used for type testing.
  5950. *
  5951. * @type {boolean}
  5952. * @readonly
  5953. * @default true
  5954. */
  5955. this.isVaryingNode = true;
  5956. /**
  5957. * The interpolation type of the varying data.
  5958. *
  5959. * @type {?string}
  5960. * @default null
  5961. */
  5962. this.interpolationType = null;
  5963. /**
  5964. * The interpolation sampling type of varying data.
  5965. *
  5966. * @type {?string}
  5967. * @default null
  5968. */
  5969. this.interpolationSampling = null;
  5970. /**
  5971. * This flag is used for global cache.
  5972. *
  5973. * @type {boolean}
  5974. * @default true
  5975. */
  5976. this.global = true;
  5977. }
  5978. /**
  5979. * Defines the interpolation type of the varying.
  5980. *
  5981. * @param {string} type - The interpolation type.
  5982. * @param {?string} sampling - The interpolation sampling type
  5983. * @return {VaryingNode} A reference to this node.
  5984. */
  5985. setInterpolation( type, sampling = null ) {
  5986. this.interpolationType = type;
  5987. this.interpolationSampling = sampling;
  5988. return this;
  5989. }
  5990. getHash( builder ) {
  5991. return this.name || super.getHash( builder );
  5992. }
  5993. getNodeType( builder ) {
  5994. // VaryingNode is auto type
  5995. return this.node.getNodeType( builder );
  5996. }
  5997. /**
  5998. * This method performs the setup of a varying node with the current node builder.
  5999. *
  6000. * @param {NodeBuilder} builder - The current node builder.
  6001. * @return {NodeVarying} The node varying from the node builder.
  6002. */
  6003. setupVarying( builder ) {
  6004. const properties = builder.getNodeProperties( this );
  6005. let varying = properties.varying;
  6006. if ( varying === undefined ) {
  6007. const name = this.name;
  6008. const type = this.getNodeType( builder );
  6009. const interpolationType = this.interpolationType;
  6010. const interpolationSampling = this.interpolationSampling;
  6011. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  6012. properties.node = subBuild( this.node, 'VERTEX' );
  6013. }
  6014. // this property can be used to check if the varying can be optimized for a variable
  6015. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  6016. return varying;
  6017. }
  6018. setup( builder ) {
  6019. this.setupVarying( builder );
  6020. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6021. }
  6022. analyze( builder ) {
  6023. this.setupVarying( builder );
  6024. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6025. }
  6026. generate( builder ) {
  6027. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  6028. const properties = builder.getNodeProperties( this );
  6029. const varying = this.setupVarying( builder );
  6030. if ( properties[ propertyKey ] === undefined ) {
  6031. const type = this.getNodeType( builder );
  6032. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  6033. // force node run in vertex stage
  6034. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  6035. properties[ propertyKey ] = propertyName;
  6036. }
  6037. return builder.getPropertyName( varying );
  6038. }
  6039. }
  6040. /**
  6041. * TSL function for creating a varying node.
  6042. *
  6043. * @tsl
  6044. * @function
  6045. * @param {Node} node - The node for which a varying should be created.
  6046. * @param {?string} name - The name of the varying in the shader.
  6047. * @returns {VaryingNode}
  6048. */
  6049. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  6050. /**
  6051. * Computes a node in the vertex stage.
  6052. *
  6053. * @tsl
  6054. * @function
  6055. * @param {Node} node - The node which should be executed in the vertex stage.
  6056. * @returns {VaryingNode}
  6057. */
  6058. const vertexStage = ( node ) => varying( node );
  6059. addMethodChaining( 'toVarying', varying );
  6060. addMethodChaining( 'toVertexStage', vertexStage );
  6061. // Deprecated
  6062. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  6063. warn( 'TSL: .varying() has been renamed to .toVarying().' );
  6064. return varying( ...params );
  6065. } );
  6066. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  6067. warn( 'TSL: .vertexStage() has been renamed to .toVertexStage().' );
  6068. return varying( ...params );
  6069. } );
  6070. /**
  6071. * Converts the given color value from sRGB to linear-sRGB color space.
  6072. *
  6073. * @tsl
  6074. * @function
  6075. * @param {Node<vec3>} color - The sRGB color.
  6076. * @return {Node<vec3>} The linear-sRGB color.
  6077. */
  6078. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6079. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6080. const b = color.mul( 0.0773993808 );
  6081. const factor = color.lessThanEqual( 0.04045 );
  6082. const rgbResult = mix( a, b, factor );
  6083. return rgbResult;
  6084. } ).setLayout( {
  6085. name: 'sRGBTransferEOTF',
  6086. type: 'vec3',
  6087. inputs: [
  6088. { name: 'color', type: 'vec3' }
  6089. ]
  6090. } );
  6091. /**
  6092. * Converts the given color value from linear-sRGB to sRGB color space.
  6093. *
  6094. * @tsl
  6095. * @function
  6096. * @param {Node<vec3>} color - The linear-sRGB color.
  6097. * @return {Node<vec3>} The sRGB color.
  6098. */
  6099. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6100. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6101. const b = color.mul( 12.92 );
  6102. const factor = color.lessThanEqual( 0.0031308 );
  6103. const rgbResult = mix( a, b, factor );
  6104. return rgbResult;
  6105. } ).setLayout( {
  6106. name: 'sRGBTransferOETF',
  6107. type: 'vec3',
  6108. inputs: [
  6109. { name: 'color', type: 'vec3' }
  6110. ]
  6111. } );
  6112. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6113. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6114. /**
  6115. * This node represents a color space conversion. Meaning it converts
  6116. * a color value from a source to a target color space.
  6117. *
  6118. * @augments TempNode
  6119. */
  6120. class ColorSpaceNode extends TempNode {
  6121. static get type() {
  6122. return 'ColorSpaceNode';
  6123. }
  6124. /**
  6125. * Constructs a new color space node.
  6126. *
  6127. * @param {Node} colorNode - Represents the color to convert.
  6128. * @param {string} source - The source color space.
  6129. * @param {string} target - The target color space.
  6130. */
  6131. constructor( colorNode, source, target ) {
  6132. super( 'vec4' );
  6133. /**
  6134. * Represents the color to convert.
  6135. *
  6136. * @type {Node}
  6137. */
  6138. this.colorNode = colorNode;
  6139. /**
  6140. * The source color space.
  6141. *
  6142. * @type {string}
  6143. */
  6144. this.source = source;
  6145. /**
  6146. * The target color space.
  6147. *
  6148. * @type {string}
  6149. */
  6150. this.target = target;
  6151. }
  6152. /**
  6153. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6154. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6155. * color management and renderer.
  6156. *
  6157. * @param {NodeBuilder} builder - The current node builder.
  6158. * @param {string} colorSpace - The color space to resolve.
  6159. * @return {string} The resolved color space.
  6160. */
  6161. resolveColorSpace( builder, colorSpace ) {
  6162. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6163. return ColorManagement.workingColorSpace;
  6164. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6165. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6166. }
  6167. return colorSpace;
  6168. }
  6169. setup( builder ) {
  6170. const { colorNode } = this;
  6171. const source = this.resolveColorSpace( builder, this.source );
  6172. const target = this.resolveColorSpace( builder, this.target );
  6173. let outputNode = colorNode;
  6174. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6175. return outputNode;
  6176. }
  6177. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6178. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6179. }
  6180. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6181. outputNode = vec4(
  6182. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6183. outputNode.a
  6184. );
  6185. }
  6186. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6187. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6188. }
  6189. return outputNode;
  6190. }
  6191. }
  6192. /**
  6193. * TSL function for converting a given color node from the current working color space to the given color space.
  6194. *
  6195. * @tsl
  6196. * @function
  6197. * @param {Node} node - Represents the node to convert.
  6198. * @param {string} targetColorSpace - The target color space.
  6199. * @returns {ColorSpaceNode}
  6200. */
  6201. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6202. /**
  6203. * TSL function for converting a given color node from the given color space to the current working color space.
  6204. *
  6205. * @tsl
  6206. * @function
  6207. * @param {Node} node - Represents the node to convert.
  6208. * @param {string} sourceColorSpace - The source color space.
  6209. * @returns {ColorSpaceNode}
  6210. */
  6211. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6212. /**
  6213. * TSL function for converting a given color node from one color space to another one.
  6214. *
  6215. * @tsl
  6216. * @function
  6217. * @param {Node} node - Represents the node to convert.
  6218. * @param {string} sourceColorSpace - The source color space.
  6219. * @param {string} targetColorSpace - The target color space.
  6220. * @returns {ColorSpaceNode}
  6221. */
  6222. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6223. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6224. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6225. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  6226. /**
  6227. * This class is only relevant if the referenced property is array-like.
  6228. * In this case, `ReferenceElementNode` allows to refer to a specific
  6229. * element inside the data structure via an index.
  6230. *
  6231. * @augments ArrayElementNode
  6232. */
  6233. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6234. static get type() {
  6235. return 'ReferenceElementNode';
  6236. }
  6237. /**
  6238. * Constructs a new reference element node.
  6239. *
  6240. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6241. * @param {Node} indexNode - The index node that defines the element access.
  6242. */
  6243. constructor( referenceNode, indexNode ) {
  6244. super( referenceNode, indexNode );
  6245. /**
  6246. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6247. * property references to the current node.
  6248. *
  6249. * @type {?ReferenceBaseNode}
  6250. * @default null
  6251. */
  6252. this.referenceNode = referenceNode;
  6253. /**
  6254. * This flag can be used for type testing.
  6255. *
  6256. * @type {boolean}
  6257. * @readonly
  6258. * @default true
  6259. */
  6260. this.isReferenceElementNode = true;
  6261. }
  6262. /**
  6263. * This method is overwritten since the node type is inferred from
  6264. * the uniform type of the reference node.
  6265. *
  6266. * @return {string} The node type.
  6267. */
  6268. getNodeType() {
  6269. return this.referenceNode.uniformType;
  6270. }
  6271. generate( builder ) {
  6272. const snippet = super.generate( builder );
  6273. const arrayType = this.referenceNode.getNodeType();
  6274. const elementType = this.getNodeType();
  6275. return builder.format( snippet, arrayType, elementType );
  6276. }
  6277. };
  6278. /**
  6279. * Base class for nodes which establishes a reference to a property of another object.
  6280. * In this way, the value of the node is automatically linked to the value of
  6281. * referenced object. Reference nodes internally represent the linked value
  6282. * as a uniform.
  6283. *
  6284. * @augments Node
  6285. */
  6286. class ReferenceBaseNode extends Node {
  6287. static get type() {
  6288. return 'ReferenceBaseNode';
  6289. }
  6290. /**
  6291. * Constructs a new reference base node.
  6292. *
  6293. * @param {string} property - The name of the property the node refers to.
  6294. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6295. * @param {?Object} [object=null] - The object the property belongs to.
  6296. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6297. */
  6298. constructor( property, uniformType, object = null, count = null ) {
  6299. super();
  6300. /**
  6301. * The name of the property the node refers to.
  6302. *
  6303. * @type {string}
  6304. */
  6305. this.property = property;
  6306. /**
  6307. * The uniform type that should be used to represent the property value.
  6308. *
  6309. * @type {string}
  6310. */
  6311. this.uniformType = uniformType;
  6312. /**
  6313. * The object the property belongs to.
  6314. *
  6315. * @type {?Object}
  6316. * @default null
  6317. */
  6318. this.object = object;
  6319. /**
  6320. * When the linked property is an array, this parameter defines its length.
  6321. *
  6322. * @type {?number}
  6323. * @default null
  6324. */
  6325. this.count = count;
  6326. /**
  6327. * The property name might have dots so nested properties can be referred.
  6328. * The hierarchy of the names is stored inside this array.
  6329. *
  6330. * @type {Array<string>}
  6331. */
  6332. this.properties = property.split( '.' );
  6333. /**
  6334. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6335. * since the final reference might be updated from calling code.
  6336. *
  6337. * @type {?Object}
  6338. * @default null
  6339. */
  6340. this.reference = object;
  6341. /**
  6342. * The uniform node that holds the value of the reference node.
  6343. *
  6344. * @type {UniformNode}
  6345. * @default null
  6346. */
  6347. this.node = null;
  6348. /**
  6349. * The uniform group of the internal uniform.
  6350. *
  6351. * @type {UniformGroupNode}
  6352. * @default null
  6353. */
  6354. this.group = null;
  6355. /**
  6356. * Overwritten since reference nodes are updated per object.
  6357. *
  6358. * @type {string}
  6359. * @default 'object'
  6360. */
  6361. this.updateType = NodeUpdateType.OBJECT;
  6362. }
  6363. /**
  6364. * Sets the uniform group for this reference node.
  6365. *
  6366. * @param {UniformGroupNode} group - The uniform group to set.
  6367. * @return {ReferenceBaseNode} A reference to this node.
  6368. */
  6369. setGroup( group ) {
  6370. this.group = group;
  6371. return this;
  6372. }
  6373. /**
  6374. * When the referred property is array-like, this method can be used
  6375. * to access elements via an index node.
  6376. *
  6377. * @param {IndexNode} indexNode - indexNode.
  6378. * @return {ReferenceElementNode} A reference to an element.
  6379. */
  6380. element( indexNode ) {
  6381. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6382. }
  6383. /**
  6384. * Sets the node type which automatically defines the internal
  6385. * uniform type.
  6386. *
  6387. * @param {string} uniformType - The type to set.
  6388. */
  6389. setNodeType( uniformType ) {
  6390. const node = uniform( null, uniformType );
  6391. if ( this.group !== null ) {
  6392. node.setGroup( this.group );
  6393. }
  6394. this.node = node;
  6395. }
  6396. /**
  6397. * This method is overwritten since the node type is inferred from
  6398. * the type of the reference node.
  6399. *
  6400. * @param {NodeBuilder} builder - The current node builder.
  6401. * @return {string} The node type.
  6402. */
  6403. getNodeType( builder ) {
  6404. if ( this.node === null ) {
  6405. this.updateReference( builder );
  6406. this.updateValue();
  6407. }
  6408. return this.node.getNodeType( builder );
  6409. }
  6410. /**
  6411. * Returns the property value from the given referred object.
  6412. *
  6413. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6414. * @return {any} The value.
  6415. */
  6416. getValueFromReference( object = this.reference ) {
  6417. const { properties } = this;
  6418. let value = object[ properties[ 0 ] ];
  6419. for ( let i = 1; i < properties.length; i ++ ) {
  6420. value = value[ properties[ i ] ];
  6421. }
  6422. return value;
  6423. }
  6424. /**
  6425. * Allows to update the reference based on the given state. The state is only
  6426. * evaluated {@link ReferenceBaseNode#object} is not set.
  6427. *
  6428. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6429. * @return {Object} The updated reference.
  6430. */
  6431. updateReference( state ) {
  6432. this.reference = this.object !== null ? this.object : state.object;
  6433. return this.reference;
  6434. }
  6435. /**
  6436. * The output of the reference node is the internal uniform node.
  6437. *
  6438. * @return {UniformNode} The output node.
  6439. */
  6440. setup() {
  6441. this.updateValue();
  6442. return this.node;
  6443. }
  6444. /**
  6445. * Overwritten to update the internal uniform value.
  6446. *
  6447. * @param {NodeFrame} frame - A reference to the current node frame.
  6448. */
  6449. update( /*frame*/ ) {
  6450. this.updateValue();
  6451. }
  6452. /**
  6453. * Retrieves the value from the referred object property and uses it
  6454. * to updated the internal uniform.
  6455. */
  6456. updateValue() {
  6457. if ( this.node === null ) this.setNodeType( this.uniformType );
  6458. const value = this.getValueFromReference();
  6459. if ( Array.isArray( value ) ) {
  6460. this.node.array = value;
  6461. } else {
  6462. this.node.value = value;
  6463. }
  6464. }
  6465. }
  6466. /**
  6467. * TSL function for creating a reference base node.
  6468. *
  6469. * @tsl
  6470. * @function
  6471. * @param {string} name - The name of the property the node refers to.
  6472. * @param {string} type - The uniform type that should be used to represent the property value.
  6473. * @param {Object} object - The object the property belongs to.
  6474. * @returns {ReferenceBaseNode}
  6475. */
  6476. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6477. /**
  6478. * This node is a special type of reference node which is intended
  6479. * for linking renderer properties with node values.
  6480. * ```js
  6481. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6482. * ```
  6483. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6484. * automatically be updated.
  6485. *
  6486. * @augments ReferenceBaseNode
  6487. */
  6488. class RendererReferenceNode extends ReferenceBaseNode {
  6489. static get type() {
  6490. return 'RendererReferenceNode';
  6491. }
  6492. /**
  6493. * Constructs a new renderer reference node.
  6494. *
  6495. * @param {string} property - The name of the property the node refers to.
  6496. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6497. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6498. * the node refers to the renderer of the current state.
  6499. */
  6500. constructor( property, inputType, renderer = null ) {
  6501. super( property, inputType, renderer );
  6502. /**
  6503. * The renderer the property belongs to. When no renderer is set,
  6504. * the node refers to the renderer of the current state.
  6505. *
  6506. * @type {?Renderer}
  6507. * @default null
  6508. */
  6509. this.renderer = renderer;
  6510. this.setGroup( renderGroup );
  6511. }
  6512. /**
  6513. * Updates the reference based on the given state. The state is only evaluated
  6514. * {@link RendererReferenceNode#renderer} is not set.
  6515. *
  6516. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6517. * @return {Object} The updated reference.
  6518. */
  6519. updateReference( state ) {
  6520. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6521. return this.reference;
  6522. }
  6523. }
  6524. /**
  6525. * TSL function for creating a renderer reference node.
  6526. *
  6527. * @tsl
  6528. * @function
  6529. * @param {string} name - The name of the property the node refers to.
  6530. * @param {string} type - The uniform type that should be used to represent the property value.
  6531. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6532. * the node refers to the renderer of the current state.
  6533. * @returns {RendererReferenceNode}
  6534. */
  6535. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6536. /**
  6537. * This node represents a tone mapping operation.
  6538. *
  6539. * @augments TempNode
  6540. */
  6541. class ToneMappingNode extends TempNode {
  6542. static get type() {
  6543. return 'ToneMappingNode';
  6544. }
  6545. /**
  6546. * Constructs a new tone mapping node.
  6547. *
  6548. * @param {number} toneMapping - The tone mapping type.
  6549. * @param {Node} exposureNode - The tone mapping exposure.
  6550. * @param {Node} [colorNode=null] - The color node to process.
  6551. */
  6552. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6553. super( 'vec3' );
  6554. /**
  6555. * The tone mapping type.
  6556. *
  6557. * @private
  6558. * @type {number}
  6559. */
  6560. this._toneMapping = toneMapping;
  6561. /**
  6562. * The tone mapping exposure.
  6563. *
  6564. * @type {Node}
  6565. * @default null
  6566. */
  6567. this.exposureNode = exposureNode;
  6568. /**
  6569. * Represents the color to process.
  6570. *
  6571. * @type {?Node}
  6572. * @default null
  6573. */
  6574. this.colorNode = colorNode;
  6575. }
  6576. /**
  6577. * Overwrites the default `customCacheKey()` implementation by including the tone
  6578. * mapping type into the cache key.
  6579. *
  6580. * @return {number} The hash.
  6581. */
  6582. customCacheKey() {
  6583. return hash$1( this._toneMapping );
  6584. }
  6585. /**
  6586. * Sets the tone mapping type.
  6587. *
  6588. * @param {number} value - The tone mapping type.
  6589. * @return {ToneMappingNode} A reference to this node.
  6590. */
  6591. setToneMapping( value ) {
  6592. this._toneMapping = value;
  6593. return this;
  6594. }
  6595. /**
  6596. * Gets the tone mapping type.
  6597. *
  6598. * @returns {number} The tone mapping type.
  6599. */
  6600. getToneMapping() {
  6601. return this._toneMapping;
  6602. }
  6603. setup( builder ) {
  6604. const colorNode = this.colorNode || builder.context.color;
  6605. const toneMapping = this._toneMapping;
  6606. if ( toneMapping === NoToneMapping ) return colorNode;
  6607. let outputNode = null;
  6608. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6609. if ( toneMappingFn !== null ) {
  6610. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6611. } else {
  6612. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6613. outputNode = colorNode;
  6614. }
  6615. return outputNode;
  6616. }
  6617. }
  6618. /**
  6619. * TSL function for creating a tone mapping node.
  6620. *
  6621. * @tsl
  6622. * @function
  6623. * @param {number} mapping - The tone mapping type.
  6624. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6625. * @param {Node<vec3> | Color} color - The color node to process.
  6626. * @returns {ToneMappingNode<vec3>}
  6627. */
  6628. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6629. /**
  6630. * TSL object that represents the global tone mapping exposure of the renderer.
  6631. *
  6632. * @tsl
  6633. * @type {RendererReferenceNode<vec3>}
  6634. */
  6635. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6636. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6637. /**
  6638. * Internal buffer attribute library.
  6639. *
  6640. * @private
  6641. * @type {WeakMap<TypedArray, InterleavedBuffer>}
  6642. */
  6643. const _bufferLib = new WeakMap();
  6644. /**
  6645. * Internal method for retrieving or creating interleaved buffers.
  6646. *
  6647. * @private
  6648. * @param {TypedArray} value - The attribute data.
  6649. * @param {number} itemSize - The attribute item size.
  6650. * @returns {InterleavedBuffer} The interleaved buffer.
  6651. */
  6652. function _getBufferAttribute( value, itemSize ) {
  6653. let buffer = _bufferLib.get( value );
  6654. if ( buffer === undefined ) {
  6655. buffer = new InterleavedBuffer( value, itemSize );
  6656. _bufferLib.set( value, buffer );
  6657. }
  6658. return buffer;
  6659. }
  6660. /**
  6661. * In earlier `three.js` versions it was only possible to define attribute data
  6662. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6663. * on the node level.
  6664. * ```js
  6665. * const geometry = new THREE.PlaneGeometry();
  6666. * const positionAttribute = geometry.getAttribute( 'position' );
  6667. *
  6668. * const colors = [];
  6669. * for ( let i = 0; i < position.count; i ++ ) {
  6670. * colors.push( 1, 0, 0 );
  6671. * }
  6672. *
  6673. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6674. * ```
  6675. * This new approach is especially interesting when geometry data are generated via
  6676. * compute shaders. The below line converts a storage buffer into an attribute node.
  6677. * ```js
  6678. * material.positionNode = positionBuffer.toAttribute();
  6679. * ```
  6680. * @augments InputNode
  6681. */
  6682. class BufferAttributeNode extends InputNode {
  6683. static get type() {
  6684. return 'BufferAttributeNode';
  6685. }
  6686. /**
  6687. * Constructs a new buffer attribute node.
  6688. *
  6689. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6690. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6691. * @param {number} [bufferStride=0] - The buffer stride.
  6692. * @param {number} [bufferOffset=0] - The buffer offset.
  6693. */
  6694. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6695. super( value, bufferType );
  6696. /**
  6697. * This flag can be used for type testing.
  6698. *
  6699. * @type {boolean}
  6700. * @readonly
  6701. * @default true
  6702. */
  6703. this.isBufferNode = true;
  6704. /**
  6705. * The buffer type (e.g. `'vec3'`).
  6706. *
  6707. * @type {?string}
  6708. * @default null
  6709. */
  6710. this.bufferType = bufferType;
  6711. /**
  6712. * The buffer stride.
  6713. *
  6714. * @type {number}
  6715. * @default 0
  6716. */
  6717. this.bufferStride = bufferStride;
  6718. /**
  6719. * The buffer offset.
  6720. *
  6721. * @type {number}
  6722. * @default 0
  6723. */
  6724. this.bufferOffset = bufferOffset;
  6725. /**
  6726. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6727. * if you are planning to update the attribute data per frame.
  6728. *
  6729. * @type {number}
  6730. * @default StaticDrawUsage
  6731. */
  6732. this.usage = StaticDrawUsage;
  6733. /**
  6734. * Whether the attribute is instanced or not.
  6735. *
  6736. * @type {boolean}
  6737. * @default false
  6738. */
  6739. this.instanced = false;
  6740. /**
  6741. * A reference to the buffer attribute.
  6742. *
  6743. * @type {?BufferAttribute}
  6744. * @default null
  6745. */
  6746. this.attribute = null;
  6747. /**
  6748. * `BufferAttributeNode` sets this property to `true` by default.
  6749. *
  6750. * @type {boolean}
  6751. * @default true
  6752. */
  6753. this.global = true;
  6754. if ( value && value.isBufferAttribute === true && value.itemSize <= 4 ) {
  6755. this.attribute = value;
  6756. this.usage = value.usage;
  6757. this.instanced = value.isInstancedBufferAttribute;
  6758. }
  6759. }
  6760. /**
  6761. * This method is overwritten since the attribute data might be shared
  6762. * and thus the hash should be shared as well.
  6763. *
  6764. * @param {NodeBuilder} builder - The current node builder.
  6765. * @return {string} The hash.
  6766. */
  6767. getHash( builder ) {
  6768. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6769. let bufferData = builder.globalCache.getData( this.value );
  6770. if ( bufferData === undefined ) {
  6771. bufferData = {
  6772. node: this
  6773. };
  6774. builder.globalCache.setData( this.value, bufferData );
  6775. }
  6776. return bufferData.node.uuid;
  6777. }
  6778. return this.uuid;
  6779. }
  6780. /**
  6781. * This method is overwritten since the node type is inferred from
  6782. * the buffer attribute.
  6783. *
  6784. * @param {NodeBuilder} builder - The current node builder.
  6785. * @return {string} The node type.
  6786. */
  6787. getNodeType( builder ) {
  6788. if ( this.bufferType === null ) {
  6789. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6790. }
  6791. return this.bufferType;
  6792. }
  6793. /**
  6794. * Depending on which value was passed to the node, `setup()` behaves
  6795. * differently. If no instance of `BufferAttribute` was passed, the method
  6796. * creates an internal attribute and configures it respectively.
  6797. *
  6798. * @param {NodeBuilder} builder - The current node builder.
  6799. */
  6800. setup( builder ) {
  6801. if ( this.attribute !== null ) return;
  6802. //
  6803. const type = this.getNodeType( builder );
  6804. const itemSize = builder.getTypeLength( type );
  6805. const value = this.value;
  6806. const stride = this.bufferStride || itemSize;
  6807. const offset = this.bufferOffset;
  6808. let buffer;
  6809. if ( value.isInterleavedBuffer === true ) {
  6810. buffer = value;
  6811. } else if ( value.isBufferAttribute === true ) {
  6812. buffer = _getBufferAttribute( value.array, stride );
  6813. } else {
  6814. buffer = _getBufferAttribute( value, stride );
  6815. }
  6816. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6817. buffer.setUsage( this.usage );
  6818. this.attribute = bufferAttribute;
  6819. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6820. }
  6821. /**
  6822. * Generates the code snippet of the buffer attribute node.
  6823. *
  6824. * @param {NodeBuilder} builder - The current node builder.
  6825. * @return {string} The generated code snippet.
  6826. */
  6827. generate( builder ) {
  6828. const nodeType = this.getNodeType( builder );
  6829. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6830. const propertyName = builder.getPropertyName( nodeAttribute );
  6831. let output = null;
  6832. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6833. this.name = propertyName;
  6834. output = propertyName;
  6835. } else {
  6836. const nodeVarying = varying( this );
  6837. output = nodeVarying.build( builder, nodeType );
  6838. }
  6839. return output;
  6840. }
  6841. /**
  6842. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6843. *
  6844. * @param {NodeBuilder} builder - The current node builder.
  6845. * @return {string} The input type.
  6846. */
  6847. getInputType( /*builder*/ ) {
  6848. return 'bufferAttribute';
  6849. }
  6850. /**
  6851. * Sets the `usage` property to the given value.
  6852. *
  6853. * @param {number} value - The usage to set.
  6854. * @return {BufferAttributeNode} A reference to this node.
  6855. */
  6856. setUsage( value ) {
  6857. this.usage = value;
  6858. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6859. this.attribute.usage = value;
  6860. }
  6861. return this;
  6862. }
  6863. /**
  6864. * Sets the `instanced` property to the given value.
  6865. *
  6866. * @param {boolean} value - The value to set.
  6867. * @return {BufferAttributeNode} A reference to this node.
  6868. */
  6869. setInstanced( value ) {
  6870. this.instanced = value;
  6871. return this;
  6872. }
  6873. }
  6874. /**
  6875. * Internal method for creating buffer attribute nodes.
  6876. *
  6877. * @private
  6878. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6879. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6880. * @param {number} [stride=0] - The buffer stride.
  6881. * @param {number} [offset=0] - The buffer offset.
  6882. * @param {number} [usage=StaticDrawUsage] - The buffer usage.
  6883. * @param {boolean} [instanced=false] - Whether the buffer is instanced.
  6884. * @returns {BufferAttributeNode|Node} The buffer attribute node.
  6885. */
  6886. function createBufferAttribute( array, type = null, stride = 0, offset = 0, usage = StaticDrawUsage, instanced = false ) {
  6887. if ( type === 'mat3' || ( type === null && array.itemSize === 9 ) ) {
  6888. return mat3(
  6889. new BufferAttributeNode( array, 'vec3', 9, 0 ).setUsage( usage ).setInstanced( instanced ),
  6890. new BufferAttributeNode( array, 'vec3', 9, 3 ).setUsage( usage ).setInstanced( instanced ),
  6891. new BufferAttributeNode( array, 'vec3', 9, 6 ).setUsage( usage ).setInstanced( instanced )
  6892. );
  6893. } else if ( type === 'mat4' || ( type === null && array.itemSize === 16 ) ) {
  6894. return mat4(
  6895. new BufferAttributeNode( array, 'vec4', 16, 0 ).setUsage( usage ).setInstanced( instanced ),
  6896. new BufferAttributeNode( array, 'vec4', 16, 4 ).setUsage( usage ).setInstanced( instanced ),
  6897. new BufferAttributeNode( array, 'vec4', 16, 8 ).setUsage( usage ).setInstanced( instanced ),
  6898. new BufferAttributeNode( array, 'vec4', 16, 12 ).setUsage( usage ).setInstanced( instanced )
  6899. );
  6900. }
  6901. return new BufferAttributeNode( array, type, stride, offset );
  6902. }
  6903. /**
  6904. * TSL function for creating a buffer attribute node.
  6905. *
  6906. * @tsl
  6907. * @function
  6908. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6909. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6910. * @param {number} [stride=0] - The buffer stride.
  6911. * @param {number} [offset=0] - The buffer offset.
  6912. * @returns {BufferAttributeNode|Node}
  6913. */
  6914. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset );
  6915. /**
  6916. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6917. * Use this function if attribute data are updated per frame.
  6918. *
  6919. * @tsl
  6920. * @function
  6921. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6922. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6923. * @param {number} [stride=0] - The buffer stride.
  6924. * @param {number} [offset=0] - The buffer offset.
  6925. * @returns {BufferAttributeNode|Node}
  6926. */
  6927. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage );
  6928. /**
  6929. * TSL function for creating a buffer attribute node but with enabled instancing
  6930. *
  6931. * @tsl
  6932. * @function
  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. * @returns {BufferAttributeNode|Node}
  6938. */
  6939. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, StaticDrawUsage, true );
  6940. /**
  6941. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6942. *
  6943. * @tsl
  6944. * @function
  6945. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6946. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6947. * @param {number} [stride=0] - The buffer stride.
  6948. * @param {number} [offset=0] - The buffer offset.
  6949. * @returns {BufferAttributeNode|Node}
  6950. */
  6951. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage, true );
  6952. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6953. /**
  6954. * TODO
  6955. *
  6956. * @augments Node
  6957. */
  6958. class ComputeNode extends Node {
  6959. static get type() {
  6960. return 'ComputeNode';
  6961. }
  6962. /**
  6963. * Constructs a new compute node.
  6964. *
  6965. * @param {Node} computeNode - TODO
  6966. * @param {Array<number>} workgroupSize - TODO.
  6967. */
  6968. constructor( computeNode, workgroupSize ) {
  6969. super( 'void' );
  6970. /**
  6971. * This flag can be used for type testing.
  6972. *
  6973. * @type {boolean}
  6974. * @readonly
  6975. * @default true
  6976. */
  6977. this.isComputeNode = true;
  6978. /**
  6979. * TODO
  6980. *
  6981. * @type {Node}
  6982. */
  6983. this.computeNode = computeNode;
  6984. /**
  6985. * TODO
  6986. *
  6987. * @type {Array<number>}
  6988. * @default [ 64 ]
  6989. */
  6990. this.workgroupSize = workgroupSize;
  6991. /**
  6992. * TODO
  6993. *
  6994. * @type {number|Array<number>}
  6995. */
  6996. this.count = null;
  6997. /**
  6998. * TODO
  6999. *
  7000. * @type {number}
  7001. */
  7002. this.version = 1;
  7003. /**
  7004. * The name or label of the uniform.
  7005. *
  7006. * @type {string}
  7007. * @default ''
  7008. */
  7009. this.name = '';
  7010. /**
  7011. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  7012. * is executed once per object by default.
  7013. *
  7014. * @type {string}
  7015. * @default 'object'
  7016. */
  7017. this.updateBeforeType = NodeUpdateType.OBJECT;
  7018. /**
  7019. * TODO
  7020. *
  7021. * @type {?Function}
  7022. */
  7023. this.onInitFunction = null;
  7024. }
  7025. /**
  7026. * TODO
  7027. *
  7028. * @param {number|Array<number>} count - Array with [ x, y, z ] values for dispatch or a single number for the count
  7029. * @return {ComputeNode}
  7030. */
  7031. setCount( count ) {
  7032. this.count = count;
  7033. return this;
  7034. }
  7035. /**
  7036. * TODO
  7037. *
  7038. * @return {number|Array<number>}
  7039. */
  7040. getCount() {
  7041. return this.count;
  7042. }
  7043. /**
  7044. * Executes the `dispose` event for this node.
  7045. */
  7046. dispose() {
  7047. this.dispatchEvent( { type: 'dispose' } );
  7048. }
  7049. /**
  7050. * Sets the {@link ComputeNode#name} property.
  7051. *
  7052. * @param {string} name - The name of the uniform.
  7053. * @return {ComputeNode} A reference to this node.
  7054. */
  7055. setName( name ) {
  7056. this.name = name;
  7057. return this;
  7058. }
  7059. /**
  7060. * Sets the {@link ComputeNode#name} property.
  7061. *
  7062. * @deprecated
  7063. * @param {string} name - The name of the uniform.
  7064. * @return {ComputeNode} A reference to this node.
  7065. */
  7066. label( name ) {
  7067. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  7068. return this.setName( name );
  7069. }
  7070. /**
  7071. * TODO
  7072. *
  7073. * @param {Function} callback - TODO.
  7074. * @return {ComputeNode} A reference to this node.
  7075. */
  7076. onInit( callback ) {
  7077. this.onInitFunction = callback;
  7078. return this;
  7079. }
  7080. /**
  7081. * The method execute the compute for this node.
  7082. *
  7083. * @param {NodeFrame} frame - A reference to the current node frame.
  7084. */
  7085. updateBefore( { renderer } ) {
  7086. renderer.compute( this );
  7087. }
  7088. setup( builder ) {
  7089. const result = this.computeNode.build( builder );
  7090. if ( result ) {
  7091. const properties = builder.getNodeProperties( this );
  7092. properties.outputComputeNode = result.outputNode;
  7093. result.outputNode = null;
  7094. }
  7095. return result;
  7096. }
  7097. generate( builder, output ) {
  7098. const { shaderStage } = builder;
  7099. if ( shaderStage === 'compute' ) {
  7100. const snippet = this.computeNode.build( builder, 'void' );
  7101. if ( snippet !== '' ) {
  7102. builder.addLineFlowCode( snippet, this );
  7103. }
  7104. } else {
  7105. const properties = builder.getNodeProperties( this );
  7106. const outputComputeNode = properties.outputComputeNode;
  7107. if ( outputComputeNode ) {
  7108. return outputComputeNode.build( builder, output );
  7109. }
  7110. }
  7111. }
  7112. }
  7113. /**
  7114. * TSL function for creating a compute kernel node.
  7115. *
  7116. * @tsl
  7117. * @function
  7118. * @param {Node} node - TODO
  7119. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7120. * @returns {AtomicFunctionNode}
  7121. */
  7122. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  7123. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  7124. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  7125. }
  7126. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  7127. const val = workgroupSize[ i ];
  7128. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  7129. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  7130. }
  7131. }
  7132. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  7133. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  7134. //
  7135. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  7136. };
  7137. /**
  7138. * TSL function for creating a compute node.
  7139. *
  7140. * @tsl
  7141. * @function
  7142. * @param {Node} node - TODO
  7143. * @param {number|Array<number>} count - TODO.
  7144. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7145. * @returns {AtomicFunctionNode}
  7146. */
  7147. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  7148. addMethodChaining( 'compute', compute );
  7149. addMethodChaining( 'computeKernel', computeKernel );
  7150. /**
  7151. * This node can be used as a cache management component for another node.
  7152. * Caching is in general used by default in {@link NodeBuilder} but this node
  7153. * allows the usage of a shared parent cache during the build process.
  7154. *
  7155. * @augments Node
  7156. */
  7157. class IsolateNode extends Node {
  7158. static get type() {
  7159. return 'IsolateNode';
  7160. }
  7161. /**
  7162. * Constructs a new cache node.
  7163. *
  7164. * @param {Node} node - The node that should be cached.
  7165. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7166. */
  7167. constructor( node, parent = true ) {
  7168. super();
  7169. /**
  7170. * The node that should be cached.
  7171. *
  7172. * @type {Node}
  7173. */
  7174. this.node = node;
  7175. /**
  7176. * Whether this node refers to a shared parent cache or not.
  7177. *
  7178. * @type {boolean}
  7179. * @default true
  7180. */
  7181. this.parent = parent;
  7182. /**
  7183. * This flag can be used for type testing.
  7184. *
  7185. * @type {boolean}
  7186. * @readonly
  7187. * @default true
  7188. */
  7189. this.isIsolateNode = true;
  7190. }
  7191. getNodeType( builder ) {
  7192. const previousCache = builder.getCache();
  7193. const cache = builder.getCacheFromNode( this, this.parent );
  7194. builder.setCache( cache );
  7195. const nodeType = this.node.getNodeType( builder );
  7196. builder.setCache( previousCache );
  7197. return nodeType;
  7198. }
  7199. build( builder, ...params ) {
  7200. const previousCache = builder.getCache();
  7201. const cache = builder.getCacheFromNode( this, this.parent );
  7202. builder.setCache( cache );
  7203. const data = this.node.build( builder, ...params );
  7204. builder.setCache( previousCache );
  7205. return data;
  7206. }
  7207. setParent( parent ) {
  7208. this.parent = parent;
  7209. return this;
  7210. }
  7211. getParent() {
  7212. return this.parent;
  7213. }
  7214. }
  7215. /**
  7216. * TSL function for creating a cache node.
  7217. *
  7218. * @tsl
  7219. * @function
  7220. * @param {Node} node - The node that should be cached.
  7221. * @returns {IsolateNode}
  7222. */
  7223. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7224. /**
  7225. * TSL function for creating a cache node.
  7226. *
  7227. * @tsl
  7228. * @function
  7229. * @deprecated
  7230. * @param {Node} node - The node that should be cached.
  7231. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7232. * @returns {IsolateNode}
  7233. */
  7234. function cache( node, parent = true ) {
  7235. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7236. return isolate( node ).setParent( parent );
  7237. }
  7238. addMethodChaining( 'cache', cache );
  7239. addMethodChaining( 'isolate', isolate );
  7240. /**
  7241. * The class generates the code of a given node but returns another node in the output.
  7242. * This can be used to call a method or node that does not return a value, i.e.
  7243. * type `void` on an input where returning a value is required. Example:
  7244. *
  7245. * ```js
  7246. * material.colorNode = myColor.bypass( runVoidFn() )
  7247. *```
  7248. *
  7249. * @augments Node
  7250. */
  7251. class BypassNode extends Node {
  7252. static get type() {
  7253. return 'BypassNode';
  7254. }
  7255. /**
  7256. * Constructs a new bypass node.
  7257. *
  7258. * @param {Node} outputNode - The output node.
  7259. * @param {Node} callNode - The call node.
  7260. */
  7261. constructor( outputNode, callNode ) {
  7262. super();
  7263. /**
  7264. * This flag can be used for type testing.
  7265. *
  7266. * @type {boolean}
  7267. * @readonly
  7268. * @default true
  7269. */
  7270. this.isBypassNode = true;
  7271. /**
  7272. * The output node.
  7273. *
  7274. * @type {Node}
  7275. */
  7276. this.outputNode = outputNode;
  7277. /**
  7278. * The call node.
  7279. *
  7280. * @type {Node}
  7281. */
  7282. this.callNode = callNode;
  7283. }
  7284. getNodeType( builder ) {
  7285. return this.outputNode.getNodeType( builder );
  7286. }
  7287. generate( builder ) {
  7288. const snippet = this.callNode.build( builder, 'void' );
  7289. if ( snippet !== '' ) {
  7290. builder.addLineFlowCode( snippet, this );
  7291. }
  7292. return this.outputNode.build( builder );
  7293. }
  7294. }
  7295. /**
  7296. * TSL function for creating a bypass node.
  7297. *
  7298. * @tsl
  7299. * @function
  7300. * @param {Node} outputNode - The output node.
  7301. * @param {Node} callNode - The call node.
  7302. * @returns {BypassNode}
  7303. */
  7304. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7305. addMethodChaining( 'bypass', bypass );
  7306. /**
  7307. * This node allows to remap a node value from one range into another. E.g a value of
  7308. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7309. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7310. *
  7311. * @augments Node
  7312. */
  7313. class RemapNode extends Node {
  7314. static get type() {
  7315. return 'RemapNode';
  7316. }
  7317. /**
  7318. * Constructs a new remap node.
  7319. *
  7320. * @param {Node} node - The node that should be remapped.
  7321. * @param {Node} inLowNode - The source or current lower bound of the range.
  7322. * @param {Node} inHighNode - The source or current upper bound of the range.
  7323. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7324. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7325. */
  7326. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7327. super();
  7328. /**
  7329. * The node that should be remapped.
  7330. *
  7331. * @type {Node}
  7332. */
  7333. this.node = node;
  7334. /**
  7335. * The source or current lower bound of the range.
  7336. *
  7337. * @type {Node}
  7338. */
  7339. this.inLowNode = inLowNode;
  7340. /**
  7341. * The source or current upper bound of the range.
  7342. *
  7343. * @type {Node}
  7344. */
  7345. this.inHighNode = inHighNode;
  7346. /**
  7347. * The target lower bound of the range.
  7348. *
  7349. * @type {Node}
  7350. * @default float(0)
  7351. */
  7352. this.outLowNode = outLowNode;
  7353. /**
  7354. * The target upper bound of the range.
  7355. *
  7356. * @type {Node}
  7357. * @default float(1)
  7358. */
  7359. this.outHighNode = outHighNode;
  7360. /**
  7361. * Whether the node value should be clamped before
  7362. * remapping it to the target range.
  7363. *
  7364. * @type {boolean}
  7365. * @default true
  7366. */
  7367. this.doClamp = true;
  7368. }
  7369. setup() {
  7370. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7371. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7372. if ( doClamp === true ) t = t.clamp();
  7373. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7374. }
  7375. }
  7376. /**
  7377. * TSL function for creating a remap node.
  7378. *
  7379. * @tsl
  7380. * @function
  7381. * @param {Node} node - The node that should be remapped.
  7382. * @param {Node} inLowNode - The source or current lower bound of the range.
  7383. * @param {Node} inHighNode - The source or current upper bound of the range.
  7384. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7385. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7386. * @returns {RemapNode}
  7387. */
  7388. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7389. /**
  7390. * TSL function for creating a remap node, but with enabled clamping.
  7391. *
  7392. * @tsl
  7393. * @function
  7394. * @param {Node} node - The node that should be remapped.
  7395. * @param {Node} inLowNode - The source or current lower bound of the range.
  7396. * @param {Node} inHighNode - The source or current upper bound of the range.
  7397. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7398. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7399. * @returns {RemapNode}
  7400. */
  7401. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7402. addMethodChaining( 'remap', remap );
  7403. addMethodChaining( 'remapClamp', remapClamp );
  7404. /**
  7405. * This class can be used to implement basic expressions in shader code.
  7406. * Basic examples for that are `return`, `continue` or `discard` statements.
  7407. *
  7408. * @augments Node
  7409. */
  7410. class ExpressionNode extends Node {
  7411. static get type() {
  7412. return 'ExpressionNode';
  7413. }
  7414. /**
  7415. * Constructs a new expression node.
  7416. *
  7417. * @param {string} [snippet=''] - The native code snippet.
  7418. * @param {string} [nodeType='void'] - The node type.
  7419. */
  7420. constructor( snippet = '', nodeType = 'void' ) {
  7421. super( nodeType );
  7422. /**
  7423. * The native code snippet.
  7424. *
  7425. * @type {string}
  7426. * @default ''
  7427. */
  7428. this.snippet = snippet;
  7429. }
  7430. generate( builder, output ) {
  7431. const type = this.getNodeType( builder );
  7432. const snippet = this.snippet;
  7433. if ( type === 'void' ) {
  7434. builder.addLineFlowCode( snippet, this );
  7435. } else {
  7436. return builder.format( snippet, type, output );
  7437. }
  7438. }
  7439. }
  7440. /**
  7441. * TSL function for creating an expression node.
  7442. *
  7443. * @tsl
  7444. * @function
  7445. * @param {string} [snippet] - The native code snippet.
  7446. * @param {?string} [nodeType='void'] - The node type.
  7447. * @returns {ExpressionNode}
  7448. */
  7449. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7450. /**
  7451. * Represents a `discard` shader operation in TSL.
  7452. *
  7453. * @tsl
  7454. * @function
  7455. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7456. * @return {Node} The `discard` expression.
  7457. */
  7458. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7459. /**
  7460. * Represents a `return` shader operation in TSL.
  7461. *
  7462. * @tsl
  7463. * @function
  7464. * @return {ExpressionNode} The `return` expression.
  7465. */
  7466. const Return = () => expression( 'return' ).toStack();
  7467. addMethodChaining( 'discard', Discard );
  7468. /**
  7469. * Normally, tone mapping and color conversion happens automatically
  7470. * before outputting pixel too the default (screen) framebuffer. In certain
  7471. * post processing setups this happens to late because certain effects
  7472. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7473. * to apply tone mapping and color space conversion at an arbitrary point
  7474. * in the effect chain.
  7475. *
  7476. * When applying tone mapping and color space conversion manually with this node,
  7477. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7478. *
  7479. * ```js
  7480. * const postProcessing = new PostProcessing( renderer );
  7481. * postProcessing.outputColorTransform = false;
  7482. *
  7483. * const scenePass = pass( scene, camera );
  7484. * const outputPass = renderOutput( scenePass );
  7485. *
  7486. * postProcessing.outputNode = outputPass;
  7487. * ```
  7488. *
  7489. * @augments TempNode
  7490. */
  7491. class RenderOutputNode extends TempNode {
  7492. static get type() {
  7493. return 'RenderOutputNode';
  7494. }
  7495. /**
  7496. * Constructs a new render output node.
  7497. *
  7498. * @param {Node} colorNode - The color node to process.
  7499. * @param {?number} toneMapping - The tone mapping type.
  7500. * @param {?string} outputColorSpace - The output color space.
  7501. */
  7502. constructor( colorNode, toneMapping, outputColorSpace ) {
  7503. super( 'vec4' );
  7504. /**
  7505. * The color node to process.
  7506. *
  7507. * @type {Node}
  7508. */
  7509. this.colorNode = colorNode;
  7510. /**
  7511. * The tone mapping type.
  7512. *
  7513. * @private
  7514. * @type {?number}
  7515. */
  7516. this._toneMapping = toneMapping;
  7517. /**
  7518. * The output color space.
  7519. *
  7520. * @type {?string}
  7521. */
  7522. this.outputColorSpace = outputColorSpace;
  7523. /**
  7524. * This flag can be used for type testing.
  7525. *
  7526. * @type {boolean}
  7527. * @readonly
  7528. * @default true
  7529. */
  7530. this.isRenderOutputNode = true;
  7531. }
  7532. /**
  7533. * Sets the tone mapping type.
  7534. *
  7535. * @param {number} value - The tone mapping type.
  7536. * @return {ToneMappingNode} A reference to this node.
  7537. */
  7538. setToneMapping( value ) {
  7539. this._toneMapping = value;
  7540. return this;
  7541. }
  7542. /**
  7543. * Gets the tone mapping type.
  7544. *
  7545. * @returns {number} The tone mapping type.
  7546. */
  7547. getToneMapping() {
  7548. return this._toneMapping;
  7549. }
  7550. setup( { context } ) {
  7551. let outputNode = this.colorNode || context.color;
  7552. // tone mapping
  7553. const toneMapping = ( this._toneMapping !== null ? this._toneMapping : context.toneMapping ) || NoToneMapping;
  7554. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7555. if ( toneMapping !== NoToneMapping ) {
  7556. outputNode = outputNode.toneMapping( toneMapping );
  7557. }
  7558. // working to output color space
  7559. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7560. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7561. }
  7562. return outputNode;
  7563. }
  7564. }
  7565. /**
  7566. * TSL function for creating a posterize node.
  7567. *
  7568. * @tsl
  7569. * @function
  7570. * @param {Node} color - The color node to process.
  7571. * @param {?number} [toneMapping=null] - The tone mapping type.
  7572. * @param {?string} [outputColorSpace=null] - The output color space.
  7573. * @returns {RenderOutputNode}
  7574. */
  7575. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7576. addMethodChaining( 'renderOutput', renderOutput );
  7577. class DebugNode extends TempNode {
  7578. static get type() {
  7579. return 'DebugNode';
  7580. }
  7581. constructor( node, callback = null ) {
  7582. super();
  7583. this.node = node;
  7584. this.callback = callback;
  7585. }
  7586. getNodeType( builder ) {
  7587. return this.node.getNodeType( builder );
  7588. }
  7589. setup( builder ) {
  7590. return this.node.build( builder );
  7591. }
  7592. analyze( builder ) {
  7593. return this.node.build( builder );
  7594. }
  7595. generate( builder ) {
  7596. const callback = this.callback;
  7597. const snippet = this.node.build( builder );
  7598. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7599. const border = '-'.repeat( title.length );
  7600. let code = '';
  7601. code += '// #' + title + '#\n';
  7602. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7603. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7604. code += '// #' + border + '#\n';
  7605. if ( callback !== null ) {
  7606. callback( builder, code );
  7607. } else {
  7608. log$1( code );
  7609. }
  7610. return snippet;
  7611. }
  7612. }
  7613. /**
  7614. * TSL function for creating a debug node.
  7615. *
  7616. * @tsl
  7617. * @function
  7618. * @param {Node} node - The node to debug.
  7619. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7620. * @returns {DebugNode}
  7621. */
  7622. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7623. addMethodChaining( 'debug', debug );
  7624. /**
  7625. * InspectorBase is the base class for all inspectors.
  7626. *
  7627. * @class InspectorBase
  7628. */
  7629. class InspectorBase {
  7630. /**
  7631. * Creates a new InspectorBase.
  7632. */
  7633. constructor() {
  7634. /**
  7635. * The renderer associated with this inspector.
  7636. *
  7637. * @type {WebGLRenderer}
  7638. * @private
  7639. */
  7640. this._renderer = null;
  7641. /**
  7642. * The current frame being processed.
  7643. *
  7644. * @type {Object}
  7645. */
  7646. this.currentFrame = null;
  7647. }
  7648. /**
  7649. * Returns the node frame for the current renderer.
  7650. *
  7651. * @return {Object} The node frame.
  7652. */
  7653. get nodeFrame() {
  7654. return this._renderer._nodes.nodeFrame;
  7655. }
  7656. /**
  7657. * Sets the renderer for this inspector.
  7658. *
  7659. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  7660. * @return {InspectorBase} This inspector instance.
  7661. */
  7662. setRenderer( renderer ) {
  7663. this._renderer = renderer;
  7664. return this;
  7665. }
  7666. /**
  7667. * Returns the renderer associated with this inspector.
  7668. *
  7669. * @return {WebGLRenderer} The associated renderer.
  7670. */
  7671. getRenderer() {
  7672. return this._renderer;
  7673. }
  7674. /**
  7675. * Initializes the inspector.
  7676. */
  7677. init() { }
  7678. /**
  7679. * Called when a frame begins.
  7680. */
  7681. begin() { }
  7682. /**
  7683. * Called when a frame ends.
  7684. */
  7685. finish() { }
  7686. /**
  7687. * Inspects a node.
  7688. *
  7689. * @param {Node} node - The node to inspect.
  7690. */
  7691. inspect( /*node*/ ) { }
  7692. /**
  7693. * When a compute operation is performed.
  7694. *
  7695. * @param {ComputeNode} computeNode - The compute node being executed.
  7696. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  7697. */
  7698. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  7699. /**
  7700. * Called when a compute operation begins.
  7701. *
  7702. * @param {string} uid - A unique identifier for the render context.
  7703. * @param {ComputeNode} computeNode - The compute node being executed.
  7704. */
  7705. beginCompute( /*uid, computeNode*/ ) { }
  7706. /**
  7707. * Called when a compute operation ends.
  7708. *
  7709. * @param {string} uid - A unique identifier for the render context.
  7710. * @param {ComputeNode} computeNode - The compute node being executed.
  7711. */
  7712. finishCompute( /*uid*/ ) { }
  7713. /**
  7714. * Called when a render operation begins.
  7715. *
  7716. * @param {string} uid - A unique identifier for the render context.
  7717. * @param {Scene} scene - The scene being rendered.
  7718. * @param {Camera} camera - The camera being used for rendering.
  7719. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  7720. */
  7721. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  7722. /**
  7723. * Called when an animation loop ends.
  7724. *
  7725. * @param {string} uid - A unique identifier for the render context.
  7726. */
  7727. finishRender( /*uid*/ ) { }
  7728. /**
  7729. * Called when a texture copy operation is performed.
  7730. *
  7731. * @param {Texture} srcTexture - The source texture.
  7732. * @param {Texture} dstTexture - The destination texture.
  7733. */
  7734. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  7735. /**
  7736. * Called when a framebuffer copy operation is performed.
  7737. *
  7738. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  7739. */
  7740. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  7741. }
  7742. /**
  7743. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  7744. * It can be used to debug or analyze node outputs in the rendering pipeline.
  7745. *
  7746. * @augments Node
  7747. */
  7748. class InspectorNode extends Node {
  7749. /**
  7750. * Returns the type of the node.
  7751. *
  7752. * @returns {string}
  7753. */
  7754. static get type() {
  7755. return 'InspectorNode';
  7756. }
  7757. /**
  7758. * Creates an InspectorNode.
  7759. *
  7760. * @param {Node} node - The node to inspect.
  7761. * @param {string} [name=''] - Optional name for the inspector node.
  7762. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7763. */
  7764. constructor( node, name = '', callback = null ) {
  7765. super();
  7766. this.node = node;
  7767. this.name = name;
  7768. this.callback = callback;
  7769. this.updateType = NodeUpdateType.FRAME;
  7770. this.isInspectorNode = true;
  7771. }
  7772. /**
  7773. * Returns the name of the inspector node.
  7774. *
  7775. * @returns {string}
  7776. */
  7777. getName() {
  7778. return this.name || this.node.name;
  7779. }
  7780. /**
  7781. * Updates the inspector node, allowing inspection of the wrapped node.
  7782. *
  7783. * @param {NodeFrame} frame - A reference to the current node frame.
  7784. */
  7785. update( frame ) {
  7786. frame.renderer.inspector.inspect( this );
  7787. }
  7788. /**
  7789. * Returns the type of the wrapped node.
  7790. *
  7791. * @param {NodeBuilder} builder - The node builder.
  7792. * @returns {string}
  7793. */
  7794. getNodeType( builder ) {
  7795. return this.node.getNodeType( builder );
  7796. }
  7797. /**
  7798. * Sets up the inspector node.
  7799. *
  7800. * @param {NodeBuilder} builder - The node builder.
  7801. * @returns {Node} The setup node.
  7802. */
  7803. setup( builder ) {
  7804. let node = this.node;
  7805. if ( builder.context.inspector === true && this.callback !== null ) {
  7806. node = this.callback( node );
  7807. }
  7808. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  7809. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  7810. }
  7811. return node;
  7812. }
  7813. }
  7814. /**
  7815. * Creates an inspector node to wrap around a given node for inspection purposes.
  7816. *
  7817. * @tsl
  7818. * @param {Node} node - The node to inspect.
  7819. * @param {string} [name=''] - Optional name for the inspector node.
  7820. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7821. * @returns {Node} The inspector node.
  7822. */
  7823. function inspector( node, name = '', callback = null ) {
  7824. node = nodeObject( node );
  7825. return node.before( new InspectorNode( node, name, callback ) );
  7826. }
  7827. addMethodChaining( 'toInspector', inspector );
  7828. function addNodeElement( name/*, nodeElement*/ ) {
  7829. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7830. }
  7831. /**
  7832. * Base class for representing shader attributes as nodes.
  7833. *
  7834. * @augments Node
  7835. */
  7836. class AttributeNode extends Node {
  7837. static get type() {
  7838. return 'AttributeNode';
  7839. }
  7840. /**
  7841. * Constructs a new attribute node.
  7842. *
  7843. * @param {string} attributeName - The name of the attribute.
  7844. * @param {?string} nodeType - The node type.
  7845. */
  7846. constructor( attributeName, nodeType = null ) {
  7847. super( nodeType );
  7848. /**
  7849. * `AttributeNode` sets this property to `true` by default.
  7850. *
  7851. * @type {boolean}
  7852. * @default true
  7853. */
  7854. this.global = true;
  7855. this._attributeName = attributeName;
  7856. }
  7857. getHash( builder ) {
  7858. return this.getAttributeName( builder );
  7859. }
  7860. getNodeType( builder ) {
  7861. let nodeType = this.nodeType;
  7862. if ( nodeType === null ) {
  7863. const attributeName = this.getAttributeName( builder );
  7864. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7865. const attribute = builder.geometry.getAttribute( attributeName );
  7866. nodeType = builder.getTypeFromAttribute( attribute );
  7867. } else {
  7868. nodeType = 'float';
  7869. }
  7870. }
  7871. return nodeType;
  7872. }
  7873. /**
  7874. * Sets the attribute name to the given value. The method can be
  7875. * overwritten in derived classes if the final name must be computed
  7876. * analytically.
  7877. *
  7878. * @param {string} attributeName - The name of the attribute.
  7879. * @return {AttributeNode} A reference to this node.
  7880. */
  7881. setAttributeName( attributeName ) {
  7882. this._attributeName = attributeName;
  7883. return this;
  7884. }
  7885. /**
  7886. * Returns the attribute name of this node. The method can be
  7887. * overwritten in derived classes if the final name must be computed
  7888. * analytically.
  7889. *
  7890. * @param {NodeBuilder} builder - The current node builder.
  7891. * @return {string} The attribute name.
  7892. */
  7893. getAttributeName( /*builder*/ ) {
  7894. return this._attributeName;
  7895. }
  7896. generate( builder ) {
  7897. const attributeName = this.getAttributeName( builder );
  7898. const nodeType = this.getNodeType( builder );
  7899. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7900. if ( geometryAttribute === true ) {
  7901. const attribute = builder.geometry.getAttribute( attributeName );
  7902. const attributeType = builder.getTypeFromAttribute( attribute );
  7903. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7904. if ( builder.shaderStage === 'vertex' ) {
  7905. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7906. } else {
  7907. const nodeVarying = varying( this );
  7908. return nodeVarying.build( builder, nodeType );
  7909. }
  7910. } else {
  7911. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7912. return builder.generateConst( nodeType );
  7913. }
  7914. }
  7915. serialize( data ) {
  7916. super.serialize( data );
  7917. data.global = this.global;
  7918. data._attributeName = this._attributeName;
  7919. }
  7920. deserialize( data ) {
  7921. super.deserialize( data );
  7922. this.global = data.global;
  7923. this._attributeName = data._attributeName;
  7924. }
  7925. }
  7926. /**
  7927. * TSL function for creating an attribute node.
  7928. *
  7929. * @tsl
  7930. * @function
  7931. * @param {string} name - The name of the attribute.
  7932. * @param {?string} [nodeType=null] - The node type.
  7933. * @returns {AttributeNode}
  7934. */
  7935. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7936. /**
  7937. * TSL function for creating an uv attribute node with the given index.
  7938. *
  7939. * @tsl
  7940. * @function
  7941. * @param {number} [index=0] - The uv index.
  7942. * @return {AttributeNode<vec2>} The uv attribute node.
  7943. */
  7944. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7945. /**
  7946. * A node that represents the dimensions of a texture. The texture size is
  7947. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7948. * or `textureSize()`.
  7949. *
  7950. * @augments Node
  7951. */
  7952. class TextureSizeNode extends Node {
  7953. static get type() {
  7954. return 'TextureSizeNode';
  7955. }
  7956. /**
  7957. * Constructs a new texture size node.
  7958. *
  7959. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7960. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7961. */
  7962. constructor( textureNode, levelNode = null ) {
  7963. super( 'uvec2' );
  7964. /**
  7965. * This flag can be used for type testing.
  7966. *
  7967. * @type {boolean}
  7968. * @readonly
  7969. * @default true
  7970. */
  7971. this.isTextureSizeNode = true;
  7972. /**
  7973. * A texture node which size should be retrieved.
  7974. *
  7975. * @type {TextureNode}
  7976. */
  7977. this.textureNode = textureNode;
  7978. /**
  7979. * A level node which defines the requested mip.
  7980. *
  7981. * @type {Node<int>}
  7982. * @default null
  7983. */
  7984. this.levelNode = levelNode;
  7985. }
  7986. generate( builder, output ) {
  7987. const textureProperty = this.textureNode.build( builder, 'property' );
  7988. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7989. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7990. }
  7991. }
  7992. /**
  7993. * TSL function for creating a texture size node.
  7994. *
  7995. * @tsl
  7996. * @function
  7997. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7998. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7999. * @returns {TextureSizeNode}
  8000. */
  8001. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  8002. /**
  8003. * A special type of uniform node that computes the
  8004. * maximum mipmap level for a given texture node.
  8005. *
  8006. * ```js
  8007. * const level = maxMipLevel( textureNode );
  8008. * ```
  8009. *
  8010. * @augments UniformNode
  8011. */
  8012. class MaxMipLevelNode extends UniformNode {
  8013. static get type() {
  8014. return 'MaxMipLevelNode';
  8015. }
  8016. /**
  8017. * Constructs a new max mip level node.
  8018. *
  8019. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8020. */
  8021. constructor( textureNode ) {
  8022. super( 0 );
  8023. /**
  8024. * The texture node to compute the max mip level for.
  8025. *
  8026. * @private
  8027. * @type {TextureNode}
  8028. */
  8029. this._textureNode = textureNode;
  8030. /**
  8031. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  8032. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  8033. *
  8034. * @type {string}
  8035. * @default 'frame'
  8036. */
  8037. this.updateType = NodeUpdateType.FRAME;
  8038. }
  8039. /**
  8040. * The texture node to compute the max mip level for.
  8041. *
  8042. * @readonly
  8043. * @type {TextureNode}
  8044. */
  8045. get textureNode() {
  8046. return this._textureNode;
  8047. }
  8048. /**
  8049. * The texture.
  8050. *
  8051. * @readonly
  8052. * @type {Texture}
  8053. */
  8054. get texture() {
  8055. return this._textureNode.value;
  8056. }
  8057. update() {
  8058. const texture = this.texture;
  8059. const images = texture.images;
  8060. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  8061. if ( image && image.width !== undefined ) {
  8062. const { width, height } = image;
  8063. this.value = Math.log2( Math.max( width, height ) );
  8064. }
  8065. }
  8066. }
  8067. /**
  8068. * TSL function for creating a max mip level node.
  8069. *
  8070. * @tsl
  8071. * @function
  8072. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8073. * @returns {MaxMipLevelNode}
  8074. */
  8075. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  8076. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  8077. /**
  8078. * This type of uniform node represents a 2D texture.
  8079. *
  8080. * @augments UniformNode
  8081. */
  8082. class TextureNode extends UniformNode {
  8083. static get type() {
  8084. return 'TextureNode';
  8085. }
  8086. /**
  8087. * Constructs a new texture node.
  8088. *
  8089. * @param {Texture} [value=EmptyTexture] - The texture.
  8090. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8091. * @param {?Node<int>} [levelNode=null] - The level node.
  8092. * @param {?Node<float>} [biasNode=null] - The bias node.
  8093. */
  8094. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  8095. super( value );
  8096. /**
  8097. * This flag can be used for type testing.
  8098. *
  8099. * @type {boolean}
  8100. * @readonly
  8101. * @default true
  8102. */
  8103. this.isTextureNode = true;
  8104. /**
  8105. * Represents the texture coordinates.
  8106. *
  8107. * @type {?Node<vec2|vec3>}
  8108. * @default null
  8109. */
  8110. this.uvNode = uvNode;
  8111. /**
  8112. * Represents the mip level that should be selected.
  8113. *
  8114. * @type {?Node<int>}
  8115. * @default null
  8116. */
  8117. this.levelNode = levelNode;
  8118. /**
  8119. * Represents the bias to be applied during level-of-detail computation.
  8120. *
  8121. * @type {?Node<float>}
  8122. * @default null
  8123. */
  8124. this.biasNode = biasNode;
  8125. /**
  8126. * Represents a reference value a texture sample is compared to.
  8127. *
  8128. * @type {?Node<float>}
  8129. * @default null
  8130. */
  8131. this.compareNode = null;
  8132. /**
  8133. * When using texture arrays, the depth node defines the layer to select.
  8134. *
  8135. * @type {?Node<int>}
  8136. * @default null
  8137. */
  8138. this.depthNode = null;
  8139. /**
  8140. * When defined, a texture is sampled using explicit gradients.
  8141. *
  8142. * @type {?Array<Node<vec2>>}
  8143. * @default null
  8144. */
  8145. this.gradNode = null;
  8146. /**
  8147. * Represents the optional texel offset applied to the unnormalized texture
  8148. * coordinate before sampling the texture.
  8149. *
  8150. * @type {?Node<ivec2|ivec3>}
  8151. * @default null
  8152. */
  8153. this.offsetNode = null;
  8154. /**
  8155. * Whether texture values should be sampled or fetched.
  8156. *
  8157. * @type {boolean}
  8158. * @default true
  8159. */
  8160. this.sampler = true;
  8161. /**
  8162. * Whether the uv transformation matrix should be
  8163. * automatically updated or not. Use `setUpdateMatrix()`
  8164. * if you want to change the value of the property.
  8165. *
  8166. * @type {boolean}
  8167. * @default false
  8168. */
  8169. this.updateMatrix = false;
  8170. /**
  8171. * By default the `update()` method is not executed. Depending on
  8172. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8173. * is executed per object.
  8174. *
  8175. * @type {string}
  8176. * @default 'none'
  8177. */
  8178. this.updateType = NodeUpdateType.NONE;
  8179. /**
  8180. * The reference node.
  8181. *
  8182. * @type {?Node}
  8183. * @default null
  8184. */
  8185. this.referenceNode = null;
  8186. /**
  8187. * The texture value is stored in a private property.
  8188. *
  8189. * @private
  8190. * @type {Texture}
  8191. */
  8192. this._value = value;
  8193. /**
  8194. * The uniform node that represents the uv transformation matrix.
  8195. *
  8196. * @private
  8197. * @type {?UniformNode<mat3>}
  8198. * @default null
  8199. */
  8200. this._matrixUniform = null;
  8201. /**
  8202. * The uniform node that represents the y-flip. Only required for WebGL.
  8203. *
  8204. * @private
  8205. * @type {?UniformNode<bool>}
  8206. * @default null
  8207. */
  8208. this._flipYUniform = null;
  8209. this.setUpdateMatrix( uvNode === null );
  8210. }
  8211. set value( value ) {
  8212. if ( this.referenceNode ) {
  8213. this.referenceNode.value = value;
  8214. } else {
  8215. this._value = value;
  8216. }
  8217. }
  8218. /**
  8219. * The texture value.
  8220. *
  8221. * @type {Texture}
  8222. */
  8223. get value() {
  8224. return this.referenceNode ? this.referenceNode.value : this._value;
  8225. }
  8226. /**
  8227. * Overwritten since the uniform hash is defined by the texture's UUID.
  8228. *
  8229. * @param {NodeBuilder} builder - The current node builder.
  8230. * @return {string} The uniform hash.
  8231. */
  8232. getUniformHash( /*builder*/ ) {
  8233. return this.value.uuid;
  8234. }
  8235. /**
  8236. * Overwritten since the node type is inferred from the texture type.
  8237. *
  8238. * @param {NodeBuilder} builder - The current node builder.
  8239. * @return {string} The node type.
  8240. */
  8241. getNodeType( /*builder*/ ) {
  8242. if ( this.value.isDepthTexture === true ) return 'float';
  8243. if ( this.value.type === UnsignedIntType ) {
  8244. return 'uvec4';
  8245. } else if ( this.value.type === IntType ) {
  8246. return 'ivec4';
  8247. }
  8248. return 'vec4';
  8249. }
  8250. /**
  8251. * Overwrites the default implementation to return a fixed value `'texture'`.
  8252. *
  8253. * @param {NodeBuilder} builder - The current node builder.
  8254. * @return {string} The input type.
  8255. */
  8256. getInputType( /*builder*/ ) {
  8257. return 'texture';
  8258. }
  8259. /**
  8260. * Returns a default uvs based on the current texture's channel.
  8261. *
  8262. * @return {AttributeNode<vec2>} The default uvs.
  8263. */
  8264. getDefaultUV() {
  8265. return uv$1( this.value.channel );
  8266. }
  8267. /**
  8268. * Overwritten to always return the texture reference of the node.
  8269. *
  8270. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8271. * @return {Texture} The texture reference.
  8272. */
  8273. updateReference( /*state*/ ) {
  8274. return this.value;
  8275. }
  8276. /**
  8277. * Transforms the given uv node with the texture transformation matrix.
  8278. *
  8279. * @param {Node} uvNode - The uv node to transform.
  8280. * @return {Node} The transformed uv node.
  8281. */
  8282. getTransformedUV( uvNode ) {
  8283. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8284. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8285. }
  8286. /**
  8287. * Defines whether the uv transformation matrix should automatically be updated or not.
  8288. *
  8289. * @param {boolean} value - The update toggle.
  8290. * @return {TextureNode} A reference to this node.
  8291. */
  8292. setUpdateMatrix( value ) {
  8293. this.updateMatrix = value;
  8294. return this;
  8295. }
  8296. /**
  8297. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8298. * to modify the uv node for correct sampling.
  8299. *
  8300. * @param {NodeBuilder} builder - The current node builder.
  8301. * @param {Node} uvNode - The uv node to setup.
  8302. * @return {Node} The updated uv node.
  8303. */
  8304. setupUV( builder, uvNode ) {
  8305. if ( builder.isFlipY() ) {
  8306. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8307. uvNode = uvNode.toVar();
  8308. if ( this.sampler ) {
  8309. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8310. } else {
  8311. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8312. }
  8313. }
  8314. return uvNode;
  8315. }
  8316. /**
  8317. * Setups texture node by preparing the internal nodes for code generation.
  8318. *
  8319. * @param {NodeBuilder} builder - The current node builder.
  8320. */
  8321. setup( builder ) {
  8322. const properties = builder.getNodeProperties( this );
  8323. properties.referenceNode = this.referenceNode;
  8324. //
  8325. const texture = this.value;
  8326. if ( ! texture || texture.isTexture !== true ) {
  8327. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  8328. }
  8329. //
  8330. const uvNode = Fn( () => {
  8331. let uvNode = this.uvNode;
  8332. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8333. uvNode = builder.context.getUV( this, builder );
  8334. }
  8335. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8336. if ( this.updateMatrix === true ) {
  8337. uvNode = this.getTransformedUV( uvNode );
  8338. }
  8339. uvNode = this.setupUV( builder, uvNode );
  8340. //
  8341. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8342. //
  8343. return uvNode;
  8344. } )();
  8345. //
  8346. let levelNode = this.levelNode;
  8347. if ( levelNode === null && builder.context.getTextureLevel ) {
  8348. levelNode = builder.context.getTextureLevel( this );
  8349. }
  8350. //
  8351. properties.uvNode = uvNode;
  8352. properties.levelNode = levelNode;
  8353. properties.biasNode = this.biasNode;
  8354. properties.compareNode = this.compareNode;
  8355. properties.gradNode = this.gradNode;
  8356. properties.depthNode = this.depthNode;
  8357. properties.offsetNode = this.offsetNode;
  8358. }
  8359. /**
  8360. * Generates the uv code snippet.
  8361. *
  8362. * @param {NodeBuilder} builder - The current node builder.
  8363. * @param {Node} uvNode - The uv node to generate code for.
  8364. * @return {string} The generated code snippet.
  8365. */
  8366. generateUV( builder, uvNode ) {
  8367. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8368. }
  8369. /**
  8370. * Generates the offset code snippet.
  8371. *
  8372. * @param {NodeBuilder} builder - The current node builder.
  8373. * @param {Node} offsetNode - The offset node to generate code for.
  8374. * @return {string} The generated code snippet.
  8375. */
  8376. generateOffset( builder, offsetNode ) {
  8377. return offsetNode.build( builder, 'ivec2' );
  8378. }
  8379. /**
  8380. * Generates the snippet for the texture sampling.
  8381. *
  8382. * @param {NodeBuilder} builder - The current node builder.
  8383. * @param {string} textureProperty - The texture property.
  8384. * @param {string} uvSnippet - The uv snippet.
  8385. * @param {?string} levelSnippet - The level snippet.
  8386. * @param {?string} biasSnippet - The bias snippet.
  8387. * @param {?string} depthSnippet - The depth snippet.
  8388. * @param {?string} compareSnippet - The compare snippet.
  8389. * @param {?Array<string>} gradSnippet - The grad snippet.
  8390. * @param {?string} offsetSnippet - The offset snippet.
  8391. * @return {string} The generated code snippet.
  8392. */
  8393. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  8394. const texture = this.value;
  8395. let snippet;
  8396. if ( biasSnippet ) {
  8397. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8398. } else if ( gradSnippet ) {
  8399. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8400. } else if ( compareSnippet ) {
  8401. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8402. } else if ( this.sampler === false ) {
  8403. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8404. } else if ( levelSnippet ) {
  8405. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8406. } else {
  8407. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8408. }
  8409. return snippet;
  8410. }
  8411. /**
  8412. * Generates the code snippet of the texture node.
  8413. *
  8414. * @param {NodeBuilder} builder - The current node builder.
  8415. * @param {string} output - The current output.
  8416. * @return {string} The generated code snippet.
  8417. */
  8418. generate( builder, output ) {
  8419. const texture = this.value;
  8420. const properties = builder.getNodeProperties( this );
  8421. const textureProperty = super.generate( builder, 'property' );
  8422. if ( /^sampler/.test( output ) ) {
  8423. return textureProperty + '_sampler';
  8424. } else if ( builder.isReference( output ) ) {
  8425. return textureProperty;
  8426. } else {
  8427. const nodeData = builder.getDataFromNode( this );
  8428. let propertyName = nodeData.propertyName;
  8429. if ( propertyName === undefined ) {
  8430. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode, offsetNode } = properties;
  8431. const uvSnippet = this.generateUV( builder, uvNode );
  8432. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8433. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8434. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8435. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8436. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8437. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8438. const nodeVar = builder.getVarFromNode( this );
  8439. propertyName = builder.getPropertyName( nodeVar );
  8440. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  8441. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  8442. nodeData.snippet = snippet;
  8443. nodeData.propertyName = propertyName;
  8444. }
  8445. let snippet = propertyName;
  8446. const nodeType = this.getNodeType( builder );
  8447. if ( builder.needsToWorkingColorSpace( texture ) ) {
  8448. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  8449. }
  8450. return builder.format( snippet, nodeType, output );
  8451. }
  8452. }
  8453. /**
  8454. * Sets the sampler value.
  8455. *
  8456. * @param {boolean} value - The sampler value to set.
  8457. * @return {TextureNode} A reference to this texture node.
  8458. */
  8459. setSampler( value ) {
  8460. this.sampler = value;
  8461. return this;
  8462. }
  8463. /**
  8464. * Returns the sampler value.
  8465. *
  8466. * @return {boolean} The sampler value.
  8467. */
  8468. getSampler() {
  8469. return this.sampler;
  8470. }
  8471. // @TODO: Move to TSL
  8472. /**
  8473. * @function
  8474. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  8475. *
  8476. * @param {Node} uvNode - The uv node.
  8477. * @return {TextureNode} A texture node representing the texture sample.
  8478. */
  8479. uv( uvNode ) { // @deprecated, r172
  8480. warn( 'TextureNode: .uv() has been renamed. Use .sample() instead.' );
  8481. return this.sample( uvNode );
  8482. }
  8483. /**
  8484. * Samples the texture with the given uv node.
  8485. *
  8486. * @param {Node} uvNode - The uv node.
  8487. * @return {TextureNode} A texture node representing the texture sample.
  8488. */
  8489. sample( uvNode ) {
  8490. const textureNode = this.clone();
  8491. textureNode.uvNode = nodeObject( uvNode );
  8492. textureNode.referenceNode = this.getBase();
  8493. return nodeObject( textureNode );
  8494. }
  8495. /**
  8496. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8497. *
  8498. * @param {Node<uvec2>} uvNode - The uv node.
  8499. * @returns {TextureNode} A texture node representing the texture load.
  8500. */
  8501. load( uvNode ) {
  8502. return this.sample( uvNode ).setSampler( false );
  8503. }
  8504. /**
  8505. * Samples a blurred version of the texture by defining an internal bias.
  8506. *
  8507. * @param {Node<float>} amountNode - How blurred the texture should be.
  8508. * @return {TextureNode} A texture node representing the texture sample.
  8509. */
  8510. blur( amountNode ) {
  8511. const textureNode = this.clone();
  8512. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8513. textureNode.referenceNode = this.getBase();
  8514. const map = textureNode.value;
  8515. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8516. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8517. textureNode.biasNode = null;
  8518. }
  8519. return nodeObject( textureNode );
  8520. }
  8521. /**
  8522. * Samples a specific mip of the texture.
  8523. *
  8524. * @param {Node<int>} levelNode - The mip level to sample.
  8525. * @return {TextureNode} A texture node representing the texture sample.
  8526. */
  8527. level( levelNode ) {
  8528. const textureNode = this.clone();
  8529. textureNode.levelNode = nodeObject( levelNode );
  8530. textureNode.referenceNode = this.getBase();
  8531. return nodeObject( textureNode );
  8532. }
  8533. /**
  8534. * Returns the texture size of the requested level.
  8535. *
  8536. * @param {Node<int>} levelNode - The level to compute the size for.
  8537. * @return {TextureSizeNode} The texture size.
  8538. */
  8539. size( levelNode ) {
  8540. return textureSize( this, levelNode );
  8541. }
  8542. /**
  8543. * Samples the texture with the given bias.
  8544. *
  8545. * @param {Node<float>} biasNode - The bias node.
  8546. * @return {TextureNode} A texture node representing the texture sample.
  8547. */
  8548. bias( biasNode ) {
  8549. const textureNode = this.clone();
  8550. textureNode.biasNode = nodeObject( biasNode );
  8551. textureNode.referenceNode = this.getBase();
  8552. return nodeObject( textureNode );
  8553. }
  8554. /**
  8555. * Returns the base texture of this node.
  8556. * @return {TextureNode} The base texture node.
  8557. */
  8558. getBase() {
  8559. return this.referenceNode ? this.referenceNode.getBase() : this;
  8560. }
  8561. /**
  8562. * Samples the texture by executing a compare operation.
  8563. *
  8564. * @param {Node<float>} compareNode - The node that defines the compare value.
  8565. * @return {TextureNode} A texture node representing the texture sample.
  8566. */
  8567. compare( compareNode ) {
  8568. const textureNode = this.clone();
  8569. textureNode.compareNode = nodeObject( compareNode );
  8570. textureNode.referenceNode = this.getBase();
  8571. return nodeObject( textureNode );
  8572. }
  8573. /**
  8574. * Samples the texture using an explicit gradient.
  8575. *
  8576. * @param {Node<vec2>} gradNodeX - The gradX node.
  8577. * @param {Node<vec2>} gradNodeY - The gradY node.
  8578. * @return {TextureNode} A texture node representing the texture sample.
  8579. */
  8580. grad( gradNodeX, gradNodeY ) {
  8581. const textureNode = this.clone();
  8582. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8583. textureNode.referenceNode = this.getBase();
  8584. return nodeObject( textureNode );
  8585. }
  8586. /**
  8587. * Samples the texture by defining a depth node.
  8588. *
  8589. * @param {Node<int>} depthNode - The depth node.
  8590. * @return {TextureNode} A texture node representing the texture sample.
  8591. */
  8592. depth( depthNode ) {
  8593. const textureNode = this.clone();
  8594. textureNode.depthNode = nodeObject( depthNode );
  8595. textureNode.referenceNode = this.getBase();
  8596. return nodeObject( textureNode );
  8597. }
  8598. /**
  8599. * Samples the texture by defining an offset node.
  8600. *
  8601. * @param {Node<ivec2>} offsetNode - The offset node.
  8602. * @return {TextureNode} A texture node representing the texture sample.
  8603. */
  8604. offset( offsetNode ) {
  8605. const textureNode = this.clone();
  8606. textureNode.offsetNode = nodeObject( offsetNode );
  8607. textureNode.referenceNode = this.getBase();
  8608. return nodeObject( textureNode );
  8609. }
  8610. // --
  8611. serialize( data ) {
  8612. super.serialize( data );
  8613. data.value = this.value.toJSON( data.meta ).uuid;
  8614. data.sampler = this.sampler;
  8615. data.updateMatrix = this.updateMatrix;
  8616. data.updateType = this.updateType;
  8617. }
  8618. deserialize( data ) {
  8619. super.deserialize( data );
  8620. this.value = data.meta.textures[ data.value ];
  8621. this.sampler = data.sampler;
  8622. this.updateMatrix = data.updateMatrix;
  8623. this.updateType = data.updateType;
  8624. }
  8625. /**
  8626. * The update is used to implement the update of the uv transformation matrix.
  8627. */
  8628. update() {
  8629. const texture = this.value;
  8630. const matrixUniform = this._matrixUniform;
  8631. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8632. if ( texture.matrixAutoUpdate === true ) {
  8633. texture.updateMatrix();
  8634. }
  8635. //
  8636. const flipYUniform = this._flipYUniform;
  8637. if ( flipYUniform !== null ) {
  8638. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  8639. }
  8640. }
  8641. /**
  8642. * Clones the texture node.
  8643. *
  8644. * @return {TextureNode} The cloned texture node.
  8645. */
  8646. clone() {
  8647. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8648. newNode.sampler = this.sampler;
  8649. newNode.depthNode = this.depthNode;
  8650. newNode.compareNode = this.compareNode;
  8651. newNode.gradNode = this.gradNode;
  8652. newNode.offsetNode = this.offsetNode;
  8653. return newNode;
  8654. }
  8655. }
  8656. /**
  8657. * TSL function for creating a texture node.
  8658. *
  8659. * @tsl
  8660. * @function
  8661. * @param {?Texture} value - The texture.
  8662. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8663. * @param {?Node<int>} [levelNode=null] - The level node.
  8664. * @param {?Node<float>} [biasNode=null] - The bias node.
  8665. * @returns {TextureNode}
  8666. */
  8667. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8668. /**
  8669. * TSL function for creating a texture node or sample a texture node already existing.
  8670. *
  8671. * @tsl
  8672. * @function
  8673. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8674. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8675. * @param {?Node<int>} [levelNode=null] - The level node.
  8676. * @param {?Node<float>} [biasNode=null] - The bias node.
  8677. * @returns {TextureNode}
  8678. */
  8679. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8680. let textureNode;
  8681. if ( value && value.isTextureNode === true ) {
  8682. textureNode = nodeObject( value.clone() );
  8683. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8684. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8685. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8686. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8687. } else {
  8688. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8689. }
  8690. return textureNode;
  8691. };
  8692. /**
  8693. * TSL function for creating a uniform texture node.
  8694. *
  8695. * @tsl
  8696. * @function
  8697. * @param {?Texture} value - The texture.
  8698. * @returns {TextureNode}
  8699. */
  8700. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8701. /**
  8702. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8703. *
  8704. * @tsl
  8705. * @function
  8706. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8707. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8708. * @param {?Node<int>} [levelNode=null] - The level node.
  8709. * @param {?Node<float>} [biasNode=null] - The bias node.
  8710. * @returns {TextureNode}
  8711. */
  8712. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8713. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8714. /**
  8715. * Converts a texture or texture node to a sampler.
  8716. *
  8717. * @tsl
  8718. * @function
  8719. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8720. * @returns {Node}
  8721. */
  8722. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8723. /**
  8724. * Converts a texture or texture node to a sampler comparison.
  8725. *
  8726. * @tsl
  8727. * @function
  8728. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8729. * @returns {Node}
  8730. */
  8731. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8732. /**
  8733. * A special type of uniform node which represents array-like data
  8734. * as uniform buffers. The access usually happens via `element()`
  8735. * which returns an instance of {@link ArrayElementNode}. For example:
  8736. *
  8737. * ```js
  8738. * const bufferNode = buffer( array, 'mat4', count );
  8739. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8740. * ```
  8741. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8742. * since it handles more input types and automatically cares about buffer paddings.
  8743. *
  8744. * @augments UniformNode
  8745. */
  8746. class BufferNode extends UniformNode {
  8747. static get type() {
  8748. return 'BufferNode';
  8749. }
  8750. /**
  8751. * Constructs a new buffer node.
  8752. *
  8753. * @param {Array<number>} value - Array-like buffer data.
  8754. * @param {string} bufferType - The data type of the buffer.
  8755. * @param {number} [bufferCount=0] - The count of buffer elements.
  8756. */
  8757. constructor( value, bufferType, bufferCount = 0 ) {
  8758. super( value, bufferType );
  8759. /**
  8760. * This flag can be used for type testing.
  8761. *
  8762. * @type {boolean}
  8763. * @readonly
  8764. * @default true
  8765. */
  8766. this.isBufferNode = true;
  8767. /**
  8768. * The data type of the buffer.
  8769. *
  8770. * @type {string}
  8771. */
  8772. this.bufferType = bufferType;
  8773. /**
  8774. * The uniform node that holds the value of the reference node.
  8775. *
  8776. * @type {number}
  8777. * @default 0
  8778. */
  8779. this.bufferCount = bufferCount;
  8780. /**
  8781. * An array of update ranges.
  8782. *
  8783. * @type {Array<{start: number, count: number}>}
  8784. */
  8785. this.updateRanges = [];
  8786. }
  8787. /**
  8788. * Adds a range of data in the data array to be updated on the GPU.
  8789. *
  8790. * @param {number} start - Position at which to start update.
  8791. * @param {number} count - The number of components to update.
  8792. */
  8793. addUpdateRange( start, count ) {
  8794. this.updateRanges.push( { start, count } );
  8795. }
  8796. /**
  8797. * Clears the update ranges.
  8798. */
  8799. clearUpdateRanges() {
  8800. this.updateRanges.length = 0;
  8801. }
  8802. /**
  8803. * The data type of the buffer elements.
  8804. *
  8805. * @param {NodeBuilder} builder - The current node builder.
  8806. * @return {string} The element type.
  8807. */
  8808. getElementType( builder ) {
  8809. return this.getNodeType( builder );
  8810. }
  8811. /**
  8812. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8813. *
  8814. * @param {NodeBuilder} builder - The current node builder.
  8815. * @return {string} The input type.
  8816. */
  8817. getInputType( /*builder*/ ) {
  8818. return 'buffer';
  8819. }
  8820. }
  8821. /**
  8822. * TSL function for creating a buffer node.
  8823. *
  8824. * @tsl
  8825. * @function
  8826. * @param {Array<number>} value - Array-like buffer data.
  8827. * @param {string} type - The data type of a buffer element.
  8828. * @param {number} count - The count of buffer elements.
  8829. * @returns {BufferNode}
  8830. */
  8831. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8832. /**
  8833. * Represents the element access on uniform array nodes.
  8834. *
  8835. * @augments ArrayElementNode
  8836. */
  8837. class UniformArrayElementNode extends ArrayElementNode {
  8838. static get type() {
  8839. return 'UniformArrayElementNode';
  8840. }
  8841. /**
  8842. * Constructs a new buffer node.
  8843. *
  8844. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8845. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8846. */
  8847. constructor( uniformArrayNode, indexNode ) {
  8848. super( uniformArrayNode, indexNode );
  8849. /**
  8850. * This flag can be used for type testing.
  8851. *
  8852. * @type {boolean}
  8853. * @readonly
  8854. * @default true
  8855. */
  8856. this.isArrayBufferElementNode = true;
  8857. }
  8858. generate( builder ) {
  8859. const snippet = super.generate( builder );
  8860. const type = this.getNodeType();
  8861. const paddedType = this.node.getPaddedType();
  8862. return builder.format( snippet, paddedType, type );
  8863. }
  8864. }
  8865. /**
  8866. * Similar to {@link BufferNode} this module represents array-like data as
  8867. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8868. * data types in the array (e.g `three.js` primitives) and automatically
  8869. * manage buffer padding. It should be the first choice when working with
  8870. * uniforms buffers.
  8871. * ```js
  8872. * const tintColors = uniformArray( [
  8873. * new Color( 1, 0, 0 ),
  8874. * new Color( 0, 1, 0 ),
  8875. * new Color( 0, 0, 1 )
  8876. * ], 'color' );
  8877. *
  8878. * const redColor = tintColors.element( 0 );
  8879. *
  8880. * @augments BufferNode
  8881. */
  8882. class UniformArrayNode extends BufferNode {
  8883. static get type() {
  8884. return 'UniformArrayNode';
  8885. }
  8886. /**
  8887. * Constructs a new uniform array node.
  8888. *
  8889. * @param {Array<any>} value - Array holding the buffer data.
  8890. * @param {?string} [elementType=null] - The data type of a buffer element.
  8891. */
  8892. constructor( value, elementType = null ) {
  8893. super( null );
  8894. /**
  8895. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8896. * hold number primitives as well as three.js objects like vectors, matrices
  8897. * or colors.
  8898. *
  8899. * @type {Array<any>}
  8900. */
  8901. this.array = value;
  8902. /**
  8903. * The data type of an array element.
  8904. *
  8905. * @type {string}
  8906. */
  8907. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8908. /**
  8909. * The padded type. Uniform buffers must conform to a certain buffer layout
  8910. * so a separate type is computed to ensure correct buffer size.
  8911. *
  8912. * @type {string}
  8913. */
  8914. this.paddedType = this.getPaddedType();
  8915. /**
  8916. * Overwritten since uniform array nodes are updated per render.
  8917. *
  8918. * @type {string}
  8919. * @default 'render'
  8920. */
  8921. this.updateType = NodeUpdateType.RENDER;
  8922. /**
  8923. * This flag can be used for type testing.
  8924. *
  8925. * @type {boolean}
  8926. * @readonly
  8927. * @default true
  8928. */
  8929. this.isArrayBufferNode = true;
  8930. }
  8931. /**
  8932. * This method is overwritten since the node type is inferred from the
  8933. * {@link UniformArrayNode#paddedType}.
  8934. *
  8935. * @param {NodeBuilder} builder - The current node builder.
  8936. * @return {string} The node type.
  8937. */
  8938. getNodeType( /*builder*/ ) {
  8939. return this.paddedType;
  8940. }
  8941. /**
  8942. * The data type of the array elements.
  8943. *
  8944. * @param {NodeBuilder} builder - The current node builder.
  8945. * @return {string} The element type.
  8946. */
  8947. getElementType() {
  8948. return this.elementType;
  8949. }
  8950. /**
  8951. * Returns the padded type based on the element type.
  8952. *
  8953. * @return {string} The padded type.
  8954. */
  8955. getPaddedType() {
  8956. const elementType = this.elementType;
  8957. let paddedType = 'vec4';
  8958. if ( elementType === 'mat2' ) {
  8959. paddedType = 'mat2';
  8960. } else if ( /mat/.test( elementType ) === true ) {
  8961. paddedType = 'mat4';
  8962. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8963. paddedType = 'ivec4';
  8964. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8965. paddedType = 'uvec4';
  8966. }
  8967. return paddedType;
  8968. }
  8969. /**
  8970. * The update makes sure to correctly transfer the data from the (complex) objects
  8971. * in the array to the internal, correctly padded value buffer.
  8972. *
  8973. * @param {NodeFrame} frame - A reference to the current node frame.
  8974. */
  8975. update( /*frame*/ ) {
  8976. const { array, value } = this;
  8977. const elementType = this.elementType;
  8978. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8979. for ( let i = 0; i < array.length; i ++ ) {
  8980. const index = i * 4;
  8981. value[ index ] = array[ i ];
  8982. }
  8983. } else if ( elementType === 'color' ) {
  8984. for ( let i = 0; i < array.length; i ++ ) {
  8985. const index = i * 4;
  8986. const vector = array[ i ];
  8987. value[ index ] = vector.r;
  8988. value[ index + 1 ] = vector.g;
  8989. value[ index + 2 ] = vector.b || 0;
  8990. //value[ index + 3 ] = vector.a || 0;
  8991. }
  8992. } else if ( elementType === 'mat2' ) {
  8993. for ( let i = 0; i < array.length; i ++ ) {
  8994. const index = i * 4;
  8995. const matrix = array[ i ];
  8996. value[ index ] = matrix.elements[ 0 ];
  8997. value[ index + 1 ] = matrix.elements[ 1 ];
  8998. value[ index + 2 ] = matrix.elements[ 2 ];
  8999. value[ index + 3 ] = matrix.elements[ 3 ];
  9000. }
  9001. } else if ( elementType === 'mat3' ) {
  9002. for ( let i = 0; i < array.length; i ++ ) {
  9003. const index = i * 16;
  9004. const matrix = array[ i ];
  9005. value[ index ] = matrix.elements[ 0 ];
  9006. value[ index + 1 ] = matrix.elements[ 1 ];
  9007. value[ index + 2 ] = matrix.elements[ 2 ];
  9008. value[ index + 4 ] = matrix.elements[ 3 ];
  9009. value[ index + 5 ] = matrix.elements[ 4 ];
  9010. value[ index + 6 ] = matrix.elements[ 5 ];
  9011. value[ index + 8 ] = matrix.elements[ 6 ];
  9012. value[ index + 9 ] = matrix.elements[ 7 ];
  9013. value[ index + 10 ] = matrix.elements[ 8 ];
  9014. value[ index + 15 ] = 1;
  9015. }
  9016. } else if ( elementType === 'mat4' ) {
  9017. for ( let i = 0; i < array.length; i ++ ) {
  9018. const index = i * 16;
  9019. const matrix = array[ i ];
  9020. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  9021. value[ index + i ] = matrix.elements[ i ];
  9022. }
  9023. }
  9024. } else {
  9025. for ( let i = 0; i < array.length; i ++ ) {
  9026. const index = i * 4;
  9027. const vector = array[ i ];
  9028. value[ index ] = vector.x;
  9029. value[ index + 1 ] = vector.y;
  9030. value[ index + 2 ] = vector.z || 0;
  9031. value[ index + 3 ] = vector.w || 0;
  9032. }
  9033. }
  9034. }
  9035. /**
  9036. * Implement the value buffer creation based on the array data.
  9037. *
  9038. * @param {NodeBuilder} builder - A reference to the current node builder.
  9039. * @return {null}
  9040. */
  9041. setup( builder ) {
  9042. const length = this.array.length;
  9043. const elementType = this.elementType;
  9044. let arrayType = Float32Array;
  9045. const paddedType = this.paddedType;
  9046. const paddedElementLength = builder.getTypeLength( paddedType );
  9047. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  9048. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  9049. this.value = new arrayType( length * paddedElementLength );
  9050. this.bufferCount = length;
  9051. this.bufferType = paddedType;
  9052. return super.setup( builder );
  9053. }
  9054. /**
  9055. * Overwrites the default `element()` method to provide element access
  9056. * based on {@link UniformArrayNode}.
  9057. *
  9058. * @param {IndexNode} indexNode - The index node.
  9059. * @return {UniformArrayElementNode}
  9060. */
  9061. element( indexNode ) {
  9062. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  9063. }
  9064. }
  9065. /**
  9066. * TSL function for creating an uniform array node.
  9067. *
  9068. * @tsl
  9069. * @function
  9070. * @param {Array<any>} values - Array-like data.
  9071. * @param {?string} [nodeType] - The data type of the array elements.
  9072. * @returns {UniformArrayNode}
  9073. */
  9074. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  9075. /**
  9076. * The node allows to set values for built-in shader variables. That is
  9077. * required for features like hardware-accelerated vertex clipping.
  9078. *
  9079. * @augments Node
  9080. */
  9081. class BuiltinNode extends Node {
  9082. /**
  9083. * Constructs a new builtin node.
  9084. *
  9085. * @param {string} name - The name of the built-in shader variable.
  9086. */
  9087. constructor( name ) {
  9088. super( 'float' );
  9089. /**
  9090. * The name of the built-in shader variable.
  9091. *
  9092. * @type {string}
  9093. */
  9094. this.name = name;
  9095. /**
  9096. * This flag can be used for type testing.
  9097. *
  9098. * @type {boolean}
  9099. * @readonly
  9100. * @default true
  9101. */
  9102. this.isBuiltinNode = true;
  9103. }
  9104. /**
  9105. * Generates the code snippet of the builtin node.
  9106. *
  9107. * @param {NodeBuilder} builder - The current node builder.
  9108. * @return {string} The generated code snippet.
  9109. */
  9110. generate( /* builder */ ) {
  9111. return this.name;
  9112. }
  9113. }
  9114. /**
  9115. * TSL function for creating a builtin node.
  9116. *
  9117. * @tsl
  9118. * @function
  9119. * @param {string} name - The name of the built-in shader variable.
  9120. * @returns {BuiltinNode}
  9121. */
  9122. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  9123. let _screenSizeVec, _viewportVec;
  9124. /**
  9125. * This node provides a collection of screen related metrics.
  9126. * Depending on {@link ScreenNode#scope}, the nodes can represent
  9127. * resolution or viewport data as well as fragment or uv coordinates.
  9128. *
  9129. * @augments Node
  9130. */
  9131. class ScreenNode extends Node {
  9132. static get type() {
  9133. return 'ScreenNode';
  9134. }
  9135. /**
  9136. * Constructs a new screen node.
  9137. *
  9138. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  9139. */
  9140. constructor( scope ) {
  9141. super();
  9142. /**
  9143. * The node represents different metric depending on which scope is selected.
  9144. *
  9145. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  9146. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  9147. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  9148. * - `ScreenNode.UV`: Normalized coordinates.
  9149. * - `ScreenNode.DPR`: Device pixel ratio.
  9150. *
  9151. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  9152. */
  9153. this.scope = scope;
  9154. /**
  9155. * This output node.
  9156. *
  9157. * @private
  9158. * @type {?Node}
  9159. * @default null
  9160. */
  9161. this._output = null;
  9162. /**
  9163. * This flag can be used for type testing.
  9164. *
  9165. * @type {boolean}
  9166. * @readonly
  9167. * @default true
  9168. */
  9169. this.isViewportNode = true;
  9170. }
  9171. /**
  9172. * This method is overwritten since the node type depends on the selected scope.
  9173. *
  9174. * @return {('float'|'vec2'|'vec4')} The node type.
  9175. */
  9176. getNodeType() {
  9177. if ( this.scope === ScreenNode.DPR ) return 'float';
  9178. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  9179. else return 'vec2';
  9180. }
  9181. /**
  9182. * This method is overwritten since the node's update type depends on the selected scope.
  9183. *
  9184. * @return {NodeUpdateType} The update type.
  9185. */
  9186. getUpdateType() {
  9187. let updateType = NodeUpdateType.NONE;
  9188. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9189. updateType = NodeUpdateType.RENDER;
  9190. }
  9191. this.updateType = updateType;
  9192. return updateType;
  9193. }
  9194. /**
  9195. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9196. * from the current renderer.
  9197. *
  9198. * @param {NodeFrame} frame - A reference to the current node frame.
  9199. */
  9200. update( { renderer } ) {
  9201. const renderTarget = renderer.getRenderTarget();
  9202. if ( this.scope === ScreenNode.VIEWPORT ) {
  9203. if ( renderTarget !== null ) {
  9204. _viewportVec.copy( renderTarget.viewport );
  9205. } else {
  9206. renderer.getViewport( _viewportVec );
  9207. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9208. }
  9209. } else if ( this.scope === ScreenNode.DPR ) {
  9210. this._output.value = renderer.getPixelRatio();
  9211. } else {
  9212. if ( renderTarget !== null ) {
  9213. _screenSizeVec.width = renderTarget.width;
  9214. _screenSizeVec.height = renderTarget.height;
  9215. } else {
  9216. renderer.getDrawingBufferSize( _screenSizeVec );
  9217. }
  9218. }
  9219. }
  9220. setup( /*builder*/ ) {
  9221. const scope = this.scope;
  9222. let output = null;
  9223. if ( scope === ScreenNode.SIZE ) {
  9224. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9225. } else if ( scope === ScreenNode.VIEWPORT ) {
  9226. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9227. } else if ( scope === ScreenNode.DPR ) {
  9228. output = uniform( 1 );
  9229. } else {
  9230. output = vec2( screenCoordinate.div( screenSize ) );
  9231. }
  9232. this._output = output;
  9233. return output;
  9234. }
  9235. generate( builder ) {
  9236. if ( this.scope === ScreenNode.COORDINATE ) {
  9237. let coord = builder.getFragCoord();
  9238. if ( builder.isFlipY() ) {
  9239. // follow webgpu standards
  9240. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9241. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9242. }
  9243. return coord;
  9244. }
  9245. return super.generate( builder );
  9246. }
  9247. }
  9248. ScreenNode.COORDINATE = 'coordinate';
  9249. ScreenNode.VIEWPORT = 'viewport';
  9250. ScreenNode.SIZE = 'size';
  9251. ScreenNode.UV = 'uv';
  9252. ScreenNode.DPR = 'dpr';
  9253. // Screen
  9254. /**
  9255. * TSL object that represents the current DPR.
  9256. *
  9257. * @tsl
  9258. * @type {ScreenNode<float>}
  9259. */
  9260. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9261. /**
  9262. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9263. *
  9264. * @tsl
  9265. * @type {ScreenNode<vec2>}
  9266. */
  9267. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9268. /**
  9269. * TSL object that represents the screen resolution in physical pixel units.
  9270. *
  9271. * @tsl
  9272. * @type {ScreenNode<vec2>}
  9273. */
  9274. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9275. /**
  9276. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9277. *
  9278. * @tsl
  9279. * @type {ScreenNode<vec2>}
  9280. */
  9281. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9282. // Viewport
  9283. /**
  9284. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9285. *
  9286. * @tsl
  9287. * @type {ScreenNode<vec4>}
  9288. */
  9289. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9290. /**
  9291. * TSL object that represents the viewport resolution in physical pixel units.
  9292. *
  9293. * @tsl
  9294. * @type {ScreenNode<vec2>}
  9295. */
  9296. const viewportSize = viewport.zw;
  9297. /**
  9298. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9299. *
  9300. * @tsl
  9301. * @type {ScreenNode<vec2>}
  9302. */
  9303. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9304. /**
  9305. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9306. *
  9307. * @tsl
  9308. * @type {ScreenNode<vec2>}
  9309. */
  9310. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9311. // Deprecated
  9312. /**
  9313. * @deprecated since r169. Use {@link screenSize} instead.
  9314. */
  9315. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  9316. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  9317. return screenSize;
  9318. }, 'vec2' ).once() )();
  9319. /**
  9320. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  9321. *
  9322. * @tsl
  9323. * @type {UniformNode<uint>}
  9324. */
  9325. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  9326. /**
  9327. * TSL object that represents the `near` value of the camera used for the current render.
  9328. *
  9329. * @tsl
  9330. * @type {UniformNode<float>}
  9331. */
  9332. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  9333. /**
  9334. * TSL object that represents the `far` value of the camera used for the current render.
  9335. *
  9336. * @tsl
  9337. * @type {UniformNode<float>}
  9338. */
  9339. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  9340. /**
  9341. * TSL object that represents the projection matrix of the camera used for the current render.
  9342. *
  9343. * @tsl
  9344. * @type {UniformNode<mat4>}
  9345. */
  9346. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9347. let cameraProjectionMatrix;
  9348. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9349. const matrices = [];
  9350. for ( const subCamera of camera.cameras ) {
  9351. matrices.push( subCamera.projectionMatrix );
  9352. }
  9353. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9354. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9355. } else {
  9356. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9357. }
  9358. return cameraProjectionMatrix;
  9359. } ).once() )();
  9360. /**
  9361. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9362. *
  9363. * @tsl
  9364. * @type {UniformNode<mat4>}
  9365. */
  9366. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9367. let cameraProjectionMatrixInverse;
  9368. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9369. const matrices = [];
  9370. for ( const subCamera of camera.cameras ) {
  9371. matrices.push( subCamera.projectionMatrixInverse );
  9372. }
  9373. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9374. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9375. } else {
  9376. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9377. }
  9378. return cameraProjectionMatrixInverse;
  9379. } ).once() )();
  9380. /**
  9381. * TSL object that represents the view matrix of the camera used for the current render.
  9382. *
  9383. * @tsl
  9384. * @type {UniformNode<mat4>}
  9385. */
  9386. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9387. let cameraViewMatrix;
  9388. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9389. const matrices = [];
  9390. for ( const subCamera of camera.cameras ) {
  9391. matrices.push( subCamera.matrixWorldInverse );
  9392. }
  9393. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9394. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  9395. } else {
  9396. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  9397. }
  9398. return cameraViewMatrix;
  9399. } ).once() )();
  9400. /**
  9401. * TSL object that represents the world matrix of the camera used for the current render.
  9402. *
  9403. * @tsl
  9404. * @type {UniformNode<mat4>}
  9405. */
  9406. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9407. let cameraWorldMatrix;
  9408. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9409. const matrices = [];
  9410. for ( const subCamera of camera.cameras ) {
  9411. matrices.push( subCamera.matrixWorld );
  9412. }
  9413. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  9414. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  9415. } else {
  9416. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  9417. }
  9418. return cameraWorldMatrix;
  9419. } ).once() )();
  9420. /**
  9421. * TSL object that represents the normal matrix of the camera used for the current render.
  9422. *
  9423. * @tsl
  9424. * @type {UniformNode<mat3>}
  9425. */
  9426. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9427. let cameraNormalMatrix;
  9428. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9429. const matrices = [];
  9430. for ( const subCamera of camera.cameras ) {
  9431. matrices.push( subCamera.normalMatrix );
  9432. }
  9433. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  9434. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  9435. } else {
  9436. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  9437. }
  9438. return cameraNormalMatrix;
  9439. } ).once() )();
  9440. /**
  9441. * TSL object that represents the position in world space of the camera used for the current render.
  9442. *
  9443. * @tsl
  9444. * @type {UniformNode<vec3>}
  9445. */
  9446. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9447. let cameraPosition;
  9448. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9449. const positions = [];
  9450. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  9451. positions.push( new Vector3() );
  9452. }
  9453. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  9454. const subCameras = camera.cameras;
  9455. const array = self.array;
  9456. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  9457. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  9458. }
  9459. } );
  9460. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  9461. } else {
  9462. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  9463. }
  9464. return cameraPosition;
  9465. } ).once() )();
  9466. /**
  9467. * TSL object that represents the viewport of the camera used for the current render.
  9468. *
  9469. * @tsl
  9470. * @type {UniformNode<vec4>}
  9471. */
  9472. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9473. let cameraViewport;
  9474. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9475. const viewports = [];
  9476. for ( const subCamera of camera.cameras ) {
  9477. viewports.push( subCamera.viewport );
  9478. }
  9479. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  9480. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  9481. } else {
  9482. // Fallback for single camera
  9483. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  9484. }
  9485. return cameraViewport;
  9486. } ).once() )();
  9487. const _sphere = /*@__PURE__*/ new Sphere();
  9488. /**
  9489. * This node can be used to access transformation related metrics of 3D objects.
  9490. * Depending on the selected scope, a different metric is represented as a uniform
  9491. * in the shader. The following scopes are supported:
  9492. *
  9493. * - `POSITION`: The object's position in world space.
  9494. * - `VIEW_POSITION`: The object's position in view/camera space.
  9495. * - `DIRECTION`: The object's direction in world space.
  9496. * - `SCALE`: The object's scale in world space.
  9497. * - `WORLD_MATRIX`: The object's matrix in world space.
  9498. *
  9499. * @augments Node
  9500. */
  9501. class Object3DNode extends Node {
  9502. static get type() {
  9503. return 'Object3DNode';
  9504. }
  9505. /**
  9506. * Constructs a new object 3D node.
  9507. *
  9508. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9509. * @param {?Object3D} [object3d=null] - The 3D object.
  9510. */
  9511. constructor( scope, object3d = null ) {
  9512. super();
  9513. /**
  9514. * The node reports a different type of transformation depending on the scope.
  9515. *
  9516. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9517. */
  9518. this.scope = scope;
  9519. /**
  9520. * The 3D object.
  9521. *
  9522. * @type {?Object3D}
  9523. * @default null
  9524. */
  9525. this.object3d = object3d;
  9526. /**
  9527. * Overwritten since this type of node is updated per object.
  9528. *
  9529. * @type {string}
  9530. * @default 'object'
  9531. */
  9532. this.updateType = NodeUpdateType.OBJECT;
  9533. /**
  9534. * Holds the value of the node as a uniform.
  9535. *
  9536. * @type {UniformNode}
  9537. */
  9538. this.uniformNode = new UniformNode( null );
  9539. }
  9540. /**
  9541. * Overwritten since the node type is inferred from the scope.
  9542. *
  9543. * @return {('mat4'|'vec3'|'float')} The node type.
  9544. */
  9545. getNodeType() {
  9546. const scope = this.scope;
  9547. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9548. return 'mat4';
  9549. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9550. return 'vec3';
  9551. } else if ( scope === Object3DNode.RADIUS ) {
  9552. return 'float';
  9553. }
  9554. }
  9555. /**
  9556. * Updates the uniform value depending on the scope.
  9557. *
  9558. * @param {NodeFrame} frame - The current node frame.
  9559. */
  9560. update( frame ) {
  9561. const object = this.object3d;
  9562. const uniformNode = this.uniformNode;
  9563. const scope = this.scope;
  9564. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9565. uniformNode.value = object.matrixWorld;
  9566. } else if ( scope === Object3DNode.POSITION ) {
  9567. uniformNode.value = uniformNode.value || new Vector3();
  9568. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9569. } else if ( scope === Object3DNode.SCALE ) {
  9570. uniformNode.value = uniformNode.value || new Vector3();
  9571. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9572. } else if ( scope === Object3DNode.DIRECTION ) {
  9573. uniformNode.value = uniformNode.value || new Vector3();
  9574. object.getWorldDirection( uniformNode.value );
  9575. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9576. const camera = frame.camera;
  9577. uniformNode.value = uniformNode.value || new Vector3();
  9578. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9579. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9580. } else if ( scope === Object3DNode.RADIUS ) {
  9581. const geometry = frame.object.geometry;
  9582. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9583. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9584. uniformNode.value = _sphere.radius;
  9585. }
  9586. }
  9587. /**
  9588. * Generates the code snippet of the uniform node. The node type of the uniform
  9589. * node also depends on the selected scope.
  9590. *
  9591. * @param {NodeBuilder} builder - The current node builder.
  9592. * @return {string} The generated code snippet.
  9593. */
  9594. generate( builder ) {
  9595. const scope = this.scope;
  9596. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9597. this.uniformNode.nodeType = 'mat4';
  9598. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9599. this.uniformNode.nodeType = 'vec3';
  9600. } else if ( scope === Object3DNode.RADIUS ) {
  9601. this.uniformNode.nodeType = 'float';
  9602. }
  9603. return this.uniformNode.build( builder );
  9604. }
  9605. serialize( data ) {
  9606. super.serialize( data );
  9607. data.scope = this.scope;
  9608. }
  9609. deserialize( data ) {
  9610. super.deserialize( data );
  9611. this.scope = data.scope;
  9612. }
  9613. }
  9614. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9615. Object3DNode.POSITION = 'position';
  9616. Object3DNode.SCALE = 'scale';
  9617. Object3DNode.VIEW_POSITION = 'viewPosition';
  9618. Object3DNode.DIRECTION = 'direction';
  9619. Object3DNode.RADIUS = 'radius';
  9620. /**
  9621. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9622. *
  9623. * @tsl
  9624. * @function
  9625. * @param {?Object3D} [object3d] - The 3D object.
  9626. * @returns {Object3DNode<vec3>}
  9627. */
  9628. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9629. /**
  9630. * TSL function for creating an object 3D node that represents the object's world matrix.
  9631. *
  9632. * @tsl
  9633. * @function
  9634. * @param {?Object3D} [object3d] - The 3D object.
  9635. * @returns {Object3DNode<mat4>}
  9636. */
  9637. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9638. /**
  9639. * TSL function for creating an object 3D node that represents the object's position in world space.
  9640. *
  9641. * @tsl
  9642. * @function
  9643. * @param {?Object3D} [object3d] - The 3D object.
  9644. * @returns {Object3DNode<vec3>}
  9645. */
  9646. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9647. /**
  9648. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9649. *
  9650. * @tsl
  9651. * @function
  9652. * @param {?Object3D} [object3d] - The 3D object.
  9653. * @returns {Object3DNode<vec3>}
  9654. */
  9655. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9656. /**
  9657. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9658. *
  9659. * @tsl
  9660. * @function
  9661. * @param {?Object3D} [object3d] - The 3D object.
  9662. * @returns {Object3DNode<vec3>}
  9663. */
  9664. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9665. /**
  9666. * TSL function for creating an object 3D node that represents the object's radius.
  9667. *
  9668. * @tsl
  9669. * @function
  9670. * @param {?Object3D} [object3d] - The 3D object.
  9671. * @returns {Object3DNode<float>}
  9672. */
  9673. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9674. /**
  9675. * This type of node is a specialized version of `Object3DNode`
  9676. * with larger set of model related metrics. Unlike `Object3DNode`,
  9677. * `ModelNode` extracts the reference to the 3D object from the
  9678. * current node frame state.
  9679. *
  9680. * @augments Object3DNode
  9681. */
  9682. class ModelNode extends Object3DNode {
  9683. static get type() {
  9684. return 'ModelNode';
  9685. }
  9686. /**
  9687. * Constructs a new object model node.
  9688. *
  9689. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9690. */
  9691. constructor( scope ) {
  9692. super( scope );
  9693. }
  9694. /**
  9695. * Extracts the model reference from the frame state and then
  9696. * updates the uniform value depending on the scope.
  9697. *
  9698. * @param {NodeFrame} frame - The current node frame.
  9699. */
  9700. update( frame ) {
  9701. this.object3d = frame.object;
  9702. super.update( frame );
  9703. }
  9704. }
  9705. /**
  9706. * TSL object that represents the object's direction in world space.
  9707. *
  9708. * @tsl
  9709. * @type {ModelNode<vec3>}
  9710. */
  9711. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9712. /**
  9713. * TSL object that represents the object's world matrix.
  9714. *
  9715. * @tsl
  9716. * @type {ModelNode<mat4>}
  9717. */
  9718. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9719. /**
  9720. * TSL object that represents the object's position in world space.
  9721. *
  9722. * @tsl
  9723. * @type {ModelNode<vec3>}
  9724. */
  9725. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9726. /**
  9727. * TSL object that represents the object's scale in world space.
  9728. *
  9729. * @tsl
  9730. * @type {ModelNode<vec3>}
  9731. */
  9732. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9733. /**
  9734. * TSL object that represents the object's position in view/camera space.
  9735. *
  9736. * @tsl
  9737. * @type {ModelNode<vec3>}
  9738. */
  9739. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9740. /**
  9741. * TSL object that represents the object's radius.
  9742. *
  9743. * @tsl
  9744. * @type {ModelNode<float>}
  9745. */
  9746. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9747. /**
  9748. * TSL object that represents the object's normal matrix.
  9749. *
  9750. * @tsl
  9751. * @type {UniformNode<mat3>}
  9752. */
  9753. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9754. /**
  9755. * TSL object that represents the object's inverse world matrix.
  9756. *
  9757. * @tsl
  9758. * @type {UniformNode<mat4>}
  9759. */
  9760. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9761. /**
  9762. * TSL object that represents the object's model view matrix.
  9763. *
  9764. * @tsl
  9765. * @type {Node<mat4>}
  9766. */
  9767. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9768. return builder.context.modelViewMatrix || mediumpModelViewMatrix;
  9769. } ).once() )().toVar( 'modelViewMatrix' );
  9770. // GPU Precision
  9771. /**
  9772. * TSL object that represents the object's model view in `mediump` precision.
  9773. *
  9774. * @tsl
  9775. * @type {Node<mat4>}
  9776. */
  9777. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9778. // CPU Precision
  9779. /**
  9780. * TSL object that represents the object's model view in `highp` precision
  9781. * which is achieved by computing the matrix in JS and not in the shader.
  9782. *
  9783. * @tsl
  9784. * @type {Node<mat4>}
  9785. */
  9786. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9787. builder.context.isHighPrecisionModelViewMatrix = true;
  9788. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9789. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9790. } );
  9791. } ).once() )().toVar( 'highpModelViewMatrix' );
  9792. /**
  9793. * TSL object that represents the object's model normal view in `highp` precision
  9794. * which is achieved by computing the matrix in JS and not in the shader.
  9795. *
  9796. * @tsl
  9797. * @type {Node<mat3>}
  9798. */
  9799. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9800. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9801. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9802. if ( isHighPrecisionModelViewMatrix !== true ) {
  9803. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9804. }
  9805. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9806. } );
  9807. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9808. /**
  9809. * TSL object that represents the position attribute of the current rendered object.
  9810. *
  9811. * @tsl
  9812. * @type {AttributeNode<vec3>}
  9813. */
  9814. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9815. /**
  9816. * TSL object that represents the vertex position in local space of the current rendered object.
  9817. *
  9818. * @tsl
  9819. * @type {AttributeNode<vec3>}
  9820. */
  9821. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9822. /**
  9823. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9824. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9825. *
  9826. * @tsl
  9827. * @type {AttributeNode<vec3>}
  9828. */
  9829. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9830. /**
  9831. * TSL object that represents the vertex position in world space of the current rendered object.
  9832. *
  9833. * @tsl
  9834. * @type {VaryingNode<vec3>}
  9835. */
  9836. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9837. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9838. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9839. /**
  9840. * TSL object that represents the position world direction of the current rendered object.
  9841. *
  9842. * @tsl
  9843. * @type {Node<vec3>}
  9844. */
  9845. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9846. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9847. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9848. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9849. /**
  9850. * TSL object that represents the vertex position in view space of the current rendered object.
  9851. *
  9852. * @tsl
  9853. * @type {VaryingNode<vec3>}
  9854. */
  9855. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9856. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9857. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9858. /**
  9859. * TSL object that represents the position view direction of the current rendered object.
  9860. *
  9861. * @tsl
  9862. * @type {VaryingNode<vec3>}
  9863. */
  9864. const positionViewDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9865. let output;
  9866. if ( builder.camera.isOrthographicCamera ) {
  9867. output = vec3( 0, 0, 1 );
  9868. } else {
  9869. output = positionView.negate().toVarying( 'v_positionViewDirection' ).normalize();
  9870. }
  9871. return output.toVar( 'positionViewDirection' );
  9872. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9873. /**
  9874. * This node can be used to evaluate whether a primitive is front or back facing.
  9875. *
  9876. * @augments Node
  9877. */
  9878. class FrontFacingNode extends Node {
  9879. static get type() {
  9880. return 'FrontFacingNode';
  9881. }
  9882. /**
  9883. * Constructs a new front facing node.
  9884. */
  9885. constructor() {
  9886. super( 'bool' );
  9887. /**
  9888. * This flag can be used for type testing.
  9889. *
  9890. * @type {boolean}
  9891. * @readonly
  9892. * @default true
  9893. */
  9894. this.isFrontFacingNode = true;
  9895. }
  9896. generate( builder ) {
  9897. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9898. //
  9899. const { material } = builder;
  9900. if ( material.side === BackSide ) {
  9901. return 'false';
  9902. }
  9903. return builder.getFrontFacing();
  9904. }
  9905. }
  9906. /**
  9907. * TSL object that represents whether a primitive is front or back facing
  9908. *
  9909. * @tsl
  9910. * @type {FrontFacingNode<bool>}
  9911. */
  9912. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9913. /**
  9914. * TSL object that represents the front facing status as a number instead of a bool.
  9915. * `1` means front facing, `-1` means back facing.
  9916. *
  9917. * @tsl
  9918. * @type {Node<float>}
  9919. */
  9920. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9921. /**
  9922. * Converts a direction vector to a face direction vector based on the material's side.
  9923. *
  9924. * If the material is set to `BackSide`, the direction is inverted.
  9925. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9926. *
  9927. * @tsl
  9928. * @param {Node<vec3>} direction - The direction vector to convert.
  9929. * @returns {Node<vec3>} The converted direction vector.
  9930. */
  9931. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9932. const side = material.side;
  9933. if ( side === BackSide ) {
  9934. direction = direction.mul( -1 );
  9935. } else if ( side === DoubleSide ) {
  9936. direction = direction.mul( faceDirection );
  9937. }
  9938. return direction;
  9939. } );
  9940. /**
  9941. * TSL object that represents the normal attribute of the current rendered object in local space.
  9942. *
  9943. * @tsl
  9944. * @type {Node<vec3>}
  9945. */
  9946. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  9947. /**
  9948. * TSL object that represents the vertex normal of the current rendered object in local space.
  9949. *
  9950. * @tsl
  9951. * @type {Node<vec3>}
  9952. */
  9953. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  9954. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  9955. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  9956. return vec3( 0, 1, 0 );
  9957. }
  9958. return normalGeometry;
  9959. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  9960. /**
  9961. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  9962. *
  9963. * @tsl
  9964. * @type {Node<vec3>}
  9965. */
  9966. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  9967. /**
  9968. * TSL object that represents the vertex normal of the current rendered object in view space.
  9969. *
  9970. * @tsl
  9971. * @type {Node<vec3>}
  9972. */
  9973. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9974. let node;
  9975. if ( builder.material.flatShading === true ) {
  9976. node = normalFlat;
  9977. } else {
  9978. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  9979. }
  9980. return node;
  9981. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  9982. /**
  9983. * TSL object that represents the vertex normal of the current rendered object in world space.
  9984. *
  9985. * @tsl
  9986. * @type {Node<vec3>}
  9987. */
  9988. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9989. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  9990. if ( builder.material.flatShading !== true ) {
  9991. normal = normal.toVarying( 'v_normalWorldGeometry' );
  9992. }
  9993. return normal.normalize().toVar( 'normalWorldGeometry' );
  9994. }, 'vec3' ).once() )();
  9995. /**
  9996. * TSL object that represents the vertex normal of the current rendered object in view space.
  9997. *
  9998. * @tsl
  9999. * @type {Node<vec3>}
  10000. */
  10001. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  10002. let node;
  10003. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10004. node = normalViewGeometry;
  10005. if ( material.flatShading !== true ) {
  10006. node = directionToFaceDirection( node );
  10007. }
  10008. } else {
  10009. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  10010. node = context.setupNormal().context( { getUV: null } );
  10011. }
  10012. return node;
  10013. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  10014. /**
  10015. * TSL object that represents the vertex normal of the current rendered object in world space.
  10016. *
  10017. * @tsl
  10018. * @type {Node<vec3>}
  10019. */
  10020. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  10021. /**
  10022. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  10023. *
  10024. * @tsl
  10025. * @type {Node<vec3>}
  10026. */
  10027. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  10028. let node;
  10029. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10030. node = normalView;
  10031. } else {
  10032. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  10033. node = context.setupClearcoatNormal().context( { getUV: null } );
  10034. }
  10035. return node;
  10036. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  10037. /**
  10038. * Transforms the normal with the given matrix.
  10039. *
  10040. * @tsl
  10041. * @function
  10042. * @param {Node<vec3>} normal - The normal.
  10043. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  10044. * @return {Node<vec3>} The transformed normal.
  10045. */
  10046. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  10047. const m = mat3( matrix );
  10048. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  10049. return m.mul( transformedNormal ).xyz;
  10050. } );
  10051. /**
  10052. * Transforms the given normal from local to view space.
  10053. *
  10054. * @tsl
  10055. * @function
  10056. * @param {Node<vec3>} normal - The normal.
  10057. * @param {NodeBuilder} builder - The current node builder.
  10058. * @return {Node<vec3>} The transformed normal.
  10059. */
  10060. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  10061. const modelNormalViewMatrix = builder.context.modelNormalViewMatrix;
  10062. if ( modelNormalViewMatrix ) {
  10063. return modelNormalViewMatrix.transformDirection( normal );
  10064. }
  10065. //
  10066. const transformedNormal = modelNormalMatrix.mul( normal );
  10067. return cameraViewMatrix.transformDirection( transformedNormal );
  10068. } );
  10069. // Deprecated
  10070. /**
  10071. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  10072. *
  10073. * @tsl
  10074. * @type {Node<vec3>}
  10075. * @deprecated since r178. Use `normalView` instead.
  10076. */
  10077. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  10078. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  10079. return normalView;
  10080. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10081. /**
  10082. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  10083. *
  10084. * @tsl
  10085. * @type {Node<vec3>}
  10086. * @deprecated since r178. Use `normalWorld` instead.
  10087. */
  10088. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  10089. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  10090. return normalWorld;
  10091. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10092. /**
  10093. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  10094. *
  10095. * @tsl
  10096. * @type {Node<vec3>}
  10097. * @deprecated since r178. Use `clearcoatNormalView` instead.
  10098. */
  10099. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  10100. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  10101. return clearcoatNormalView;
  10102. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10103. const _e1$1 = /*@__PURE__*/ new Euler();
  10104. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10105. /**
  10106. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  10107. *
  10108. * @tsl
  10109. * @type {UniformNode<float>}
  10110. */
  10111. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  10112. /**
  10113. * TSL object that represents the intensity of environment maps of PBR materials.
  10114. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  10115. *
  10116. * @tsl
  10117. * @type {Node<float>}
  10118. */
  10119. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  10120. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  10121. } );
  10122. /**
  10123. * TSL object that represents the rotation of environment maps.
  10124. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  10125. * rotation of `scene.environment` instead.
  10126. *
  10127. * @tsl
  10128. * @type {Node<mat4>}
  10129. */
  10130. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  10131. return frame.material;
  10132. } ).onObjectUpdate( function ( { material, scene } ) {
  10133. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  10134. if ( rotation ) {
  10135. _e1$1.copy( rotation );
  10136. _m1$1.makeRotationFromEuler( _e1$1 );
  10137. } else {
  10138. _m1$1.identity();
  10139. }
  10140. return _m1$1;
  10141. } );
  10142. /**
  10143. * The reflect vector in view space.
  10144. *
  10145. * @tsl
  10146. * @type {Node<vec3>}
  10147. */
  10148. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  10149. /**
  10150. * The refract vector in view space.
  10151. *
  10152. * @tsl
  10153. * @type {Node<vec3>}
  10154. */
  10155. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  10156. /**
  10157. * Used for sampling cube maps when using cube reflection mapping.
  10158. *
  10159. * @tsl
  10160. * @type {Node<vec3>}
  10161. */
  10162. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10163. /**
  10164. * Used for sampling cube maps when using cube refraction mapping.
  10165. *
  10166. * @tsl
  10167. * @type {Node<vec3>}
  10168. */
  10169. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10170. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  10171. /**
  10172. * This type of uniform node represents a cube texture.
  10173. *
  10174. * @augments TextureNode
  10175. */
  10176. class CubeTextureNode extends TextureNode {
  10177. static get type() {
  10178. return 'CubeTextureNode';
  10179. }
  10180. /**
  10181. * Constructs a new cube texture node.
  10182. *
  10183. * @param {CubeTexture} value - The cube texture.
  10184. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10185. * @param {?Node<int>} [levelNode=null] - The level node.
  10186. * @param {?Node<float>} [biasNode=null] - The bias node.
  10187. */
  10188. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  10189. super( value, uvNode, levelNode, biasNode );
  10190. /**
  10191. * This flag can be used for type testing.
  10192. *
  10193. * @type {boolean}
  10194. * @readonly
  10195. * @default true
  10196. */
  10197. this.isCubeTextureNode = true;
  10198. }
  10199. /**
  10200. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  10201. *
  10202. * @param {NodeBuilder} builder - The current node builder.
  10203. * @return {string} The input type.
  10204. */
  10205. getInputType( /*builder*/ ) {
  10206. return 'cubeTexture';
  10207. }
  10208. /**
  10209. * Returns a default uvs based on the mapping type of the cube texture.
  10210. *
  10211. * @return {Node<vec3>} The default uv attribute.
  10212. */
  10213. getDefaultUV() {
  10214. const texture = this.value;
  10215. if ( texture.mapping === CubeReflectionMapping ) {
  10216. return reflectVector;
  10217. } else if ( texture.mapping === CubeRefractionMapping ) {
  10218. return refractVector;
  10219. } else {
  10220. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  10221. return vec3( 0, 0, 0 );
  10222. }
  10223. }
  10224. /**
  10225. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  10226. * for cube textures. The uv transformation matrix is not applied to cube textures.
  10227. *
  10228. * @param {boolean} value - The update toggle.
  10229. */
  10230. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  10231. /**
  10232. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  10233. * to modify the uv node for correct sampling.
  10234. *
  10235. * @param {NodeBuilder} builder - The current node builder.
  10236. * @param {Node} uvNode - The uv node to setup.
  10237. * @return {Node} The updated uv node.
  10238. */
  10239. setupUV( builder, uvNode ) {
  10240. const texture = this.value;
  10241. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  10242. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  10243. }
  10244. return materialEnvRotation.mul( uvNode );
  10245. }
  10246. /**
  10247. * Generates the uv code snippet.
  10248. *
  10249. * @param {NodeBuilder} builder - The current node builder.
  10250. * @param {Node} cubeUV - The uv node to generate code for.
  10251. * @return {string} The generated code snippet.
  10252. */
  10253. generateUV( builder, cubeUV ) {
  10254. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  10255. }
  10256. }
  10257. /**
  10258. * TSL function for creating a cube texture node.
  10259. *
  10260. * @tsl
  10261. * @function
  10262. * @param {CubeTexture} value - The cube texture.
  10263. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10264. * @param {?Node<int>} [levelNode=null] - The level node.
  10265. * @param {?Node<float>} [biasNode=null] - The bias node.
  10266. * @returns {CubeTextureNode}
  10267. */
  10268. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  10269. /**
  10270. * TSL function for creating a cube texture uniform node.
  10271. *
  10272. * @tsl
  10273. * @function
  10274. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  10275. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10276. * @param {?Node<int>} [levelNode=null] - The level node.
  10277. * @param {?Node<float>} [biasNode=null] - The bias node.
  10278. * @returns {CubeTextureNode}
  10279. */
  10280. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  10281. let textureNode;
  10282. if ( value && value.isCubeTextureNode === true ) {
  10283. textureNode = nodeObject( value.clone() );
  10284. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  10285. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  10286. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  10287. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  10288. } else {
  10289. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  10290. }
  10291. return textureNode;
  10292. };
  10293. /**
  10294. * TSL function for creating a uniform cube texture node.
  10295. *
  10296. * @tsl
  10297. * @function
  10298. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  10299. * @returns {CubeTextureNode}
  10300. */
  10301. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  10302. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  10303. /**
  10304. * This class is only relevant if the referenced property is array-like.
  10305. * In this case, `ReferenceElementNode` allows to refer to a specific
  10306. * element inside the data structure via an index.
  10307. *
  10308. * @augments ArrayElementNode
  10309. */
  10310. class ReferenceElementNode extends ArrayElementNode {
  10311. static get type() {
  10312. return 'ReferenceElementNode';
  10313. }
  10314. /**
  10315. * Constructs a new reference element node.
  10316. *
  10317. * @param {?ReferenceNode} referenceNode - The reference node.
  10318. * @param {Node} indexNode - The index node that defines the element access.
  10319. */
  10320. constructor( referenceNode, indexNode ) {
  10321. super( referenceNode, indexNode );
  10322. /**
  10323. * Similar to {@link ReferenceNode#reference}, an additional
  10324. * property references to the current node.
  10325. *
  10326. * @type {?ReferenceNode}
  10327. * @default null
  10328. */
  10329. this.referenceNode = referenceNode;
  10330. /**
  10331. * This flag can be used for type testing.
  10332. *
  10333. * @type {boolean}
  10334. * @readonly
  10335. * @default true
  10336. */
  10337. this.isReferenceElementNode = true;
  10338. }
  10339. /**
  10340. * This method is overwritten since the node type is inferred from
  10341. * the uniform type of the reference node.
  10342. *
  10343. * @return {string} The node type.
  10344. */
  10345. getNodeType() {
  10346. return this.referenceNode.uniformType;
  10347. }
  10348. generate( builder ) {
  10349. const snippet = super.generate( builder );
  10350. const arrayType = this.referenceNode.getNodeType();
  10351. const elementType = this.getNodeType();
  10352. return builder.format( snippet, arrayType, elementType );
  10353. }
  10354. }
  10355. /**
  10356. * This type of node establishes a reference to a property of another object.
  10357. * In this way, the value of the node is automatically linked to the value of
  10358. * referenced object. Reference nodes internally represent the linked value
  10359. * as a uniform.
  10360. *
  10361. * @augments Node
  10362. */
  10363. class ReferenceNode extends Node {
  10364. static get type() {
  10365. return 'ReferenceNode';
  10366. }
  10367. /**
  10368. * Constructs a new reference node.
  10369. *
  10370. * @param {string} property - The name of the property the node refers to.
  10371. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  10372. * @param {?Object} [object=null] - The object the property belongs to.
  10373. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  10374. */
  10375. constructor( property, uniformType, object = null, count = null ) {
  10376. super();
  10377. /**
  10378. * The name of the property the node refers to.
  10379. *
  10380. * @type {string}
  10381. */
  10382. this.property = property;
  10383. /**
  10384. * The uniform type that should be used to represent the property value.
  10385. *
  10386. * @type {string}
  10387. */
  10388. this.uniformType = uniformType;
  10389. /**
  10390. * The object the property belongs to.
  10391. *
  10392. * @type {?Object}
  10393. * @default null
  10394. */
  10395. this.object = object;
  10396. /**
  10397. * When the linked property is an array, this parameter defines its length.
  10398. *
  10399. * @type {?number}
  10400. * @default null
  10401. */
  10402. this.count = count;
  10403. /**
  10404. * The property name might have dots so nested properties can be referred.
  10405. * The hierarchy of the names is stored inside this array.
  10406. *
  10407. * @type {Array<string>}
  10408. */
  10409. this.properties = property.split( '.' );
  10410. /**
  10411. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  10412. * since the final reference might be updated from calling code.
  10413. *
  10414. * @type {?Object}
  10415. * @default null
  10416. */
  10417. this.reference = object;
  10418. /**
  10419. * The uniform node that holds the value of the reference node.
  10420. *
  10421. * @type {UniformNode}
  10422. * @default null
  10423. */
  10424. this.node = null;
  10425. /**
  10426. * The uniform group of the internal uniform.
  10427. *
  10428. * @type {UniformGroupNode}
  10429. * @default null
  10430. */
  10431. this.group = null;
  10432. /**
  10433. * An optional label of the internal uniform node.
  10434. *
  10435. * @type {?string}
  10436. * @default null
  10437. */
  10438. this.name = null;
  10439. /**
  10440. * Overwritten since reference nodes are updated per object.
  10441. *
  10442. * @type {string}
  10443. * @default 'object'
  10444. */
  10445. this.updateType = NodeUpdateType.OBJECT;
  10446. }
  10447. /**
  10448. * When the referred property is array-like, this method can be used
  10449. * to access elements via an index node.
  10450. *
  10451. * @param {IndexNode} indexNode - indexNode.
  10452. * @return {ReferenceElementNode} A reference to an element.
  10453. */
  10454. element( indexNode ) {
  10455. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  10456. }
  10457. /**
  10458. * Sets the uniform group for this reference node.
  10459. *
  10460. * @param {UniformGroupNode} group - The uniform group to set.
  10461. * @return {ReferenceNode} A reference to this node.
  10462. */
  10463. setGroup( group ) {
  10464. this.group = group;
  10465. return this;
  10466. }
  10467. /**
  10468. * Sets the name for the internal uniform.
  10469. *
  10470. * @param {string} name - The label to set.
  10471. * @return {ReferenceNode} A reference to this node.
  10472. */
  10473. setName( name ) {
  10474. this.name = name;
  10475. return this;
  10476. }
  10477. /**
  10478. * Sets the label for the internal uniform.
  10479. *
  10480. * @deprecated
  10481. * @param {string} name - The label to set.
  10482. * @return {ReferenceNode} A reference to this node.
  10483. */
  10484. label( name ) {
  10485. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  10486. return this.setName( name );
  10487. }
  10488. /**
  10489. * Sets the node type which automatically defines the internal
  10490. * uniform type.
  10491. *
  10492. * @param {string} uniformType - The type to set.
  10493. */
  10494. setNodeType( uniformType ) {
  10495. let node = null;
  10496. if ( this.count !== null ) {
  10497. node = buffer( null, uniformType, this.count );
  10498. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  10499. node = uniformArray( null, uniformType );
  10500. } else if ( uniformType === 'texture' ) {
  10501. node = texture( null );
  10502. } else if ( uniformType === 'cubeTexture' ) {
  10503. node = cubeTexture( null );
  10504. } else {
  10505. node = uniform( null, uniformType );
  10506. }
  10507. if ( this.group !== null ) {
  10508. node.setGroup( this.group );
  10509. }
  10510. if ( this.name !== null ) node.setName( this.name );
  10511. this.node = node;
  10512. }
  10513. /**
  10514. * This method is overwritten since the node type is inferred from
  10515. * the type of the reference node.
  10516. *
  10517. * @param {NodeBuilder} builder - The current node builder.
  10518. * @return {string} The node type.
  10519. */
  10520. getNodeType( builder ) {
  10521. if ( this.node === null ) {
  10522. this.updateReference( builder );
  10523. this.updateValue();
  10524. }
  10525. return this.node.getNodeType( builder );
  10526. }
  10527. /**
  10528. * Returns the property value from the given referred object.
  10529. *
  10530. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10531. * @return {any} The value.
  10532. */
  10533. getValueFromReference( object = this.reference ) {
  10534. const { properties } = this;
  10535. let value = object[ properties[ 0 ] ];
  10536. for ( let i = 1; i < properties.length; i ++ ) {
  10537. value = value[ properties[ i ] ];
  10538. }
  10539. return value;
  10540. }
  10541. /**
  10542. * Allows to update the reference based on the given state. The state is only
  10543. * evaluated {@link ReferenceNode#object} is not set.
  10544. *
  10545. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10546. * @return {Object} The updated reference.
  10547. */
  10548. updateReference( state ) {
  10549. this.reference = this.object !== null ? this.object : state.object;
  10550. return this.reference;
  10551. }
  10552. /**
  10553. * The output of the reference node is the internal uniform node.
  10554. *
  10555. * @param {NodeBuilder} builder - The current node builder.
  10556. * @return {UniformNode} The output node.
  10557. */
  10558. setup( /* builder */ ) {
  10559. this.updateValue();
  10560. return this.node;
  10561. }
  10562. /**
  10563. * Overwritten to update the internal uniform value.
  10564. *
  10565. * @param {NodeFrame} frame - A reference to the current node frame.
  10566. */
  10567. update( /*frame*/ ) {
  10568. this.updateValue();
  10569. }
  10570. /**
  10571. * Retrieves the value from the referred object property and uses it
  10572. * to updated the internal uniform.
  10573. */
  10574. updateValue() {
  10575. if ( this.node === null ) this.setNodeType( this.uniformType );
  10576. const value = this.getValueFromReference();
  10577. if ( Array.isArray( value ) ) {
  10578. this.node.array = value;
  10579. } else {
  10580. this.node.value = value;
  10581. }
  10582. }
  10583. }
  10584. /**
  10585. * TSL function for creating a reference node.
  10586. *
  10587. * @tsl
  10588. * @function
  10589. * @param {string} name - The name of the property the node refers to.
  10590. * @param {string} type - The uniform type that should be used to represent the property value.
  10591. * @param {?Object} [object] - The object the property belongs to.
  10592. * @returns {ReferenceNode}
  10593. */
  10594. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  10595. /**
  10596. * TSL function for creating a reference node. Use this function if you want need a reference
  10597. * to an array-like property that should be represented as a uniform buffer.
  10598. *
  10599. * @tsl
  10600. * @function
  10601. * @param {string} name - The name of the property the node refers to.
  10602. * @param {string} type - The uniform type that should be used to represent the property value.
  10603. * @param {number} count - The number of value inside the array-like object.
  10604. * @param {Object} object - An array-like object the property belongs to.
  10605. * @returns {ReferenceNode}
  10606. */
  10607. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  10608. /**
  10609. * This node is a special type of reference node which is intended
  10610. * for linking material properties with node values.
  10611. * ```js
  10612. * const opacityNode = materialReference( 'opacity', 'float', material );
  10613. * ```
  10614. * When changing `material.opacity`, the node value of `opacityNode` will
  10615. * automatically be updated.
  10616. *
  10617. * @augments ReferenceNode
  10618. */
  10619. class MaterialReferenceNode extends ReferenceNode {
  10620. static get type() {
  10621. return 'MaterialReferenceNode';
  10622. }
  10623. /**
  10624. * Constructs a new material reference node.
  10625. *
  10626. * @param {string} property - The name of the property the node refers to.
  10627. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10628. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10629. * the node refers to the material of the current rendered object.
  10630. */
  10631. constructor( property, inputType, material = null ) {
  10632. super( property, inputType, material );
  10633. /**
  10634. * The material the property belongs to. When no material is set,
  10635. * the node refers to the material of the current rendered object.
  10636. *
  10637. * @type {?Material}
  10638. * @default null
  10639. */
  10640. this.material = material;
  10641. /**
  10642. * This flag can be used for type testing.
  10643. *
  10644. * @type {boolean}
  10645. * @readonly
  10646. * @default true
  10647. */
  10648. this.isMaterialReferenceNode = true;
  10649. }
  10650. /**
  10651. * Updates the reference based on the given state. The state is only evaluated
  10652. * {@link MaterialReferenceNode#material} is not set.
  10653. *
  10654. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10655. * @return {Object} The updated reference.
  10656. */
  10657. updateReference( state ) {
  10658. this.reference = this.material !== null ? this.material : state.material;
  10659. return this.reference;
  10660. }
  10661. }
  10662. /**
  10663. * TSL function for creating a material reference node.
  10664. *
  10665. * @tsl
  10666. * @function
  10667. * @param {string} name - The name of the property the node refers to.
  10668. * @param {string} type - The uniform type that should be used to represent the property value.
  10669. * @param {?Material} [material=null] - The material the property belongs to.
  10670. * When no material is set, the node refers to the material of the current rendered object.
  10671. * @returns {MaterialReferenceNode}
  10672. */
  10673. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  10674. // Normal Mapping Without Precomputed Tangents
  10675. // http://www.thetenthplanet.de/archives/1180
  10676. const uv = uv$1();
  10677. const q0 = positionView.dFdx();
  10678. const q1 = positionView.dFdy();
  10679. const st0 = uv.dFdx();
  10680. const st1 = uv.dFdy();
  10681. const N = normalView;
  10682. const q1perp = q1.cross( N );
  10683. const q0perp = N.cross( q0 );
  10684. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10685. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10686. const det = T.dot( T ).max( B.dot( B ) );
  10687. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10688. /**
  10689. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10690. * Useful for normal mapping without precomputed tangents.
  10691. *
  10692. * Reference: http://www.thetenthplanet.de/archives/1180
  10693. *
  10694. * @tsl
  10695. * @type {Node<vec3>}
  10696. */
  10697. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10698. /**
  10699. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10700. * Complements the tangentViewFrame for constructing the tangent space basis.
  10701. *
  10702. * Reference: http://www.thetenthplanet.de/archives/1180
  10703. *
  10704. * @tsl
  10705. * @type {Node<vec3>}
  10706. */
  10707. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10708. /**
  10709. * TSL object that represents the tangent attribute of the current rendered object.
  10710. *
  10711. * @tsl
  10712. * @type {Node<vec4>}
  10713. */
  10714. const tangentGeometry = /*@__PURE__*/ attribute( 'tangent', 'vec4' );
  10715. /**
  10716. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10717. *
  10718. * @tsl
  10719. * @type {Node<vec3>}
  10720. */
  10721. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10722. /**
  10723. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10724. *
  10725. * @tsl
  10726. * @type {Node<vec3>}
  10727. */
  10728. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10729. let node;
  10730. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10731. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10732. } else {
  10733. node = tangentViewFrame;
  10734. }
  10735. if ( material.flatShading !== true ) {
  10736. node = directionToFaceDirection( node );
  10737. }
  10738. return node;
  10739. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10740. /**
  10741. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10742. *
  10743. * @tsl
  10744. * @type {Node<vec3>}
  10745. */
  10746. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10747. /**
  10748. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10749. *
  10750. * @tsl
  10751. * @private
  10752. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10753. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10754. * @returns {Node<vec3>} The bitangent node.
  10755. */
  10756. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10757. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10758. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10759. bitangent = bitangent.toVarying( varyingName );
  10760. }
  10761. return bitangent;
  10762. } ).once( [ 'NORMAL' ] );
  10763. /**
  10764. * TSL object that represents the bitangent attribute of the current rendered object.
  10765. *
  10766. * @tsl
  10767. * @type {Node<vec3>}
  10768. */
  10769. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10770. /**
  10771. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10772. *
  10773. * @tsl
  10774. * @type {Node<vec3>}
  10775. */
  10776. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10777. /**
  10778. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10779. *
  10780. * @tsl
  10781. * @type {Node<vec3>}
  10782. */
  10783. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10784. let node;
  10785. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10786. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10787. } else {
  10788. node = bitangentViewFrame;
  10789. }
  10790. if ( material.flatShading !== true ) {
  10791. node = directionToFaceDirection( node );
  10792. }
  10793. return node;
  10794. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10795. /**
  10796. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10797. *
  10798. * @tsl
  10799. * @type {Node<vec3>}
  10800. */
  10801. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10802. /**
  10803. * TSL object that represents the TBN matrix in view space.
  10804. *
  10805. * @tsl
  10806. * @type {Node<mat3>}
  10807. */
  10808. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10809. /**
  10810. * TSL object that represents the parallax direction.
  10811. *
  10812. * @tsl
  10813. * @type {Node<mat3>}
  10814. */
  10815. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10816. /**
  10817. * TSL function for computing parallax uv coordinates.
  10818. *
  10819. * @tsl
  10820. * @function
  10821. * @param {Node<vec2>} uv - A uv node.
  10822. * @param {Node<vec2>} scale - A scale node.
  10823. * @returns {Node<vec2>} Parallax uv coordinates.
  10824. */
  10825. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10826. /**
  10827. * TSL function for computing bent normals.
  10828. *
  10829. * @tsl
  10830. * @function
  10831. * @returns {Node<vec3>} Bent normals.
  10832. */
  10833. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10834. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10835. let bentNormal = anisotropyB.cross( positionViewDirection );
  10836. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10837. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10838. return bentNormal;
  10839. } ).once() )();
  10840. /**
  10841. * Packs a direction vector into a color value.
  10842. *
  10843. * @tsl
  10844. * @function
  10845. * @param {Node<vec3>} node - The direction to pack.
  10846. * @return {Node<vec3>} The color.
  10847. */
  10848. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  10849. /**
  10850. * Unpacks a color value into a direction vector.
  10851. *
  10852. * @tsl
  10853. * @function
  10854. * @param {Node<vec3>} node - The color to unpack.
  10855. * @return {Node<vec3>} The direction.
  10856. */
  10857. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  10858. /**
  10859. * Unpacks a tangent space normal, reconstructing the Z component by projecting the X,Y coordinates onto the hemisphere.
  10860. * The X,Y coordinates are expected to be in the [-1, 1] range.
  10861. *
  10862. * @tsl
  10863. * @function
  10864. * @param {Node<vec2>} xy - The X,Y coordinates of the normal.
  10865. * @return {Node<vec3>} The resulting normal.
  10866. */
  10867. const unpackNormal = ( xy ) => vec3( xy, sqrt( saturate( float( 1.0 ).sub( dot( xy, xy ) ) ) ) );
  10868. /**
  10869. * This class can be used for applying normals maps to materials.
  10870. *
  10871. * ```js
  10872. * material.normalNode = normalMap( texture( normalTex ) );
  10873. * ```
  10874. *
  10875. * @augments TempNode
  10876. */
  10877. class NormalMapNode extends TempNode {
  10878. static get type() {
  10879. return 'NormalMapNode';
  10880. }
  10881. /**
  10882. * Constructs a new normal map node.
  10883. *
  10884. * @param {Node<vec3>} node - Represents the normal map data.
  10885. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10886. */
  10887. constructor( node, scaleNode = null ) {
  10888. super( 'vec3' );
  10889. /**
  10890. * Represents the normal map data.
  10891. *
  10892. * @type {Node<vec3>}
  10893. */
  10894. this.node = node;
  10895. /**
  10896. * Controls the intensity of the effect.
  10897. *
  10898. * @type {?Node<vec2>}
  10899. * @default null
  10900. */
  10901. this.scaleNode = scaleNode;
  10902. /**
  10903. * The normal map type.
  10904. *
  10905. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10906. * @default TangentSpaceNormalMap
  10907. */
  10908. this.normalMapType = TangentSpaceNormalMap;
  10909. /**
  10910. * Controls how to unpack the sampled normal map values.
  10911. *
  10912. * @type {string}
  10913. * @default NoNormalPacking
  10914. */
  10915. this.unpackNormalMode = NoNormalPacking;
  10916. }
  10917. setup( { material } ) {
  10918. const { normalMapType, scaleNode, unpackNormalMode } = this;
  10919. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10920. if ( normalMapType === TangentSpaceNormalMap ) {
  10921. if ( unpackNormalMode === NormalRGPacking ) {
  10922. normalMap = unpackNormal( normalMap.xy );
  10923. } else if ( unpackNormalMode === NormalGAPacking ) {
  10924. normalMap = unpackNormal( normalMap.yw );
  10925. } else if ( unpackNormalMode !== NoNormalPacking ) {
  10926. console.error( `THREE.NodeMaterial: Unexpected unpack normal mode: ${ unpackNormalMode }` );
  10927. }
  10928. } else {
  10929. if ( unpackNormalMode !== NoNormalPacking ) {
  10930. console.error( `THREE.NodeMaterial: Normal map type '${ normalMapType }' is not compatible with unpack normal mode '${ unpackNormalMode }'` );
  10931. }
  10932. }
  10933. if ( scaleNode !== null ) {
  10934. let scale = scaleNode;
  10935. if ( material.flatShading === true ) {
  10936. scale = directionToFaceDirection( scale );
  10937. }
  10938. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  10939. }
  10940. let output = null;
  10941. if ( normalMapType === ObjectSpaceNormalMap ) {
  10942. output = transformNormalToView( normalMap );
  10943. } else if ( normalMapType === TangentSpaceNormalMap ) {
  10944. output = TBNViewMatrix.mul( normalMap ).normalize();
  10945. } else {
  10946. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  10947. output = normalView; // Fallback to default normal view
  10948. }
  10949. return output;
  10950. }
  10951. }
  10952. /**
  10953. * TSL function for creating a normal map node.
  10954. *
  10955. * @tsl
  10956. * @function
  10957. * @param {Node<vec3>} node - Represents the normal map data.
  10958. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10959. * @returns {NormalMapNode}
  10960. */
  10961. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  10962. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  10963. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  10964. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  10965. // It's used to preserve the same TextureNode instance
  10966. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  10967. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  10968. return vec2(
  10969. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  10970. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  10971. ).mul( bumpScale );
  10972. } );
  10973. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10974. const perturbNormalArb = Fn( ( inputs ) => {
  10975. const { surf_pos, surf_norm, dHdxy } = inputs;
  10976. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  10977. const vSigmaX = surf_pos.dFdx().normalize();
  10978. const vSigmaY = surf_pos.dFdy().normalize();
  10979. const vN = surf_norm; // normalized
  10980. const R1 = vSigmaY.cross( vN );
  10981. const R2 = vN.cross( vSigmaX );
  10982. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  10983. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  10984. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  10985. } );
  10986. /**
  10987. * This class can be used for applying bump maps to materials.
  10988. *
  10989. * ```js
  10990. * material.normalNode = bumpMap( texture( bumpTex ) );
  10991. * ```
  10992. *
  10993. * @augments TempNode
  10994. */
  10995. class BumpMapNode extends TempNode {
  10996. static get type() {
  10997. return 'BumpMapNode';
  10998. }
  10999. /**
  11000. * Constructs a new bump map node.
  11001. *
  11002. * @param {Node<float>} textureNode - Represents the bump map data.
  11003. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11004. */
  11005. constructor( textureNode, scaleNode = null ) {
  11006. super( 'vec3' );
  11007. /**
  11008. * Represents the bump map data.
  11009. *
  11010. * @type {Node<float>}
  11011. */
  11012. this.textureNode = textureNode;
  11013. /**
  11014. * Controls the intensity of the bump effect.
  11015. *
  11016. * @type {?Node<float>}
  11017. * @default null
  11018. */
  11019. this.scaleNode = scaleNode;
  11020. }
  11021. setup() {
  11022. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  11023. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  11024. return perturbNormalArb( {
  11025. surf_pos: positionView,
  11026. surf_norm: normalView,
  11027. dHdxy
  11028. } );
  11029. }
  11030. }
  11031. /**
  11032. * TSL function for creating a bump map node.
  11033. *
  11034. * @tsl
  11035. * @function
  11036. * @param {Node<float>} textureNode - Represents the bump map data.
  11037. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11038. * @returns {BumpMapNode}
  11039. */
  11040. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  11041. const _propertyCache = new Map();
  11042. /**
  11043. * This class should simplify the node access to material properties.
  11044. * It internal uses reference nodes to make sure changes to material
  11045. * properties are automatically reflected to predefined TSL objects
  11046. * like e.g. `materialColor`.
  11047. *
  11048. * @augments Node
  11049. */
  11050. class MaterialNode extends Node {
  11051. static get type() {
  11052. return 'MaterialNode';
  11053. }
  11054. /**
  11055. * Constructs a new material node.
  11056. *
  11057. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  11058. */
  11059. constructor( scope ) {
  11060. super();
  11061. /**
  11062. * The scope defines what material property is referred by the node.
  11063. *
  11064. * @type {string}
  11065. */
  11066. this.scope = scope;
  11067. }
  11068. /**
  11069. * Returns a cached reference node for the given property and type.
  11070. *
  11071. * @param {string} property - The name of the material property.
  11072. * @param {string} type - The uniform type of the property.
  11073. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11074. */
  11075. getCache( property, type ) {
  11076. let node = _propertyCache.get( property );
  11077. if ( node === undefined ) {
  11078. node = materialReference( property, type );
  11079. _propertyCache.set( property, node );
  11080. }
  11081. return node;
  11082. }
  11083. /**
  11084. * Returns a float-typed material reference node for the given property name.
  11085. *
  11086. * @param {string} property - The name of the material property.
  11087. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  11088. */
  11089. getFloat( property ) {
  11090. return this.getCache( property, 'float' );
  11091. }
  11092. /**
  11093. * Returns a color-typed material reference node for the given property name.
  11094. *
  11095. * @param {string} property - The name of the material property.
  11096. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  11097. */
  11098. getColor( property ) {
  11099. return this.getCache( property, 'color' );
  11100. }
  11101. /**
  11102. * Returns a texture-typed material reference node for the given property name.
  11103. *
  11104. * @param {string} property - The name of the material property.
  11105. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11106. */
  11107. getTexture( property ) {
  11108. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  11109. }
  11110. /**
  11111. * The node setup is done depending on the selected scope. Multiple material properties
  11112. * might be grouped into a single node composition if they logically belong together.
  11113. *
  11114. * @param {NodeBuilder} builder - The current node builder.
  11115. * @return {Node} The node representing the selected scope.
  11116. */
  11117. setup( builder ) {
  11118. const material = builder.context.material;
  11119. const scope = this.scope;
  11120. let node = null;
  11121. if ( scope === MaterialNode.COLOR ) {
  11122. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  11123. if ( material.map && material.map.isTexture === true ) {
  11124. node = colorNode.mul( this.getTexture( 'map' ) );
  11125. } else {
  11126. node = colorNode;
  11127. }
  11128. } else if ( scope === MaterialNode.OPACITY ) {
  11129. const opacityNode = this.getFloat( scope );
  11130. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  11131. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  11132. } else {
  11133. node = opacityNode;
  11134. }
  11135. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  11136. if ( material.specularMap && material.specularMap.isTexture === true ) {
  11137. node = this.getTexture( 'specular' ).r;
  11138. } else {
  11139. node = float( 1 );
  11140. }
  11141. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  11142. const specularIntensityNode = this.getFloat( scope );
  11143. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  11144. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  11145. } else {
  11146. node = specularIntensityNode;
  11147. }
  11148. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  11149. const specularColorNode = this.getColor( scope );
  11150. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  11151. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  11152. } else {
  11153. node = specularColorNode;
  11154. }
  11155. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  11156. const roughnessNode = this.getFloat( scope );
  11157. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  11158. node = roughnessNode.mul( this.getTexture( scope ).g );
  11159. } else {
  11160. node = roughnessNode;
  11161. }
  11162. } else if ( scope === MaterialNode.METALNESS ) {
  11163. const metalnessNode = this.getFloat( scope );
  11164. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  11165. node = metalnessNode.mul( this.getTexture( scope ).b );
  11166. } else {
  11167. node = metalnessNode;
  11168. }
  11169. } else if ( scope === MaterialNode.EMISSIVE ) {
  11170. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  11171. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  11172. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  11173. node = emissiveNode.mul( this.getTexture( scope ) );
  11174. } else {
  11175. node = emissiveNode;
  11176. }
  11177. } else if ( scope === MaterialNode.NORMAL ) {
  11178. if ( material.normalMap ) {
  11179. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  11180. node.normalMapType = material.normalMapType;
  11181. if ( material.normalMap.format == RGFormat || material.normalMap.format == RED_GREEN_RGTC2_Format || material.normalMap.format == RG11_EAC_Format ) {
  11182. node.unpackNormalMode = NormalRGPacking;
  11183. }
  11184. } else if ( material.bumpMap ) {
  11185. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  11186. } else {
  11187. node = normalView;
  11188. }
  11189. } else if ( scope === MaterialNode.CLEARCOAT ) {
  11190. const clearcoatNode = this.getFloat( scope );
  11191. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  11192. node = clearcoatNode.mul( this.getTexture( scope ).r );
  11193. } else {
  11194. node = clearcoatNode;
  11195. }
  11196. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  11197. const clearcoatRoughnessNode = this.getFloat( scope );
  11198. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  11199. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  11200. } else {
  11201. node = clearcoatRoughnessNode;
  11202. }
  11203. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  11204. if ( material.clearcoatNormalMap ) {
  11205. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  11206. } else {
  11207. node = normalView;
  11208. }
  11209. } else if ( scope === MaterialNode.SHEEN ) {
  11210. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  11211. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  11212. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  11213. } else {
  11214. node = sheenNode;
  11215. }
  11216. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  11217. const sheenRoughnessNode = this.getFloat( scope );
  11218. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  11219. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  11220. } else {
  11221. node = sheenRoughnessNode;
  11222. }
  11223. node = node.clamp( 0.0001, 1.0 );
  11224. } else if ( scope === MaterialNode.ANISOTROPY ) {
  11225. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  11226. const anisotropyPolar = this.getTexture( scope );
  11227. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  11228. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  11229. } else {
  11230. node = materialAnisotropyVector;
  11231. }
  11232. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  11233. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  11234. if ( material.iridescenceThicknessMap ) {
  11235. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  11236. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  11237. } else {
  11238. node = iridescenceThicknessMaximum;
  11239. }
  11240. } else if ( scope === MaterialNode.TRANSMISSION ) {
  11241. const transmissionNode = this.getFloat( scope );
  11242. if ( material.transmissionMap ) {
  11243. node = transmissionNode.mul( this.getTexture( scope ).r );
  11244. } else {
  11245. node = transmissionNode;
  11246. }
  11247. } else if ( scope === MaterialNode.THICKNESS ) {
  11248. const thicknessNode = this.getFloat( scope );
  11249. if ( material.thicknessMap ) {
  11250. node = thicknessNode.mul( this.getTexture( scope ).g );
  11251. } else {
  11252. node = thicknessNode;
  11253. }
  11254. } else if ( scope === MaterialNode.IOR ) {
  11255. node = this.getFloat( scope );
  11256. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  11257. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  11258. } else if ( scope === MaterialNode.AO ) {
  11259. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  11260. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  11261. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  11262. } else {
  11263. const outputType = this.getNodeType( builder );
  11264. node = this.getCache( scope, outputType );
  11265. }
  11266. return node;
  11267. }
  11268. }
  11269. MaterialNode.ALPHA_TEST = 'alphaTest';
  11270. MaterialNode.COLOR = 'color';
  11271. MaterialNode.OPACITY = 'opacity';
  11272. MaterialNode.SHININESS = 'shininess';
  11273. MaterialNode.SPECULAR = 'specular';
  11274. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  11275. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  11276. MaterialNode.SPECULAR_COLOR = 'specularColor';
  11277. MaterialNode.REFLECTIVITY = 'reflectivity';
  11278. MaterialNode.ROUGHNESS = 'roughness';
  11279. MaterialNode.METALNESS = 'metalness';
  11280. MaterialNode.NORMAL = 'normal';
  11281. MaterialNode.CLEARCOAT = 'clearcoat';
  11282. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  11283. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  11284. MaterialNode.EMISSIVE = 'emissive';
  11285. MaterialNode.ROTATION = 'rotation';
  11286. MaterialNode.SHEEN = 'sheen';
  11287. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  11288. MaterialNode.ANISOTROPY = 'anisotropy';
  11289. MaterialNode.IRIDESCENCE = 'iridescence';
  11290. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  11291. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  11292. MaterialNode.IOR = 'ior';
  11293. MaterialNode.TRANSMISSION = 'transmission';
  11294. MaterialNode.THICKNESS = 'thickness';
  11295. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  11296. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  11297. MaterialNode.LINE_SCALE = 'scale';
  11298. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  11299. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  11300. MaterialNode.LINE_WIDTH = 'linewidth';
  11301. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  11302. MaterialNode.POINT_SIZE = 'size';
  11303. MaterialNode.DISPERSION = 'dispersion';
  11304. MaterialNode.LIGHT_MAP = 'light';
  11305. MaterialNode.AO = 'ao';
  11306. /**
  11307. * TSL object that represents alpha test of the current material.
  11308. *
  11309. * @tsl
  11310. * @type {Node<float>}
  11311. */
  11312. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  11313. /**
  11314. * TSL object that represents the diffuse color of the current material.
  11315. * The value is composed via `color` * `map`.
  11316. *
  11317. * @tsl
  11318. * @type {Node<vec3>}
  11319. */
  11320. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  11321. /**
  11322. * TSL object that represents the shininess of the current material.
  11323. *
  11324. * @tsl
  11325. * @type {Node<float>}
  11326. */
  11327. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  11328. /**
  11329. * TSL object that represents the emissive color of the current material.
  11330. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  11331. *
  11332. * @tsl
  11333. * @type {Node<vec3>}
  11334. */
  11335. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  11336. /**
  11337. * TSL object that represents the opacity of the current material.
  11338. * The value is composed via `opacity` * `alphaMap`.
  11339. *
  11340. * @tsl
  11341. * @type {Node<float>}
  11342. */
  11343. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  11344. /**
  11345. * TSL object that represents the specular of the current material.
  11346. *
  11347. * @tsl
  11348. * @type {Node<vec3>}
  11349. */
  11350. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  11351. /**
  11352. * TSL object that represents the specular intensity of the current material.
  11353. * The value is composed via `specularIntensity` * `specularMap.a`.
  11354. *
  11355. * @tsl
  11356. * @type {Node<float>}
  11357. */
  11358. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  11359. /**
  11360. * TSL object that represents the specular color of the current material.
  11361. * The value is composed via `specularColor` * `specularMap.rgb`.
  11362. *
  11363. * @tsl
  11364. * @type {Node<vec3>}
  11365. */
  11366. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  11367. /**
  11368. * TSL object that represents the specular strength of the current material.
  11369. * The value is composed via `specularMap.r`.
  11370. *
  11371. * @tsl
  11372. * @type {Node<float>}
  11373. */
  11374. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  11375. /**
  11376. * TSL object that represents the reflectivity of the current material.
  11377. *
  11378. * @tsl
  11379. * @type {Node<float>}
  11380. */
  11381. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  11382. /**
  11383. * TSL object that represents the roughness of the current material.
  11384. * The value is composed via `roughness` * `roughnessMap.g`.
  11385. *
  11386. * @tsl
  11387. * @type {Node<float>}
  11388. */
  11389. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  11390. /**
  11391. * TSL object that represents the metalness of the current material.
  11392. * The value is composed via `metalness` * `metalnessMap.b`.
  11393. *
  11394. * @tsl
  11395. * @type {Node<float>}
  11396. */
  11397. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  11398. /**
  11399. * TSL object that represents the normal of the current material.
  11400. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  11401. *
  11402. * @tsl
  11403. * @type {Node<vec3>}
  11404. */
  11405. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  11406. /**
  11407. * TSL object that represents the clearcoat of the current material.
  11408. * The value is composed via `clearcoat` * `clearcoatMap.r`
  11409. *
  11410. * @tsl
  11411. * @type {Node<float>}
  11412. */
  11413. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  11414. /**
  11415. * TSL object that represents the clearcoat roughness of the current material.
  11416. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  11417. *
  11418. * @tsl
  11419. * @type {Node<float>}
  11420. */
  11421. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  11422. /**
  11423. * TSL object that represents the clearcoat normal of the current material.
  11424. * The value will be either `clearcoatNormalMap` or `normalView`.
  11425. *
  11426. * @tsl
  11427. * @type {Node<vec3>}
  11428. */
  11429. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  11430. /**
  11431. * TSL object that represents the rotation of the current sprite material.
  11432. *
  11433. * @tsl
  11434. * @type {Node<float>}
  11435. */
  11436. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  11437. /**
  11438. * TSL object that represents the sheen color of the current material.
  11439. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  11440. *
  11441. * @tsl
  11442. * @type {Node<vec3>}
  11443. */
  11444. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  11445. /**
  11446. * TSL object that represents the sheen roughness of the current material.
  11447. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  11448. *
  11449. * @tsl
  11450. * @type {Node<float>}
  11451. */
  11452. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  11453. /**
  11454. * TSL object that represents the anisotropy of the current material.
  11455. *
  11456. * @tsl
  11457. * @type {Node<vec2>}
  11458. */
  11459. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  11460. /**
  11461. * TSL object that represents the iridescence of the current material.
  11462. *
  11463. * @tsl
  11464. * @type {Node<float>}
  11465. */
  11466. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  11467. /**
  11468. * TSL object that represents the iridescence IOR of the current material.
  11469. *
  11470. * @tsl
  11471. * @type {Node<float>}
  11472. */
  11473. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  11474. /**
  11475. * TSL object that represents the iridescence thickness of the current material.
  11476. *
  11477. * @tsl
  11478. * @type {Node<float>}
  11479. */
  11480. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  11481. /**
  11482. * TSL object that represents the transmission of the current material.
  11483. * The value is composed via `transmission` * `transmissionMap.r`.
  11484. *
  11485. * @tsl
  11486. * @type {Node<float>}
  11487. */
  11488. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  11489. /**
  11490. * TSL object that represents the thickness of the current material.
  11491. * The value is composed via `thickness` * `thicknessMap.g`.
  11492. *
  11493. * @tsl
  11494. * @type {Node<float>}
  11495. */
  11496. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  11497. /**
  11498. * TSL object that represents the IOR of the current material.
  11499. *
  11500. * @tsl
  11501. * @type {Node<float>}
  11502. */
  11503. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  11504. /**
  11505. * TSL object that represents the attenuation distance of the current material.
  11506. *
  11507. * @tsl
  11508. * @type {Node<float>}
  11509. */
  11510. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  11511. /**
  11512. * TSL object that represents the attenuation color of the current material.
  11513. *
  11514. * @tsl
  11515. * @type {Node<vec3>}
  11516. */
  11517. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  11518. /**
  11519. * TSL object that represents the scale of the current dashed line material.
  11520. *
  11521. * @tsl
  11522. * @type {Node<float>}
  11523. */
  11524. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  11525. /**
  11526. * TSL object that represents the dash size of the current dashed line material.
  11527. *
  11528. * @tsl
  11529. * @type {Node<float>}
  11530. */
  11531. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  11532. /**
  11533. * TSL object that represents the gap size of the current dashed line material.
  11534. *
  11535. * @tsl
  11536. * @type {Node<float>}
  11537. */
  11538. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  11539. /**
  11540. * TSL object that represents the line width of the current line material.
  11541. *
  11542. * @tsl
  11543. * @type {Node<float>}
  11544. */
  11545. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  11546. /**
  11547. * TSL object that represents the dash offset of the current line material.
  11548. *
  11549. * @tsl
  11550. * @type {Node<float>}
  11551. */
  11552. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  11553. /**
  11554. * TSL object that represents the point size of the current points material.
  11555. *
  11556. * @tsl
  11557. * @type {Node<float>}
  11558. */
  11559. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  11560. /**
  11561. * TSL object that represents the dispersion of the current material.
  11562. *
  11563. * @tsl
  11564. * @type {Node<float>}
  11565. */
  11566. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11567. /**
  11568. * TSL object that represents the light map of the current material.
  11569. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11570. *
  11571. * @tsl
  11572. * @type {Node<vec3>}
  11573. */
  11574. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11575. /**
  11576. * TSL object that represents the ambient occlusion map of the current material.
  11577. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11578. *
  11579. * @tsl
  11580. * @type {Node<float>}
  11581. */
  11582. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11583. /**
  11584. * TSL object that represents the anisotropy vector of the current material.
  11585. *
  11586. * @tsl
  11587. * @type {Node<vec2>}
  11588. */
  11589. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11590. return frame.material;
  11591. } ).onRenderUpdate( function ( { material } ) {
  11592. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11593. } );
  11594. /**
  11595. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11596. *
  11597. * @tsl
  11598. * @type {VaryingNode<vec4>}
  11599. */
  11600. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11601. return builder.context.setupModelViewProjection();
  11602. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11603. /**
  11604. * This class enables element access on instances of {@link StorageBufferNode}.
  11605. * In most cases, it is indirectly used when accessing elements with the
  11606. * {@link StorageBufferNode#element} method.
  11607. *
  11608. * ```js
  11609. * const position = positionStorage.element( instanceIndex );
  11610. * ```
  11611. *
  11612. * @augments ArrayElementNode
  11613. */
  11614. class StorageArrayElementNode extends ArrayElementNode {
  11615. static get type() {
  11616. return 'StorageArrayElementNode';
  11617. }
  11618. /**
  11619. * Constructs storage buffer element node.
  11620. *
  11621. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11622. * @param {Node} indexNode - The index node that defines the element access.
  11623. */
  11624. constructor( storageBufferNode, indexNode ) {
  11625. super( storageBufferNode, indexNode );
  11626. /**
  11627. * This flag can be used for type testing.
  11628. *
  11629. * @type {boolean}
  11630. * @readonly
  11631. * @default true
  11632. */
  11633. this.isStorageArrayElementNode = true;
  11634. }
  11635. /**
  11636. * The storage buffer node.
  11637. *
  11638. * @param {Node} value
  11639. * @type {StorageBufferNode}
  11640. */
  11641. set storageBufferNode( value ) {
  11642. this.node = value;
  11643. }
  11644. get storageBufferNode() {
  11645. return this.node;
  11646. }
  11647. getMemberType( builder, name ) {
  11648. const structTypeNode = this.storageBufferNode.structTypeNode;
  11649. if ( structTypeNode ) {
  11650. return structTypeNode.getMemberType( builder, name );
  11651. }
  11652. return 'void';
  11653. }
  11654. setup( builder ) {
  11655. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11656. if ( this.node.isPBO === true ) {
  11657. builder.setupPBO( this.node );
  11658. }
  11659. }
  11660. return super.setup( builder );
  11661. }
  11662. generate( builder, output ) {
  11663. let snippet;
  11664. const isAssignContext = builder.context.assign;
  11665. //
  11666. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11667. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11668. snippet = builder.generatePBO( this );
  11669. } else {
  11670. snippet = this.node.build( builder );
  11671. }
  11672. } else {
  11673. snippet = super.generate( builder );
  11674. }
  11675. if ( isAssignContext !== true ) {
  11676. const type = this.getNodeType( builder );
  11677. snippet = builder.format( snippet, type, output );
  11678. }
  11679. return snippet;
  11680. }
  11681. }
  11682. /**
  11683. * TSL function for creating a storage element node.
  11684. *
  11685. * @tsl
  11686. * @function
  11687. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11688. * @param {Node} indexNode - The index node that defines the element access.
  11689. * @returns {StorageArrayElementNode}
  11690. */
  11691. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11692. /**
  11693. * This node is used in context of compute shaders and allows to define a
  11694. * storage buffer for data. A typical workflow is to create instances of
  11695. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11696. * setup up a compute shader that writes into the buffers and then convert
  11697. * the storage buffers to attribute nodes for rendering.
  11698. *
  11699. * ```js
  11700. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11701. *
  11702. * const computeInit = Fn( () => { // the compute shader
  11703. *
  11704. * const position = positionBuffer.element( instanceIndex );
  11705. *
  11706. * // compute position data
  11707. *
  11708. * position.x = 1;
  11709. * position.y = 1;
  11710. * position.z = 1;
  11711. *
  11712. * } )().compute( particleCount );
  11713. *
  11714. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11715. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11716. *
  11717. * renderer.computeAsync( computeInit );
  11718. *
  11719. * ```
  11720. *
  11721. * @augments BufferNode
  11722. */
  11723. class StorageBufferNode extends BufferNode {
  11724. static get type() {
  11725. return 'StorageBufferNode';
  11726. }
  11727. /**
  11728. * Constructs a new storage buffer node.
  11729. *
  11730. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11731. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11732. * @param {number} [bufferCount=0] - The buffer count.
  11733. */
  11734. constructor( value, bufferType = null, bufferCount = 0 ) {
  11735. let nodeType, structTypeNode = null;
  11736. if ( bufferType && bufferType.isStruct ) {
  11737. nodeType = 'struct';
  11738. structTypeNode = bufferType.layout;
  11739. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11740. bufferCount = value.count;
  11741. }
  11742. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11743. nodeType = getTypeFromLength( value.itemSize );
  11744. bufferCount = value.count;
  11745. } else {
  11746. nodeType = bufferType;
  11747. }
  11748. super( value, nodeType, bufferCount );
  11749. /**
  11750. * This flag can be used for type testing.
  11751. *
  11752. * @type {boolean}
  11753. * @readonly
  11754. * @default true
  11755. */
  11756. this.isStorageBufferNode = true;
  11757. /**
  11758. * The buffer struct type.
  11759. *
  11760. * @type {?StructTypeNode}
  11761. * @default null
  11762. */
  11763. this.structTypeNode = structTypeNode;
  11764. /**
  11765. * The access type of the texture node.
  11766. *
  11767. * @type {string}
  11768. * @default 'readWrite'
  11769. */
  11770. this.access = NodeAccess.READ_WRITE;
  11771. /**
  11772. * Whether the node is atomic or not.
  11773. *
  11774. * @type {boolean}
  11775. * @default false
  11776. */
  11777. this.isAtomic = false;
  11778. /**
  11779. * Whether the node represents a PBO or not.
  11780. * Only relevant for WebGL.
  11781. *
  11782. * @type {boolean}
  11783. * @default false
  11784. */
  11785. this.isPBO = false;
  11786. /**
  11787. * A reference to the internal buffer attribute node.
  11788. *
  11789. * @private
  11790. * @type {?BufferAttributeNode}
  11791. * @default null
  11792. */
  11793. this._attribute = null;
  11794. /**
  11795. * A reference to the internal varying node.
  11796. *
  11797. * @private
  11798. * @type {?VaryingNode}
  11799. * @default null
  11800. */
  11801. this._varying = null;
  11802. /**
  11803. * `StorageBufferNode` sets this property to `true` by default.
  11804. *
  11805. * @type {boolean}
  11806. * @default true
  11807. */
  11808. this.global = true;
  11809. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11810. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11811. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11812. else value.isStorageBufferAttribute = true;
  11813. }
  11814. }
  11815. /**
  11816. * This method is overwritten since the buffer data might be shared
  11817. * and thus the hash should be shared as well.
  11818. *
  11819. * @param {NodeBuilder} builder - The current node builder.
  11820. * @return {string} The hash.
  11821. */
  11822. getHash( builder ) {
  11823. if ( this.bufferCount === 0 ) {
  11824. let bufferData = builder.globalCache.getData( this.value );
  11825. if ( bufferData === undefined ) {
  11826. bufferData = {
  11827. node: this
  11828. };
  11829. builder.globalCache.setData( this.value, bufferData );
  11830. }
  11831. return bufferData.node.uuid;
  11832. }
  11833. return this.uuid;
  11834. }
  11835. /**
  11836. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  11837. *
  11838. * @param {NodeBuilder} builder - The current node builder.
  11839. * @return {string} The input type.
  11840. */
  11841. getInputType( /*builder*/ ) {
  11842. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11843. }
  11844. /**
  11845. * Enables element access with the given index node.
  11846. *
  11847. * @param {IndexNode} indexNode - The index node.
  11848. * @return {StorageArrayElementNode} A node representing the element access.
  11849. */
  11850. element( indexNode ) {
  11851. return storageElement( this, indexNode );
  11852. }
  11853. /**
  11854. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  11855. *
  11856. * @param {boolean} value - The value so set.
  11857. * @return {StorageBufferNode} A reference to this node.
  11858. */
  11859. setPBO( value ) {
  11860. this.isPBO = value;
  11861. return this;
  11862. }
  11863. /**
  11864. * Returns the `isPBO` value.
  11865. *
  11866. * @return {boolean} Whether the node represents a PBO or not.
  11867. */
  11868. getPBO() {
  11869. return this.isPBO;
  11870. }
  11871. /**
  11872. * Defines the node access.
  11873. *
  11874. * @param {string} value - The node access.
  11875. * @return {StorageBufferNode} A reference to this node.
  11876. */
  11877. setAccess( value ) {
  11878. this.access = value;
  11879. return this;
  11880. }
  11881. /**
  11882. * Convenience method for configuring a read-only node access.
  11883. *
  11884. * @return {StorageBufferNode} A reference to this node.
  11885. */
  11886. toReadOnly() {
  11887. return this.setAccess( NodeAccess.READ_ONLY );
  11888. }
  11889. /**
  11890. * Defines whether the node is atomic or not.
  11891. *
  11892. * @param {boolean} value - The atomic flag.
  11893. * @return {StorageBufferNode} A reference to this node.
  11894. */
  11895. setAtomic( value ) {
  11896. this.isAtomic = value;
  11897. return this;
  11898. }
  11899. /**
  11900. * Convenience method for making this node atomic.
  11901. *
  11902. * @return {StorageBufferNode} A reference to this node.
  11903. */
  11904. toAtomic() {
  11905. return this.setAtomic( true );
  11906. }
  11907. /**
  11908. * Returns attribute data for this storage buffer node.
  11909. *
  11910. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  11911. */
  11912. getAttributeData() {
  11913. if ( this._attribute === null ) {
  11914. this._attribute = bufferAttribute( this.value );
  11915. this._varying = varying( this._attribute );
  11916. }
  11917. return {
  11918. attribute: this._attribute,
  11919. varying: this._varying
  11920. };
  11921. }
  11922. /**
  11923. * This method is overwritten since the node type from the availability of storage buffers
  11924. * and the attribute data.
  11925. *
  11926. * @param {NodeBuilder} builder - The current node builder.
  11927. * @return {string} The node type.
  11928. */
  11929. getNodeType( builder ) {
  11930. if ( this.structTypeNode !== null ) {
  11931. return this.structTypeNode.getNodeType( builder );
  11932. }
  11933. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11934. return super.getNodeType( builder );
  11935. }
  11936. const { attribute } = this.getAttributeData();
  11937. return attribute.getNodeType( builder );
  11938. }
  11939. /**
  11940. * Returns the type of a member of the struct.
  11941. *
  11942. * @param {NodeBuilder} builder - The current node builder.
  11943. * @param {string} name - The name of the member.
  11944. * @return {string} The type of the member.
  11945. */
  11946. getMemberType( builder, name ) {
  11947. if ( this.structTypeNode !== null ) {
  11948. return this.structTypeNode.getMemberType( builder, name );
  11949. }
  11950. return 'void';
  11951. }
  11952. /**
  11953. * Generates the code snippet of the storage buffer node.
  11954. *
  11955. * @param {NodeBuilder} builder - The current node builder.
  11956. * @return {string} The generated code snippet.
  11957. */
  11958. generate( builder ) {
  11959. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  11960. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11961. return super.generate( builder );
  11962. }
  11963. const { attribute, varying } = this.getAttributeData();
  11964. const output = varying.build( builder );
  11965. builder.registerTransform( output, attribute );
  11966. return output;
  11967. }
  11968. }
  11969. /**
  11970. * TSL function for creating a storage buffer node.
  11971. *
  11972. * @tsl
  11973. * @function
  11974. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11975. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  11976. * @param {number} [count=0] - The buffer count.
  11977. * @returns {StorageBufferNode}
  11978. */
  11979. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  11980. /**
  11981. * @tsl
  11982. * @function
  11983. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  11984. *
  11985. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11986. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  11987. * @param {number} count - The buffer count.
  11988. * @returns {StorageBufferNode}
  11989. */
  11990. const storageObject = ( value, type, count ) => { // @deprecated, r171
  11991. warn( 'TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  11992. return storage( value, type, count ).setPBO( true );
  11993. };
  11994. /**
  11995. * This class represents shader indices of different types. The following predefined node
  11996. * objects cover frequent use cases:
  11997. *
  11998. * - `vertexIndex`: The index of a vertex within a mesh.
  11999. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  12000. * - `drawIndex`: The index of a draw call.
  12001. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  12002. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  12003. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  12004. *
  12005. * @augments Node
  12006. */
  12007. class IndexNode extends Node {
  12008. static get type() {
  12009. return 'IndexNode';
  12010. }
  12011. /**
  12012. * Constructs a new index node.
  12013. *
  12014. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  12015. */
  12016. constructor( scope ) {
  12017. super( 'uint' );
  12018. /**
  12019. * The scope of the index node.
  12020. *
  12021. * @type {string}
  12022. */
  12023. this.scope = scope;
  12024. /**
  12025. * This flag can be used for type testing.
  12026. *
  12027. * @type {boolean}
  12028. * @readonly
  12029. * @default true
  12030. */
  12031. this.isIndexNode = true;
  12032. }
  12033. generate( builder ) {
  12034. const nodeType = this.getNodeType( builder );
  12035. const scope = this.scope;
  12036. let propertyName;
  12037. if ( scope === IndexNode.VERTEX ) {
  12038. propertyName = builder.getVertexIndex();
  12039. } else if ( scope === IndexNode.INSTANCE ) {
  12040. propertyName = builder.getInstanceIndex();
  12041. } else if ( scope === IndexNode.DRAW ) {
  12042. propertyName = builder.getDrawIndex();
  12043. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  12044. propertyName = builder.getInvocationLocalIndex();
  12045. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  12046. propertyName = builder.getInvocationSubgroupIndex();
  12047. } else if ( scope === IndexNode.SUBGROUP ) {
  12048. propertyName = builder.getSubgroupIndex();
  12049. } else {
  12050. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  12051. }
  12052. let output;
  12053. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  12054. output = propertyName;
  12055. } else {
  12056. const nodeVarying = varying( this );
  12057. output = nodeVarying.build( builder, nodeType );
  12058. }
  12059. return output;
  12060. }
  12061. }
  12062. IndexNode.VERTEX = 'vertex';
  12063. IndexNode.INSTANCE = 'instance';
  12064. IndexNode.SUBGROUP = 'subgroup';
  12065. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  12066. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  12067. IndexNode.DRAW = 'draw';
  12068. /**
  12069. * TSL object that represents the index of a vertex within a mesh.
  12070. *
  12071. * @tsl
  12072. * @type {IndexNode}
  12073. */
  12074. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  12075. /**
  12076. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  12077. *
  12078. * @tsl
  12079. * @type {IndexNode}
  12080. */
  12081. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  12082. /**
  12083. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  12084. *
  12085. * @tsl
  12086. * @type {IndexNode}
  12087. */
  12088. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  12089. /**
  12090. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  12091. *
  12092. * @tsl
  12093. * @type {IndexNode}
  12094. */
  12095. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  12096. /**
  12097. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  12098. *
  12099. * @tsl
  12100. * @type {IndexNode}
  12101. */
  12102. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  12103. /**
  12104. * TSL object that represents the index of a draw call.
  12105. *
  12106. * @tsl
  12107. * @type {IndexNode}
  12108. */
  12109. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  12110. /**
  12111. * This node implements the vertex shader logic which is required
  12112. * when rendering 3D objects via instancing. The code makes sure
  12113. * vertex positions, normals and colors can be modified via instanced
  12114. * data.
  12115. *
  12116. * @augments Node
  12117. */
  12118. class InstanceNode extends Node {
  12119. static get type() {
  12120. return 'InstanceNode';
  12121. }
  12122. /**
  12123. * Constructs a new instance node.
  12124. *
  12125. * @param {number} count - The number of instances.
  12126. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12127. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12128. */
  12129. constructor( count, instanceMatrix, instanceColor = null ) {
  12130. super( 'void' );
  12131. /**
  12132. * The number of instances.
  12133. *
  12134. * @type {number}
  12135. */
  12136. this.count = count;
  12137. /**
  12138. * Instanced buffer attribute representing the transformation of instances.
  12139. *
  12140. * @type {InstancedBufferAttribute}
  12141. */
  12142. this.instanceMatrix = instanceMatrix;
  12143. /**
  12144. * Instanced buffer attribute representing the color of instances.
  12145. *
  12146. * @type {InstancedBufferAttribute}
  12147. */
  12148. this.instanceColor = instanceColor;
  12149. /**
  12150. * The node that represents the instance matrix data.
  12151. *
  12152. * @type {?Node}
  12153. */
  12154. this.instanceMatrixNode = null;
  12155. /**
  12156. * The node that represents the instance color data.
  12157. *
  12158. * @type {?Node}
  12159. * @default null
  12160. */
  12161. this.instanceColorNode = null;
  12162. /**
  12163. * The update type is set to `frame` since an update
  12164. * of instanced buffer data must be checked per frame.
  12165. *
  12166. * @type {string}
  12167. * @default 'frame'
  12168. */
  12169. this.updateType = NodeUpdateType.FRAME;
  12170. /**
  12171. * A reference to a buffer that is used by `instanceMatrixNode`.
  12172. *
  12173. * @type {?InstancedInterleavedBuffer}
  12174. */
  12175. this.buffer = null;
  12176. /**
  12177. * A reference to a buffer that is used by `instanceColorNode`.
  12178. *
  12179. * @type {?InstancedBufferAttribute}
  12180. */
  12181. this.bufferColor = null;
  12182. }
  12183. /**
  12184. * Tracks whether the matrix data is provided via a storage buffer.
  12185. *
  12186. * @type {boolean}
  12187. */
  12188. get isStorageMatrix() {
  12189. const { instanceMatrix } = this;
  12190. return instanceMatrix && instanceMatrix.isStorageInstancedBufferAttribute === true;
  12191. }
  12192. /**
  12193. * Tracks whether the color data is provided via a storage buffer.
  12194. *
  12195. * @type {boolean}
  12196. */
  12197. get isStorageColor() {
  12198. const { instanceColor } = this;
  12199. return instanceColor && instanceColor.isStorageInstancedBufferAttribute === true;
  12200. }
  12201. /**
  12202. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12203. * to predefined node variables for accumulation. That follows the same patterns
  12204. * like with morph and skinning nodes.
  12205. *
  12206. * @param {NodeBuilder} builder - The current node builder.
  12207. */
  12208. setup( builder ) {
  12209. const { instanceMatrix, instanceColor, isStorageMatrix, isStorageColor } = this;
  12210. const { count } = instanceMatrix;
  12211. let { instanceMatrixNode, instanceColorNode } = this;
  12212. if ( instanceMatrixNode === null ) {
  12213. if ( isStorageMatrix ) {
  12214. instanceMatrixNode = storage( instanceMatrix, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12215. } else {
  12216. // Both backends have ~64kb UBO limit; fallback to attributes above 1000 matrices.
  12217. if ( count <= 1000 ) {
  12218. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12219. } else {
  12220. const interleaved = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  12221. this.buffer = interleaved;
  12222. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12223. const instanceBuffers = [
  12224. bufferFn( interleaved, 'vec4', 16, 0 ),
  12225. bufferFn( interleaved, 'vec4', 16, 4 ),
  12226. bufferFn( interleaved, 'vec4', 16, 8 ),
  12227. bufferFn( interleaved, 'vec4', 16, 12 )
  12228. ];
  12229. instanceMatrixNode = mat4( ...instanceBuffers );
  12230. }
  12231. }
  12232. this.instanceMatrixNode = instanceMatrixNode;
  12233. }
  12234. if ( instanceColor && instanceColorNode === null ) {
  12235. if ( isStorageColor ) {
  12236. instanceColorNode = storage( instanceColor, 'vec3', Math.max( instanceColor.count, 1 ) ).element( instanceIndex );
  12237. } else {
  12238. const bufferAttribute = new InstancedBufferAttribute( instanceColor.array, 3 );
  12239. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12240. this.bufferColor = bufferAttribute;
  12241. instanceColorNode = vec3( bufferFn( bufferAttribute, 'vec3', 3, 0 ) );
  12242. }
  12243. this.instanceColorNode = instanceColorNode;
  12244. }
  12245. // POSITION
  12246. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  12247. positionLocal.assign( instancePosition );
  12248. // NORMAL
  12249. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12250. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  12251. // ASSIGNS
  12252. normalLocal.assign( instanceNormal );
  12253. }
  12254. // COLOR
  12255. if ( this.instanceColorNode !== null ) {
  12256. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  12257. }
  12258. }
  12259. /**
  12260. * Checks if the internal buffers require an update.
  12261. *
  12262. * @param {NodeFrame} frame - The current node frame.
  12263. */
  12264. update( /*frame*/ ) {
  12265. if ( this.buffer !== null && this.isStorageMatrix !== true ) {
  12266. this.buffer.clearUpdateRanges();
  12267. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  12268. // update version if necessary
  12269. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMatrix.version !== this.buffer.version ) {
  12270. this.buffer.version = this.instanceMatrix.version;
  12271. }
  12272. }
  12273. if ( this.instanceColor && this.bufferColor !== null && this.isStorageColor !== true ) {
  12274. this.bufferColor.clearUpdateRanges();
  12275. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  12276. if ( this.instanceColor.usage !== DynamicDrawUsage && this.instanceColor.version !== this.bufferColor.version ) {
  12277. this.bufferColor.version = this.instanceColor.version;
  12278. }
  12279. }
  12280. }
  12281. }
  12282. /**
  12283. * TSL function for creating an instance node.
  12284. *
  12285. * @tsl
  12286. * @function
  12287. * @param {number} count - The number of instances.
  12288. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12289. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12290. * @returns {InstanceNode}
  12291. */
  12292. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  12293. /**
  12294. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  12295. * It allows an easier setup of the instance node.
  12296. *
  12297. * @augments InstanceNode
  12298. */
  12299. class InstancedMeshNode extends InstanceNode {
  12300. static get type() {
  12301. return 'InstancedMeshNode';
  12302. }
  12303. /**
  12304. * Constructs a new instanced mesh node.
  12305. *
  12306. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  12307. */
  12308. constructor( instancedMesh ) {
  12309. const { count, instanceMatrix, instanceColor } = instancedMesh;
  12310. super( count, instanceMatrix, instanceColor );
  12311. /**
  12312. * A reference to the instanced mesh.
  12313. *
  12314. * @type {InstancedMesh}
  12315. */
  12316. this.instancedMesh = instancedMesh;
  12317. }
  12318. }
  12319. /**
  12320. * TSL function for creating an instanced mesh node.
  12321. *
  12322. * @tsl
  12323. * @function
  12324. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  12325. * @returns {InstancedMeshNode}
  12326. */
  12327. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  12328. /**
  12329. * This node implements the vertex shader logic which is required
  12330. * when rendering 3D objects via batching. `BatchNode` must be used
  12331. * with instances of {@link BatchedMesh}.
  12332. *
  12333. * @augments Node
  12334. */
  12335. class BatchNode extends Node {
  12336. static get type() {
  12337. return 'BatchNode';
  12338. }
  12339. /**
  12340. * Constructs a new batch node.
  12341. *
  12342. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12343. */
  12344. constructor( batchMesh ) {
  12345. super( 'void' );
  12346. /**
  12347. * A reference to batched mesh.
  12348. *
  12349. * @type {BatchedMesh}
  12350. */
  12351. this.batchMesh = batchMesh;
  12352. /**
  12353. * The batching index node.
  12354. *
  12355. * @type {?IndexNode}
  12356. * @default null
  12357. */
  12358. this.batchingIdNode = null;
  12359. }
  12360. /**
  12361. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12362. * to predefined node variables for accumulation. That follows the same patterns
  12363. * like with morph and skinning nodes.
  12364. *
  12365. * @param {NodeBuilder} builder - The current node builder.
  12366. */
  12367. setup( builder ) {
  12368. if ( this.batchingIdNode === null ) {
  12369. if ( builder.getDrawIndex() === null ) {
  12370. this.batchingIdNode = instanceIndex;
  12371. } else {
  12372. this.batchingIdNode = drawIndex;
  12373. }
  12374. }
  12375. const getIndirectIndex = Fn( ( [ id ] ) => {
  12376. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x ).toConst();
  12377. const x = int( id ).mod( size ).toConst();
  12378. const y = int( id ).div( size ).toConst();
  12379. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  12380. } ).setLayout( {
  12381. name: 'getIndirectIndex',
  12382. type: 'uint',
  12383. inputs: [
  12384. { name: 'id', type: 'int' }
  12385. ]
  12386. } );
  12387. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  12388. const matricesTexture = this.batchMesh._matricesTexture;
  12389. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x ).toConst();
  12390. const j = float( indirectId ).mul( 4 ).toInt().toConst();
  12391. const x = j.mod( size ).toConst();
  12392. const y = j.div( size ).toConst();
  12393. const batchingMatrix = mat4(
  12394. textureLoad( matricesTexture, ivec2( x, y ) ),
  12395. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  12396. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  12397. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  12398. );
  12399. const colorsTexture = this.batchMesh._colorsTexture;
  12400. if ( colorsTexture !== null ) {
  12401. const getBatchingColor = Fn( ( [ id ] ) => {
  12402. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x ).toConst();
  12403. const j = id;
  12404. const x = j.mod( size ).toConst();
  12405. const y = j.div( size ).toConst();
  12406. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  12407. } ).setLayout( {
  12408. name: 'getBatchingColor',
  12409. type: 'vec3',
  12410. inputs: [
  12411. { name: 'id', type: 'int' }
  12412. ]
  12413. } );
  12414. const color = getBatchingColor( indirectId );
  12415. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  12416. }
  12417. const bm = mat3( batchingMatrix );
  12418. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  12419. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  12420. const batchingNormal = bm.mul( transformedNormal ).xyz;
  12421. normalLocal.assign( batchingNormal );
  12422. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12423. tangentLocal.mulAssign( bm );
  12424. }
  12425. }
  12426. }
  12427. /**
  12428. * TSL function for creating a batch node.
  12429. *
  12430. * @tsl
  12431. * @function
  12432. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12433. * @returns {BatchNode}
  12434. */
  12435. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  12436. const _frameId = new WeakMap();
  12437. /**
  12438. * This node implements the vertex transformation shader logic which is required
  12439. * for skinning/skeletal animation.
  12440. *
  12441. * @augments Node
  12442. */
  12443. class SkinningNode extends Node {
  12444. static get type() {
  12445. return 'SkinningNode';
  12446. }
  12447. /**
  12448. * Constructs a new skinning node.
  12449. *
  12450. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12451. */
  12452. constructor( skinnedMesh ) {
  12453. super( 'void' );
  12454. /**
  12455. * The skinned mesh.
  12456. *
  12457. * @type {SkinnedMesh}
  12458. */
  12459. this.skinnedMesh = skinnedMesh;
  12460. /**
  12461. * The update type overwritten since skinning nodes are updated per object.
  12462. *
  12463. * @type {string}
  12464. */
  12465. this.updateType = NodeUpdateType.OBJECT;
  12466. //
  12467. /**
  12468. * The skin index attribute.
  12469. *
  12470. * @type {AttributeNode}
  12471. */
  12472. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  12473. /**
  12474. * The skin weight attribute.
  12475. *
  12476. * @type {AttributeNode}
  12477. */
  12478. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  12479. /**
  12480. * The bind matrix node.
  12481. *
  12482. * @type {Node<mat4>}
  12483. */
  12484. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  12485. /**
  12486. * The bind matrix inverse node.
  12487. *
  12488. * @type {Node<mat4>}
  12489. */
  12490. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  12491. /**
  12492. * The bind matrices as a uniform buffer node.
  12493. *
  12494. * @type {Node}
  12495. */
  12496. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12497. /**
  12498. * The current vertex position in local space.
  12499. *
  12500. * @type {Node<vec3>}
  12501. */
  12502. this.positionNode = positionLocal;
  12503. /**
  12504. * The result of vertex position in local space.
  12505. *
  12506. * @type {Node<vec3>}
  12507. */
  12508. this.toPositionNode = positionLocal;
  12509. /**
  12510. * The previous bind matrices as a uniform buffer node.
  12511. * Required for computing motion vectors.
  12512. *
  12513. * @type {?Node}
  12514. * @default null
  12515. */
  12516. this.previousBoneMatricesNode = null;
  12517. }
  12518. /**
  12519. * Transforms the given vertex position via skinning.
  12520. *
  12521. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12522. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  12523. * @return {Node<vec3>} The transformed vertex position.
  12524. */
  12525. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  12526. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12527. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12528. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12529. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12530. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12531. // POSITION
  12532. const skinVertex = bindMatrixNode.mul( position );
  12533. const skinned = add(
  12534. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  12535. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  12536. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  12537. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  12538. );
  12539. return bindMatrixInverseNode.mul( skinned ).xyz;
  12540. }
  12541. /**
  12542. * Transforms the given vertex normal via skinning.
  12543. *
  12544. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12545. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  12546. * @return {Node<vec3>} The transformed vertex normal.
  12547. */
  12548. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  12549. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12550. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12551. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12552. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12553. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12554. // NORMAL
  12555. let skinMatrix = add(
  12556. skinWeightNode.x.mul( boneMatX ),
  12557. skinWeightNode.y.mul( boneMatY ),
  12558. skinWeightNode.z.mul( boneMatZ ),
  12559. skinWeightNode.w.mul( boneMatW )
  12560. );
  12561. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  12562. return skinMatrix.transformDirection( normal ).xyz;
  12563. }
  12564. /**
  12565. * Computes the transformed/skinned vertex position of the previous frame.
  12566. *
  12567. * @param {NodeBuilder} builder - The current node builder.
  12568. * @return {Node<vec3>} The skinned position from the previous frame.
  12569. */
  12570. getPreviousSkinnedPosition( builder ) {
  12571. const skinnedMesh = builder.object;
  12572. if ( this.previousBoneMatricesNode === null ) {
  12573. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  12574. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12575. }
  12576. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  12577. }
  12578. /**
  12579. * Returns `true` if bone matrices from the previous frame are required. Relevant
  12580. * when computing motion vectors with {@link VelocityNode}.
  12581. *
  12582. * @param {NodeBuilder} builder - The current node builder.
  12583. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  12584. */
  12585. needsPreviousBoneMatrices( builder ) {
  12586. const mrt = builder.renderer.getMRT();
  12587. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  12588. }
  12589. /**
  12590. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  12591. *
  12592. * @param {NodeBuilder} builder - The current node builder.
  12593. * @return {Node<vec3>} The transformed vertex position.
  12594. */
  12595. setup( builder ) {
  12596. if ( this.needsPreviousBoneMatrices( builder ) ) {
  12597. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  12598. }
  12599. const skinPosition = this.getSkinnedPosition();
  12600. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12601. //
  12602. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12603. const skinNormal = this.getSkinnedNormal();
  12604. normalLocal.assign( skinNormal );
  12605. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12606. tangentLocal.assign( skinNormal );
  12607. }
  12608. }
  12609. return skinPosition;
  12610. }
  12611. /**
  12612. * Generates the code snippet of the skinning node.
  12613. *
  12614. * @param {NodeBuilder} builder - The current node builder.
  12615. * @param {string} output - The current output.
  12616. * @return {string} The generated code snippet.
  12617. */
  12618. generate( builder, output ) {
  12619. if ( output !== 'void' ) {
  12620. return super.generate( builder, output );
  12621. }
  12622. }
  12623. /**
  12624. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12625. *
  12626. * @param {NodeFrame} frame - The current node frame.
  12627. */
  12628. update( frame ) {
  12629. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12630. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12631. _frameId.set( skeleton, frame.frameId );
  12632. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12633. skeleton.update();
  12634. }
  12635. }
  12636. /**
  12637. * TSL function for creating a skinning node.
  12638. *
  12639. * @tsl
  12640. * @function
  12641. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12642. * @returns {SkinningNode}
  12643. */
  12644. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  12645. /**
  12646. * TSL function for computing skinning.
  12647. *
  12648. * @tsl
  12649. * @function
  12650. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12651. * @param {Node<vec3>} [toPosition=null] - The target position.
  12652. * @returns {SkinningNode}
  12653. */
  12654. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12655. const node = new SkinningNode( skinnedMesh );
  12656. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12657. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12658. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12659. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12660. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12661. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12662. node.toPositionNode = toPosition;
  12663. return nodeObject( node );
  12664. };
  12665. /**
  12666. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12667. * ```js
  12668. * Loop( count, ( { i } ) => {
  12669. *
  12670. * } );
  12671. * ```
  12672. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12673. * ```js
  12674. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12675. *
  12676. * } );
  12677. *```
  12678. * Nested loops can be defined in a compacted form:
  12679. * ```js
  12680. * Loop( 10, 5, ( { i, j } ) => {
  12681. *
  12682. * } );
  12683. * ```
  12684. * Loops that should run backwards can be defined like so:
  12685. * ```js
  12686. * Loop( { start: 10 }, () => {} );
  12687. * ```
  12688. * It is possible to execute with boolean values, similar to the `while` syntax.
  12689. * ```js
  12690. * const value = float( 0 ).toVar();
  12691. *
  12692. * Loop( value.lessThan( 10 ), () => {
  12693. *
  12694. * value.addAssign( 1 );
  12695. *
  12696. * } );
  12697. * ```
  12698. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  12699. * @augments Node
  12700. */
  12701. class LoopNode extends Node {
  12702. static get type() {
  12703. return 'LoopNode';
  12704. }
  12705. /**
  12706. * Constructs a new loop node.
  12707. *
  12708. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  12709. */
  12710. constructor( params = [] ) {
  12711. super( 'void' );
  12712. this.params = params;
  12713. }
  12714. /**
  12715. * Returns a loop variable name based on an index. The pattern is
  12716. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  12717. *
  12718. * @param {number} index - The index.
  12719. * @return {string} The loop variable name.
  12720. */
  12721. getVarName( index ) {
  12722. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  12723. }
  12724. /**
  12725. * Returns properties about this node.
  12726. *
  12727. * @param {NodeBuilder} builder - The current node builder.
  12728. * @return {Object} The node properties.
  12729. */
  12730. getProperties( builder ) {
  12731. const properties = builder.getNodeProperties( this );
  12732. if ( properties.stackNode !== undefined ) return properties;
  12733. //
  12734. const inputs = {};
  12735. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12736. const param = this.params[ i ];
  12737. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12738. const type = ( param.isNode !== true && param.type ) || 'int';
  12739. inputs[ name ] = expression( name, type );
  12740. }
  12741. const stack = builder.addStack();
  12742. const fnCall = this.params[ this.params.length - 1 ]( inputs );
  12743. properties.returnsNode = fnCall.context( { nodeLoop: fnCall } );
  12744. properties.stackNode = stack;
  12745. const baseParam = this.params[ 0 ];
  12746. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12747. const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs );
  12748. properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } );
  12749. }
  12750. builder.removeStack();
  12751. return properties;
  12752. }
  12753. setup( builder ) {
  12754. // setup properties
  12755. this.getProperties( builder );
  12756. if ( builder.fnCall ) {
  12757. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  12758. shaderNodeData.hasLoop = true;
  12759. }
  12760. }
  12761. generate( builder ) {
  12762. const properties = this.getProperties( builder );
  12763. const params = this.params;
  12764. const stackNode = properties.stackNode;
  12765. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12766. const param = params[ i ];
  12767. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12768. if ( param.isNode ) {
  12769. if ( param.getNodeType( builder ) === 'bool' ) {
  12770. isWhile = true;
  12771. type = 'bool';
  12772. end = param.build( builder, type );
  12773. } else {
  12774. type = 'int';
  12775. name = this.getVarName( i );
  12776. start = '0';
  12777. end = param.build( builder, type );
  12778. condition = '<';
  12779. }
  12780. } else {
  12781. type = param.type || 'int';
  12782. name = param.name || this.getVarName( i );
  12783. start = param.start;
  12784. end = param.end;
  12785. condition = param.condition;
  12786. update = param.update;
  12787. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12788. else if ( start && start.isNode ) start = start.build( builder, type );
  12789. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12790. else if ( end && end.isNode ) end = end.build( builder, type );
  12791. if ( start !== undefined && end === undefined ) {
  12792. start = start + ' - 1';
  12793. end = '0';
  12794. condition = '>=';
  12795. } else if ( end !== undefined && start === undefined ) {
  12796. start = '0';
  12797. condition = '<';
  12798. }
  12799. if ( condition === undefined ) {
  12800. if ( Number( start ) > Number( end ) ) {
  12801. condition = '>=';
  12802. } else {
  12803. condition = '<';
  12804. }
  12805. }
  12806. }
  12807. let loopSnippet;
  12808. if ( isWhile ) {
  12809. loopSnippet = `while ( ${ end } )`;
  12810. } else {
  12811. const internalParam = { start, end};
  12812. //
  12813. const startSnippet = internalParam.start;
  12814. const endSnippet = internalParam.end;
  12815. let updateSnippet;
  12816. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12817. if ( update !== undefined && update !== null ) {
  12818. switch ( typeof update ) {
  12819. case 'function':
  12820. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12821. const snippet = flow.code.replace( /\t|;/g, '' );
  12822. updateSnippet = snippet;
  12823. break;
  12824. case 'number':
  12825. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12826. break;
  12827. case 'string':
  12828. updateSnippet = name + ' ' + update;
  12829. break;
  12830. default:
  12831. if ( update.isNode ) {
  12832. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12833. } else {
  12834. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12835. updateSnippet = 'break /* invalid update */';
  12836. }
  12837. }
  12838. } else {
  12839. if ( type === 'int' || type === 'uint' ) {
  12840. update = condition.includes( '<' ) ? '++' : '--';
  12841. } else {
  12842. update = deltaOperator() + ' 1.';
  12843. }
  12844. updateSnippet = name + ' ' + update;
  12845. }
  12846. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12847. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12848. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12849. }
  12850. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12851. }
  12852. const stackSnippet = stackNode.build( builder, 'void' );
  12853. properties.returnsNode.build( builder, 'void' );
  12854. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12855. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12856. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12857. }
  12858. builder.addFlowTab();
  12859. }
  12860. }
  12861. /**
  12862. * TSL function for creating a loop node.
  12863. *
  12864. * @tsl
  12865. * @function
  12866. * @param {...any} params - A list of parameters.
  12867. * @returns {LoopNode}
  12868. */
  12869. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  12870. /**
  12871. * TSL function for creating a `Continue()` expression.
  12872. *
  12873. * @tsl
  12874. * @function
  12875. * @returns {ExpressionNode}
  12876. */
  12877. const Continue = () => expression( 'continue' ).toStack();
  12878. /**
  12879. * TSL function for creating a `Break()` expression.
  12880. *
  12881. * @tsl
  12882. * @function
  12883. * @returns {ExpressionNode}
  12884. */
  12885. const Break = () => expression( 'break' ).toStack();
  12886. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12887. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12888. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12889. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12890. const y = texelIndex.div( width );
  12891. const x = texelIndex.sub( y.mul( width ) );
  12892. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12893. return bufferAttrib.mul( influence );
  12894. } );
  12895. function getEntry( geometry ) {
  12896. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12897. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12898. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12899. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12900. // into an array of data textures. Each layer represents a single morph target.
  12901. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12902. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12903. let entry = _morphTextures.get( geometry );
  12904. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12905. if ( entry !== undefined ) entry.texture.dispose();
  12906. const morphTargets = geometry.morphAttributes.position || [];
  12907. const morphNormals = geometry.morphAttributes.normal || [];
  12908. const morphColors = geometry.morphAttributes.color || [];
  12909. let vertexDataCount = 0;
  12910. if ( hasMorphPosition === true ) vertexDataCount = 1;
  12911. if ( hasMorphNormals === true ) vertexDataCount = 2;
  12912. if ( hasMorphColors === true ) vertexDataCount = 3;
  12913. let width = geometry.attributes.position.count * vertexDataCount;
  12914. let height = 1;
  12915. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  12916. if ( width > maxTextureSize ) {
  12917. height = Math.ceil( width / maxTextureSize );
  12918. width = maxTextureSize;
  12919. }
  12920. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  12921. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  12922. bufferTexture.type = FloatType;
  12923. bufferTexture.needsUpdate = true;
  12924. // fill buffer
  12925. const vertexDataStride = vertexDataCount * 4;
  12926. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  12927. const morphTarget = morphTargets[ i ];
  12928. const morphNormal = morphNormals[ i ];
  12929. const morphColor = morphColors[ i ];
  12930. const offset = width * height * 4 * i;
  12931. for ( let j = 0; j < morphTarget.count; j ++ ) {
  12932. const stride = j * vertexDataStride;
  12933. if ( hasMorphPosition === true ) {
  12934. _morphVec4.fromBufferAttribute( morphTarget, j );
  12935. buffer[ offset + stride + 0 ] = _morphVec4.x;
  12936. buffer[ offset + stride + 1 ] = _morphVec4.y;
  12937. buffer[ offset + stride + 2 ] = _morphVec4.z;
  12938. buffer[ offset + stride + 3 ] = 0;
  12939. }
  12940. if ( hasMorphNormals === true ) {
  12941. _morphVec4.fromBufferAttribute( morphNormal, j );
  12942. buffer[ offset + stride + 4 ] = _morphVec4.x;
  12943. buffer[ offset + stride + 5 ] = _morphVec4.y;
  12944. buffer[ offset + stride + 6 ] = _morphVec4.z;
  12945. buffer[ offset + stride + 7 ] = 0;
  12946. }
  12947. if ( hasMorphColors === true ) {
  12948. _morphVec4.fromBufferAttribute( morphColor, j );
  12949. buffer[ offset + stride + 8 ] = _morphVec4.x;
  12950. buffer[ offset + stride + 9 ] = _morphVec4.y;
  12951. buffer[ offset + stride + 10 ] = _morphVec4.z;
  12952. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  12953. }
  12954. }
  12955. }
  12956. entry = {
  12957. count: morphTargetsCount,
  12958. texture: bufferTexture,
  12959. stride: vertexDataCount,
  12960. size: new Vector2( width, height )
  12961. };
  12962. _morphTextures.set( geometry, entry );
  12963. function disposeTexture() {
  12964. bufferTexture.dispose();
  12965. _morphTextures.delete( geometry );
  12966. geometry.removeEventListener( 'dispose', disposeTexture );
  12967. }
  12968. geometry.addEventListener( 'dispose', disposeTexture );
  12969. }
  12970. return entry;
  12971. }
  12972. /**
  12973. * This node implements the vertex transformation shader logic which is required
  12974. * for morph target animation.
  12975. *
  12976. * @augments Node
  12977. */
  12978. class MorphNode extends Node {
  12979. static get type() {
  12980. return 'MorphNode';
  12981. }
  12982. /**
  12983. * Constructs a new morph node.
  12984. *
  12985. * @param {Mesh} mesh - The mesh holding the morph targets.
  12986. */
  12987. constructor( mesh ) {
  12988. super( 'void' );
  12989. /**
  12990. * The mesh holding the morph targets.
  12991. *
  12992. * @type {Mesh}
  12993. */
  12994. this.mesh = mesh;
  12995. /**
  12996. * A uniform node which represents the morph base influence value.
  12997. *
  12998. * @type {UniformNode<float>}
  12999. */
  13000. this.morphBaseInfluence = uniform( 1 );
  13001. /**
  13002. * The update type overwritten since morph nodes are updated per object.
  13003. *
  13004. * @type {string}
  13005. */
  13006. this.updateType = NodeUpdateType.OBJECT;
  13007. }
  13008. /**
  13009. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  13010. *
  13011. * @param {NodeBuilder} builder - The current node builder.
  13012. */
  13013. setup( builder ) {
  13014. const { geometry } = builder;
  13015. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13016. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  13017. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13018. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13019. // nodes
  13020. const { texture: bufferMap, stride, size } = getEntry( geometry );
  13021. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  13022. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  13023. const width = int( size.width );
  13024. Loop( morphTargetsCount, ( { i } ) => {
  13025. const influence = float( 0 ).toVar();
  13026. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  13027. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  13028. } else {
  13029. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  13030. }
  13031. If( influence.notEqual( 0 ), () => {
  13032. if ( hasMorphPosition === true ) {
  13033. positionLocal.addAssign( getMorph( {
  13034. bufferMap,
  13035. influence,
  13036. stride,
  13037. width,
  13038. depth: i,
  13039. offset: int( 0 )
  13040. } ) );
  13041. }
  13042. if ( hasMorphNormals === true ) {
  13043. normalLocal.addAssign( getMorph( {
  13044. bufferMap,
  13045. influence,
  13046. stride,
  13047. width,
  13048. depth: i,
  13049. offset: int( 1 )
  13050. } ) );
  13051. }
  13052. } );
  13053. } );
  13054. }
  13055. /**
  13056. * Updates the state of the morphed mesh by updating the base influence.
  13057. *
  13058. * @param {NodeFrame} frame - The current node frame.
  13059. */
  13060. update( /*frame*/ ) {
  13061. const morphBaseInfluence = this.morphBaseInfluence;
  13062. if ( this.mesh.geometry.morphTargetsRelative ) {
  13063. morphBaseInfluence.value = 1;
  13064. } else {
  13065. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  13066. }
  13067. }
  13068. }
  13069. /**
  13070. * TSL function for creating a morph node.
  13071. *
  13072. * @tsl
  13073. * @function
  13074. * @param {Mesh} mesh - The mesh holding the morph targets.
  13075. * @returns {MorphNode}
  13076. */
  13077. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  13078. /**
  13079. * Base class for lighting nodes.
  13080. *
  13081. * @augments Node
  13082. */
  13083. class LightingNode extends Node {
  13084. static get type() {
  13085. return 'LightingNode';
  13086. }
  13087. /**
  13088. * Constructs a new lighting node.
  13089. */
  13090. constructor() {
  13091. super( 'vec3' );
  13092. /**
  13093. * This flag can be used for type testing.
  13094. *
  13095. * @type {boolean}
  13096. * @readonly
  13097. * @default true
  13098. */
  13099. this.isLightingNode = true;
  13100. }
  13101. }
  13102. /**
  13103. * A generic class that can be used by nodes which contribute
  13104. * ambient occlusion to the scene. E.g. an ambient occlusion map
  13105. * node can be used as input for this module. Used in {@link NodeMaterial}.
  13106. *
  13107. * @augments LightingNode
  13108. */
  13109. class AONode extends LightingNode {
  13110. static get type() {
  13111. return 'AONode';
  13112. }
  13113. /**
  13114. * Constructs a new AO node.
  13115. *
  13116. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  13117. */
  13118. constructor( aoNode = null ) {
  13119. super();
  13120. /**
  13121. * The ambient occlusion node.
  13122. *
  13123. * @type {?Node<float>}
  13124. * @default null
  13125. */
  13126. this.aoNode = aoNode;
  13127. }
  13128. setup( builder ) {
  13129. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  13130. }
  13131. }
  13132. /**
  13133. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  13134. * by adding lighting specific context data. It represents the runtime context of
  13135. * {@link LightsNode}.
  13136. *
  13137. * @augments ContextNode
  13138. */
  13139. class LightingContextNode extends ContextNode {
  13140. static get type() {
  13141. return 'LightingContextNode';
  13142. }
  13143. /**
  13144. * Constructs a new lighting context node.
  13145. *
  13146. * @param {LightsNode} lightsNode - The lights node.
  13147. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  13148. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  13149. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  13150. */
  13151. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  13152. super( lightsNode );
  13153. /**
  13154. * The current lighting model.
  13155. *
  13156. * @type {?LightingModel}
  13157. * @default null
  13158. */
  13159. this.lightingModel = lightingModel;
  13160. /**
  13161. * A backdrop node.
  13162. *
  13163. * @type {?Node<vec3>}
  13164. * @default null
  13165. */
  13166. this.backdropNode = backdropNode;
  13167. /**
  13168. * A backdrop alpha node.
  13169. *
  13170. * @type {?Node<float>}
  13171. * @default null
  13172. */
  13173. this.backdropAlphaNode = backdropAlphaNode;
  13174. this._value = null;
  13175. }
  13176. /**
  13177. * Returns a lighting context object.
  13178. *
  13179. * @return {{
  13180. * radiance: Node<vec3>,
  13181. * irradiance: Node<vec3>,
  13182. * iblIrradiance: Node<vec3>,
  13183. * ambientOcclusion: Node<float>,
  13184. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  13185. * backdrop: Node<vec3>,
  13186. * backdropAlpha: Node<float>
  13187. * }} The lighting context object.
  13188. */
  13189. getContext() {
  13190. const { backdropNode, backdropAlphaNode } = this;
  13191. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  13192. directSpecular = vec3().toVar( 'directSpecular' ),
  13193. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  13194. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  13195. const reflectedLight = {
  13196. directDiffuse,
  13197. directSpecular,
  13198. indirectDiffuse,
  13199. indirectSpecular
  13200. };
  13201. const context = {
  13202. radiance: vec3().toVar( 'radiance' ),
  13203. irradiance: vec3().toVar( 'irradiance' ),
  13204. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  13205. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  13206. reflectedLight,
  13207. backdrop: backdropNode,
  13208. backdropAlpha: backdropAlphaNode
  13209. };
  13210. return context;
  13211. }
  13212. setup( builder ) {
  13213. this.value = this._value || ( this._value = this.getContext() );
  13214. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  13215. return super.setup( builder );
  13216. }
  13217. }
  13218. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  13219. /**
  13220. * A generic class that can be used by nodes which contribute
  13221. * irradiance to the scene. E.g. a light map node can be used
  13222. * as input for this module. Used in {@link NodeMaterial}.
  13223. *
  13224. * @augments LightingNode
  13225. */
  13226. class IrradianceNode extends LightingNode {
  13227. static get type() {
  13228. return 'IrradianceNode';
  13229. }
  13230. /**
  13231. * Constructs a new irradiance node.
  13232. *
  13233. * @param {Node<vec3>} node - A node contributing irradiance.
  13234. */
  13235. constructor( node ) {
  13236. super();
  13237. /**
  13238. * A node contributing irradiance.
  13239. *
  13240. * @type {Node<vec3>}
  13241. */
  13242. this.node = node;
  13243. }
  13244. setup( builder ) {
  13245. builder.context.irradiance.addAssign( this.node );
  13246. }
  13247. }
  13248. const _size$5 = /*@__PURE__*/ new Vector2();
  13249. /**
  13250. * A special type of texture node which represents the data of the current viewport
  13251. * as a texture. The module extracts data from the current bound framebuffer with
  13252. * a copy operation so no extra render pass is required to produce the texture data
  13253. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13254. * variety of effects like refractive or transmissive materials.
  13255. *
  13256. * @augments TextureNode
  13257. */
  13258. class ViewportTextureNode extends TextureNode {
  13259. static get type() {
  13260. return 'ViewportTextureNode';
  13261. }
  13262. /**
  13263. * Constructs a new viewport texture node.
  13264. *
  13265. * @param {Node} [uvNode=screenUV] - The uv node.
  13266. * @param {?Node} [levelNode=null] - The level node.
  13267. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13268. */
  13269. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13270. let defaultFramebuffer = null;
  13271. if ( framebufferTexture === null ) {
  13272. defaultFramebuffer = new FramebufferTexture();
  13273. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13274. framebufferTexture = defaultFramebuffer;
  13275. } else {
  13276. defaultFramebuffer = framebufferTexture;
  13277. }
  13278. super( framebufferTexture, uvNode, levelNode );
  13279. /**
  13280. * Whether to generate mipmaps or not.
  13281. *
  13282. * @type {boolean}
  13283. * @default false
  13284. */
  13285. this.generateMipmaps = false;
  13286. /**
  13287. * The reference framebuffer texture. This is used to store the framebuffer texture
  13288. * for the current render target. If the render target changes, a new framebuffer texture
  13289. * is created automatically.
  13290. *
  13291. * @type {FramebufferTexture}
  13292. * @default null
  13293. */
  13294. this.defaultFramebuffer = defaultFramebuffer;
  13295. /**
  13296. * This flag can be used for type testing.
  13297. *
  13298. * @type {boolean}
  13299. * @readonly
  13300. * @default true
  13301. */
  13302. this.isOutputTextureNode = true;
  13303. /**
  13304. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  13305. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  13306. *
  13307. * @type {string}
  13308. * @default 'frame'
  13309. */
  13310. this.updateBeforeType = NodeUpdateType.FRAME;
  13311. /**
  13312. * The framebuffer texture for the current renderer context.
  13313. *
  13314. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13315. * @private
  13316. */
  13317. this._cacheTextures = new WeakMap();
  13318. }
  13319. /**
  13320. * This methods returns a texture for the given render target reference.
  13321. *
  13322. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13323. * for different render contexts.
  13324. *
  13325. * @param {?RenderTarget} [reference=null] - The render target reference.
  13326. * @return {Texture} The framebuffer texture.
  13327. */
  13328. getTextureForReference( reference = null ) {
  13329. let defaultFramebuffer;
  13330. let cacheTextures;
  13331. if ( this.referenceNode ) {
  13332. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13333. cacheTextures = this.referenceNode._cacheTextures;
  13334. } else {
  13335. defaultFramebuffer = this.defaultFramebuffer;
  13336. cacheTextures = this._cacheTextures;
  13337. }
  13338. if ( reference === null ) {
  13339. return defaultFramebuffer;
  13340. }
  13341. if ( cacheTextures.has( reference ) === false ) {
  13342. const framebufferTexture = defaultFramebuffer.clone();
  13343. cacheTextures.set( reference, framebufferTexture );
  13344. }
  13345. return cacheTextures.get( reference );
  13346. }
  13347. updateReference( frame ) {
  13348. const renderTarget = frame.renderer.getRenderTarget();
  13349. this.value = this.getTextureForReference( renderTarget );
  13350. return this.value;
  13351. }
  13352. updateBefore( frame ) {
  13353. const renderer = frame.renderer;
  13354. const renderTarget = renderer.getRenderTarget();
  13355. if ( renderTarget === null ) {
  13356. renderer.getDrawingBufferSize( _size$5 );
  13357. } else {
  13358. _size$5.set( renderTarget.width, renderTarget.height );
  13359. }
  13360. //
  13361. const framebufferTexture = this.getTextureForReference( renderTarget );
  13362. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  13363. framebufferTexture.image.width = _size$5.width;
  13364. framebufferTexture.image.height = _size$5.height;
  13365. framebufferTexture.needsUpdate = true;
  13366. }
  13367. //
  13368. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  13369. framebufferTexture.generateMipmaps = this.generateMipmaps;
  13370. renderer.copyFramebufferToTexture( framebufferTexture );
  13371. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  13372. }
  13373. clone() {
  13374. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  13375. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  13376. return viewportTextureNode;
  13377. }
  13378. }
  13379. /**
  13380. * TSL function for creating a viewport texture node.
  13381. *
  13382. * @tsl
  13383. * @function
  13384. * @param {?Node} [uvNode=screenUV] - The uv node.
  13385. * @param {?Node} [levelNode=null] - The level node.
  13386. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13387. * @returns {ViewportTextureNode}
  13388. */
  13389. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  13390. /**
  13391. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13392. *
  13393. * @tsl
  13394. * @function
  13395. * @param {?Node} [uvNode=screenUV] - The uv node.
  13396. * @param {?Node} [levelNode=null] - The level node.
  13397. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13398. * @returns {ViewportTextureNode}
  13399. */
  13400. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  13401. let _sharedDepthbuffer = null;
  13402. /**
  13403. * Represents the depth of the current viewport as a texture. This module
  13404. * can be used in combination with viewport texture to achieve effects
  13405. * that require depth evaluation.
  13406. *
  13407. * @augments ViewportTextureNode
  13408. */
  13409. class ViewportDepthTextureNode extends ViewportTextureNode {
  13410. static get type() {
  13411. return 'ViewportDepthTextureNode';
  13412. }
  13413. /**
  13414. * Constructs a new viewport depth texture node.
  13415. *
  13416. * @param {Node} [uvNode=screenUV] - The uv node.
  13417. * @param {?Node} [levelNode=null] - The level node.
  13418. */
  13419. constructor( uvNode = screenUV, levelNode = null ) {
  13420. if ( _sharedDepthbuffer === null ) {
  13421. _sharedDepthbuffer = new DepthTexture();
  13422. }
  13423. super( uvNode, levelNode, _sharedDepthbuffer );
  13424. }
  13425. /**
  13426. * Overwritten so the method always returns the unique shared
  13427. * depth texture.
  13428. *
  13429. * @return {DepthTexture} The shared depth texture.
  13430. */
  13431. getTextureForReference() {
  13432. return _sharedDepthbuffer;
  13433. }
  13434. }
  13435. /**
  13436. * TSL function for a viewport depth texture node.
  13437. *
  13438. * @tsl
  13439. * @function
  13440. * @param {?Node} [uvNode=screenUV] - The uv node.
  13441. * @param {?Node} [levelNode=null] - The level node.
  13442. * @returns {ViewportDepthTextureNode}
  13443. */
  13444. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  13445. /**
  13446. * This node offers a collection of features in context of the depth logic in the fragment shader.
  13447. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  13448. * fragment or for depth evaluation purposes.
  13449. *
  13450. * @augments Node
  13451. */
  13452. class ViewportDepthNode extends Node {
  13453. static get type() {
  13454. return 'ViewportDepthNode';
  13455. }
  13456. /**
  13457. * Constructs a new viewport depth node.
  13458. *
  13459. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  13460. * @param {?Node} [valueNode=null] - The value node.
  13461. */
  13462. constructor( scope, valueNode = null ) {
  13463. super( 'float' );
  13464. /**
  13465. * The node behaves differently depending on which scope is selected.
  13466. *
  13467. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  13468. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  13469. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  13470. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  13471. *
  13472. * @type {('depth'|'depthBase'|'linearDepth')}
  13473. */
  13474. this.scope = scope;
  13475. /**
  13476. * Can be used to define a custom depth value.
  13477. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  13478. *
  13479. * @type {?Node}
  13480. * @default null
  13481. */
  13482. this.valueNode = valueNode;
  13483. /**
  13484. * This flag can be used for type testing.
  13485. *
  13486. * @type {boolean}
  13487. * @readonly
  13488. * @default true
  13489. */
  13490. this.isViewportDepthNode = true;
  13491. }
  13492. generate( builder ) {
  13493. const { scope } = this;
  13494. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13495. return builder.getFragDepth();
  13496. }
  13497. return super.generate( builder );
  13498. }
  13499. setup( { camera } ) {
  13500. const { scope } = this;
  13501. const value = this.valueNode;
  13502. let node = null;
  13503. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13504. if ( value !== null ) {
  13505. node = depthBase().assign( value );
  13506. }
  13507. } else if ( scope === ViewportDepthNode.DEPTH ) {
  13508. if ( camera.isPerspectiveCamera ) {
  13509. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  13510. } else {
  13511. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13512. }
  13513. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  13514. if ( value !== null ) {
  13515. if ( camera.isPerspectiveCamera ) {
  13516. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  13517. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  13518. } else {
  13519. node = value;
  13520. }
  13521. } else {
  13522. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13523. }
  13524. }
  13525. return node;
  13526. }
  13527. }
  13528. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  13529. ViewportDepthNode.DEPTH = 'depth';
  13530. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  13531. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  13532. /**
  13533. * TSL function for converting a viewZ value to an orthographic depth value.
  13534. *
  13535. * @tsl
  13536. * @function
  13537. * @param {Node<float>} viewZ - The viewZ node.
  13538. * @param {Node<float>} near - The camera's near value.
  13539. * @param {Node<float>} far - The camera's far value.
  13540. * @returns {Node<float>}
  13541. */
  13542. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  13543. /**
  13544. * TSL function for converting an orthographic depth value to a viewZ value.
  13545. *
  13546. * @tsl
  13547. * @function
  13548. * @param {Node<float>} depth - The orthographic depth.
  13549. * @param {Node<float>} near - The camera's near value.
  13550. * @param {Node<float>} far - The camera's far value.
  13551. * @returns {Node<float>}
  13552. */
  13553. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  13554. /**
  13555. * TSL function for converting a viewZ value to a perspective depth value.
  13556. *
  13557. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  13558. *
  13559. * @tsl
  13560. * @function
  13561. * @param {Node<float>} viewZ - The viewZ node.
  13562. * @param {Node<float>} near - The camera's near value.
  13563. * @param {Node<float>} far - The camera's far value.
  13564. * @returns {Node<float>}
  13565. */
  13566. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  13567. /**
  13568. * TSL function for converting a perspective depth value to a viewZ value.
  13569. *
  13570. * @tsl
  13571. * @function
  13572. * @param {Node<float>} depth - The perspective depth.
  13573. * @param {Node<float>} near - The camera's near value.
  13574. * @param {Node<float>} far - The camera's far value.
  13575. * @returns {Node<float>}
  13576. */
  13577. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  13578. /**
  13579. * TSL function for converting a viewZ value to a logarithmic depth value.
  13580. *
  13581. * @tsl
  13582. * @function
  13583. * @param {Node<float>} viewZ - The viewZ node.
  13584. * @param {Node<float>} near - The camera's near value.
  13585. * @param {Node<float>} far - The camera's far value.
  13586. * @returns {Node<float>}
  13587. */
  13588. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  13589. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  13590. // The final logarithmic depth formula used here is adapted from one described in an
  13591. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  13592. // which was an improvement upon an earlier formula one described in an
  13593. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13594. // Ulrich's formula is the following:
  13595. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13596. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13597. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13598. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13599. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13600. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13601. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13602. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13603. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13604. // Outerra eventually made another improvement to their original "C-constant" variant,
  13605. // but it still does not incorporate the camera near plane (for this version,
  13606. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13607. // Here we make 4 changes to Ulrich's formula:
  13608. // 1. Clamp the camera near plane so we don't divide by 0.
  13609. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13610. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13611. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13612. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13613. // so we do the same here, hence the 'viewZ.negate()' call.
  13614. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13615. near = near.max( 1e-6 ).toVar();
  13616. const numerator = log2( viewZ.negate().div( near ) );
  13617. const denominator = log2( far.div( near ) );
  13618. return numerator.div( denominator );
  13619. };
  13620. /**
  13621. * TSL function for converting a logarithmic depth value to a viewZ value.
  13622. *
  13623. * @tsl
  13624. * @function
  13625. * @param {Node<float>} depth - The logarithmic depth.
  13626. * @param {Node<float>} near - The camera's near value.
  13627. * @param {Node<float>} far - The camera's far value.
  13628. * @returns {Node<float>}
  13629. */
  13630. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  13631. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13632. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13633. // a negative viewZ).
  13634. const exponent = depth.mul( log( far.div( near ) ) );
  13635. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13636. };
  13637. /**
  13638. * TSL function for defining a value for the current fragment's depth.
  13639. *
  13640. * @tsl
  13641. * @function
  13642. * @param {Node<float>} value - The depth value to set.
  13643. * @returns {ViewportDepthNode<float>}
  13644. */
  13645. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13646. /**
  13647. * TSL object that represents the depth value for the current fragment.
  13648. *
  13649. * @tsl
  13650. * @type {ViewportDepthNode}
  13651. */
  13652. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13653. /**
  13654. * TSL function for converting a perspective depth value to linear depth.
  13655. *
  13656. * @tsl
  13657. * @function
  13658. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13659. * @returns {ViewportDepthNode<float>}
  13660. */
  13661. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13662. /**
  13663. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13664. *
  13665. * @tsl
  13666. * @type {ViewportDepthNode}
  13667. */
  13668. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  13669. depth.assign = ( value ) => depthBase( value );
  13670. /**
  13671. * This node is used in {@link NodeMaterial} to setup the clipping
  13672. * which can happen hardware-accelerated (if supported) and optionally
  13673. * use alpha-to-coverage for anti-aliasing clipped edges.
  13674. *
  13675. * @augments Node
  13676. */
  13677. class ClippingNode extends Node {
  13678. static get type() {
  13679. return 'ClippingNode';
  13680. }
  13681. /**
  13682. * Constructs a new clipping node.
  13683. *
  13684. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  13685. * the selected scope influences the behavior of the node and what type of code is generated.
  13686. */
  13687. constructor( scope = ClippingNode.DEFAULT ) {
  13688. super();
  13689. /**
  13690. * The node's scope. Similar to other nodes, the selected scope influences
  13691. * the behavior of the node and what type of code is generated.
  13692. *
  13693. * @type {('default'|'hardware'|'alphaToCoverage')}
  13694. */
  13695. this.scope = scope;
  13696. }
  13697. /**
  13698. * Setups the node depending on the selected scope.
  13699. *
  13700. * @param {NodeBuilder} builder - The current node builder.
  13701. * @return {Node} The result node.
  13702. */
  13703. setup( builder ) {
  13704. super.setup( builder );
  13705. const clippingContext = builder.clippingContext;
  13706. const { intersectionPlanes, unionPlanes } = clippingContext;
  13707. this.hardwareClipping = builder.material.hardwareClipping;
  13708. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  13709. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  13710. } else if ( this.scope === ClippingNode.HARDWARE ) {
  13711. return this.setupHardwareClipping( unionPlanes, builder );
  13712. } else {
  13713. return this.setupDefault( intersectionPlanes, unionPlanes );
  13714. }
  13715. }
  13716. /**
  13717. * Setups alpha to coverage.
  13718. *
  13719. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13720. * @param {Array<Vector4>} unionPlanes - The union planes.
  13721. * @return {Node} The result node.
  13722. */
  13723. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13724. return Fn( () => {
  13725. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13726. const distanceGradient = float().toVar( 'distanceToGradient' );
  13727. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13728. const numUnionPlanes = unionPlanes.length;
  13729. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13730. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13731. Loop( numUnionPlanes, ( { i } ) => {
  13732. const plane = clippingPlanes.element( i );
  13733. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13734. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13735. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13736. } );
  13737. }
  13738. const numIntersectionPlanes = intersectionPlanes.length;
  13739. if ( numIntersectionPlanes > 0 ) {
  13740. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13741. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13742. Loop( numIntersectionPlanes, ( { i } ) => {
  13743. const plane = clippingPlanes.element( i );
  13744. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13745. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13746. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13747. } );
  13748. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13749. }
  13750. diffuseColor.a.mulAssign( clipOpacity );
  13751. diffuseColor.a.equal( 0.0 ).discard();
  13752. } )();
  13753. }
  13754. /**
  13755. * Setups the default clipping.
  13756. *
  13757. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13758. * @param {Array<Vector4>} unionPlanes - The union planes.
  13759. * @return {Node} The result node.
  13760. */
  13761. setupDefault( intersectionPlanes, unionPlanes ) {
  13762. return Fn( () => {
  13763. const numUnionPlanes = unionPlanes.length;
  13764. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13765. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13766. Loop( numUnionPlanes, ( { i } ) => {
  13767. const plane = clippingPlanes.element( i );
  13768. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13769. } );
  13770. }
  13771. const numIntersectionPlanes = intersectionPlanes.length;
  13772. if ( numIntersectionPlanes > 0 ) {
  13773. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13774. const clipped = bool( true ).toVar( 'clipped' );
  13775. Loop( numIntersectionPlanes, ( { i } ) => {
  13776. const plane = clippingPlanes.element( i );
  13777. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13778. } );
  13779. clipped.discard();
  13780. }
  13781. } )();
  13782. }
  13783. /**
  13784. * Setups hardware clipping.
  13785. *
  13786. * @param {Array<Vector4>} unionPlanes - The union planes.
  13787. * @param {NodeBuilder} builder - The current node builder.
  13788. * @return {Node} The result node.
  13789. */
  13790. setupHardwareClipping( unionPlanes, builder ) {
  13791. const numUnionPlanes = unionPlanes.length;
  13792. builder.enableHardwareClipping( numUnionPlanes );
  13793. return Fn( () => {
  13794. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13795. const hw_clip_distances = builtin( builder.getClipDistance() );
  13796. Loop( numUnionPlanes, ( { i } ) => {
  13797. const plane = clippingPlanes.element( i );
  13798. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13799. hw_clip_distances.element( i ).assign( distance );
  13800. } );
  13801. } )();
  13802. }
  13803. }
  13804. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13805. ClippingNode.DEFAULT = 'default';
  13806. ClippingNode.HARDWARE = 'hardware';
  13807. /**
  13808. * TSL function for setting up the default clipping logic.
  13809. *
  13810. * @tsl
  13811. * @function
  13812. * @returns {ClippingNode}
  13813. */
  13814. const clipping = () => nodeObject( new ClippingNode() );
  13815. /**
  13816. * TSL function for setting up alpha to coverage.
  13817. *
  13818. * @tsl
  13819. * @function
  13820. * @returns {ClippingNode}
  13821. */
  13822. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  13823. /**
  13824. * TSL function for setting up hardware-based clipping.
  13825. *
  13826. * @tsl
  13827. * @function
  13828. * @returns {ClippingNode}
  13829. */
  13830. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  13831. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13832. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13833. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13834. 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 ) ) ) ) ) );
  13835. } );
  13836. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13837. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13838. } );
  13839. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13840. // Find the discretized derivatives of our coordinates
  13841. const maxDeriv = max$1(
  13842. length( dFdx( position.xyz ) ),
  13843. length( dFdy( position.xyz ) )
  13844. );
  13845. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13846. // Find two nearest log-discretized noise scales
  13847. const pixScales = vec2(
  13848. exp2( floor( log2( pixScale ) ) ),
  13849. exp2( ceil( log2( pixScale ) ) )
  13850. );
  13851. // Compute alpha thresholds at our two noise scales
  13852. const alpha = vec2(
  13853. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13854. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13855. );
  13856. // Factor to interpolate lerp with
  13857. const lerpFactor = fract( log2( pixScale ) );
  13858. // Interpolate alpha threshold from noise at two scales
  13859. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13860. // Pass into CDF to compute uniformly distrib threshold
  13861. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13862. const cases = vec3(
  13863. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13864. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13865. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13866. // Find our final, uniformly distributed alpha threshold (ατ)
  13867. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13868. // Avoids ατ == 0. Could also do ατ =1-ατ
  13869. return clamp( threshold, 1.0e-6, 1.0 );
  13870. } ).setLayout( {
  13871. name: 'getAlphaHashThreshold',
  13872. type: 'float',
  13873. inputs: [
  13874. { name: 'position', type: 'vec3' }
  13875. ]
  13876. } );
  13877. /**
  13878. * An attribute node for representing vertex colors.
  13879. *
  13880. * @augments AttributeNode
  13881. */
  13882. class VertexColorNode extends AttributeNode {
  13883. static get type() {
  13884. return 'VertexColorNode';
  13885. }
  13886. /**
  13887. * Constructs a new vertex color node.
  13888. *
  13889. * @param {number} index - The attribute index.
  13890. */
  13891. constructor( index ) {
  13892. super( null, 'vec4' );
  13893. /**
  13894. * This flag can be used for type testing.
  13895. *
  13896. * @type {boolean}
  13897. * @readonly
  13898. * @default true
  13899. */
  13900. this.isVertexColorNode = true;
  13901. /**
  13902. * The attribute index to enable more than one sets of vertex colors.
  13903. *
  13904. * @type {number}
  13905. * @default 0
  13906. */
  13907. this.index = index;
  13908. }
  13909. /**
  13910. * Overwrites the default implementation by honoring the attribute index.
  13911. *
  13912. * @param {NodeBuilder} builder - The current node builder.
  13913. * @return {string} The attribute name.
  13914. */
  13915. getAttributeName( /*builder*/ ) {
  13916. const index = this.index;
  13917. return 'color' + ( index > 0 ? index : '' );
  13918. }
  13919. generate( builder ) {
  13920. const attributeName = this.getAttributeName( builder );
  13921. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13922. let result;
  13923. if ( geometryAttribute === true ) {
  13924. result = super.generate( builder );
  13925. } else {
  13926. // Vertex color fallback should be white
  13927. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13928. }
  13929. return result;
  13930. }
  13931. serialize( data ) {
  13932. super.serialize( data );
  13933. data.index = this.index;
  13934. }
  13935. deserialize( data ) {
  13936. super.deserialize( data );
  13937. this.index = data.index;
  13938. }
  13939. }
  13940. /**
  13941. * TSL function for creating a reference node.
  13942. *
  13943. * @tsl
  13944. * @function
  13945. * @param {number} [index=0] - The attribute index.
  13946. * @returns {VertexColorNode}
  13947. */
  13948. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  13949. /**
  13950. * Represents a "Color Burn" blend mode.
  13951. *
  13952. * It's designed to darken the base layer's colors based on the color of the blend layer.
  13953. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  13954. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  13955. *
  13956. * @tsl
  13957. * @function
  13958. * @param {Node<vec3>} base - The base color.
  13959. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  13960. * @return {Node<vec3>} The result.
  13961. */
  13962. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13963. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13964. } ).setLayout( {
  13965. name: 'blendBurn',
  13966. type: 'vec3',
  13967. inputs: [
  13968. { name: 'base', type: 'vec3' },
  13969. { name: 'blend', type: 'vec3' }
  13970. ]
  13971. } );
  13972. /**
  13973. * Represents a "Color Dodge" blend mode.
  13974. *
  13975. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  13976. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  13977. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  13978. *
  13979. * @tsl
  13980. * @function
  13981. * @param {Node<vec3>} base - The base color.
  13982. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13983. * @return {Node<vec3>} The result.
  13984. */
  13985. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13986. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13987. } ).setLayout( {
  13988. name: 'blendDodge',
  13989. type: 'vec3',
  13990. inputs: [
  13991. { name: 'base', type: 'vec3' },
  13992. { name: 'blend', type: 'vec3' }
  13993. ]
  13994. } );
  13995. /**
  13996. * Represents a "Screen" blend mode.
  13997. *
  13998. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  13999. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  14000. * effects.
  14001. *
  14002. * @tsl
  14003. * @function
  14004. * @param {Node<vec3>} base - The base color.
  14005. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  14006. * @return {Node<vec3>} The result.
  14007. */
  14008. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14009. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  14010. } ).setLayout( {
  14011. name: 'blendScreen',
  14012. type: 'vec3',
  14013. inputs: [
  14014. { name: 'base', type: 'vec3' },
  14015. { name: 'blend', type: 'vec3' }
  14016. ]
  14017. } );
  14018. /**
  14019. * Represents a "Overlay" blend mode.
  14020. *
  14021. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  14022. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  14023. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  14024. *
  14025. * @tsl
  14026. * @function
  14027. * @param {Node<vec3>} base - The base color.
  14028. * @param {Node<vec3>} blend - The blend color
  14029. * @return {Node<vec3>} The result.
  14030. */
  14031. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14032. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  14033. } ).setLayout( {
  14034. name: 'blendOverlay',
  14035. type: 'vec3',
  14036. inputs: [
  14037. { name: 'base', type: 'vec3' },
  14038. { name: 'blend', type: 'vec3' }
  14039. ]
  14040. } );
  14041. /**
  14042. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  14043. * It assumes both input colors have non-premultiplied alpha.
  14044. *
  14045. * @tsl
  14046. * @function
  14047. * @param {Node<vec4>} base - The base color.
  14048. * @param {Node<vec4>} blend - The blend color
  14049. * @return {Node<vec4>} The result.
  14050. */
  14051. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14052. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  14053. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  14054. } ).setLayout( {
  14055. name: 'blendColor',
  14056. type: 'vec4',
  14057. inputs: [
  14058. { name: 'base', type: 'vec4' },
  14059. { name: 'blend', type: 'vec4' }
  14060. ]
  14061. } );
  14062. /**
  14063. * Premultiplies the RGB channels of a color by its alpha channel.
  14064. *
  14065. * This function is useful for converting a non-premultiplied alpha color
  14066. * into a premultiplied alpha format, where the RGB values are scaled
  14067. * by the alpha value. Premultiplied alpha is often used in graphics
  14068. * rendering for certain operations, such as compositing and image processing.
  14069. *
  14070. * @tsl
  14071. * @function
  14072. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  14073. * @return {Node<vec4>} The color with premultiplied alpha.
  14074. */
  14075. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14076. return vec4( color.rgb.mul( color.a ), color.a );
  14077. }, { color: 'vec4', return: 'vec4' } );
  14078. /**
  14079. * Unpremultiplies the RGB channels of a color by its alpha channel.
  14080. *
  14081. * This function is useful for converting a premultiplied alpha color
  14082. * back into a non-premultiplied alpha format, where the RGB values are
  14083. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  14084. * rendering for certain operations, such as compositing and image processing.
  14085. *
  14086. * @tsl
  14087. * @function
  14088. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  14089. * @return {Node<vec4>} The color with non-premultiplied alpha.
  14090. */
  14091. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14092. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  14093. return vec4( color.rgb.div( color.a ), color.a );
  14094. }, { color: 'vec4', return: 'vec4' } );
  14095. // Deprecated
  14096. /**
  14097. * @tsl
  14098. * @function
  14099. * @deprecated since r171. Use {@link blendBurn} instead.
  14100. *
  14101. * @param {...any} params
  14102. * @returns {Function}
  14103. */
  14104. const burn = ( ...params ) => { // @deprecated, r171
  14105. warn( 'TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  14106. return blendBurn( params );
  14107. };
  14108. /**
  14109. * @tsl
  14110. * @function
  14111. * @deprecated since r171. Use {@link blendDodge} instead.
  14112. *
  14113. * @param {...any} params
  14114. * @returns {Function}
  14115. */
  14116. const dodge = ( ...params ) => { // @deprecated, r171
  14117. warn( 'TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  14118. return blendDodge( params );
  14119. };
  14120. /**
  14121. * @tsl
  14122. * @function
  14123. * @deprecated since r171. Use {@link blendScreen} instead.
  14124. *
  14125. * @param {...any} params
  14126. * @returns {Function}
  14127. */
  14128. const screen = ( ...params ) => { // @deprecated, r171
  14129. warn( 'TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  14130. return blendScreen( params );
  14131. };
  14132. /**
  14133. * @tsl
  14134. * @function
  14135. * @deprecated since r171. Use {@link blendOverlay} instead.
  14136. *
  14137. * @param {...any} params
  14138. * @returns {Function}
  14139. */
  14140. const overlay = ( ...params ) => { // @deprecated, r171
  14141. warn( 'TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  14142. return blendOverlay( params );
  14143. };
  14144. /**
  14145. * Base class for all node materials.
  14146. *
  14147. * @augments Material
  14148. */
  14149. class NodeMaterial extends Material {
  14150. static get type() {
  14151. return 'NodeMaterial';
  14152. }
  14153. /**
  14154. * Represents the type of the node material.
  14155. *
  14156. * @type {string}
  14157. */
  14158. get type() {
  14159. return this.constructor.type;
  14160. }
  14161. set type( _value ) { /* */ }
  14162. /**
  14163. * Constructs a new node material.
  14164. */
  14165. constructor() {
  14166. super();
  14167. /**
  14168. * This flag can be used for type testing.
  14169. *
  14170. * @type {boolean}
  14171. * @readonly
  14172. * @default true
  14173. */
  14174. this.isNodeMaterial = true;
  14175. /**
  14176. * Whether this material is affected by fog or not.
  14177. *
  14178. * @type {boolean}
  14179. * @default true
  14180. */
  14181. this.fog = true;
  14182. /**
  14183. * Whether this material is affected by lights or not.
  14184. *
  14185. * @type {boolean}
  14186. * @default false
  14187. */
  14188. this.lights = false;
  14189. /**
  14190. * Whether this material uses hardware clipping or not.
  14191. * This property is managed by the engine and should not be
  14192. * modified by apps.
  14193. *
  14194. * @type {boolean}
  14195. * @default false
  14196. */
  14197. this.hardwareClipping = false;
  14198. /**
  14199. * Node materials which set their `lights` property to `true`
  14200. * are affected by all lights of the scene. Sometimes selective
  14201. * lighting is wanted which means only _some_ lights in the scene
  14202. * affect a material. This can be achieved by creating an instance
  14203. * of {@link LightsNode} with a list of selective
  14204. * lights and assign the node to this property.
  14205. *
  14206. * ```js
  14207. * const customLightsNode = lights( [ light1, light2 ] );
  14208. * material.lightsNode = customLightsNode;
  14209. * ```
  14210. *
  14211. * @type {?LightsNode}
  14212. * @default null
  14213. */
  14214. this.lightsNode = null;
  14215. /**
  14216. * The environment of node materials can be defined by an environment
  14217. * map assigned to the `envMap` property or by `Scene.environment`
  14218. * if the node material is a PBR material. This node property allows to overwrite
  14219. * the default behavior and define the environment with a custom node.
  14220. *
  14221. * ```js
  14222. * material.envNode = pmremTexture( renderTarget.texture );
  14223. * ```
  14224. *
  14225. * @type {?Node<vec3>}
  14226. * @default null
  14227. */
  14228. this.envNode = null;
  14229. /**
  14230. * The lighting of node materials might be influenced by ambient occlusion.
  14231. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  14232. * and the respective `aoMapIntensity`. This node property allows to overwrite
  14233. * the default and define the ambient occlusion with a custom node instead.
  14234. *
  14235. * If you don't want to overwrite the diffuse color but modify the existing
  14236. * values instead, use {@link materialAO}.
  14237. *
  14238. * @type {?Node<float>}
  14239. * @default null
  14240. */
  14241. this.aoNode = null;
  14242. /**
  14243. * The diffuse color of node materials is by default inferred from the
  14244. * `color` and `map` properties. This node property allows to overwrite the default
  14245. * and define the diffuse color with a node instead.
  14246. *
  14247. * ```js
  14248. * material.colorNode = color( 0xff0000 ); // define red color
  14249. * ```
  14250. *
  14251. * If you don't want to overwrite the diffuse color but modify the existing
  14252. * values instead, use {@link materialColor}.
  14253. *
  14254. * ```js
  14255. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14256. * ```
  14257. *
  14258. * @type {?Node<vec3>}
  14259. * @default null
  14260. */
  14261. this.colorNode = null;
  14262. /**
  14263. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14264. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14265. * and define the normals with a node instead.
  14266. *
  14267. * If you don't want to overwrite the normals but modify the existing values instead,
  14268. * use {@link materialNormal}.
  14269. *
  14270. * @type {?Node<vec3>}
  14271. * @default null
  14272. */
  14273. this.normalNode = null;
  14274. /**
  14275. * The opacity of node materials is by default inferred from the `opacity`
  14276. * and `alphaMap` properties. This node property allows to overwrite the default
  14277. * and define the opacity with a node instead.
  14278. *
  14279. * If you don't want to overwrite the opacity but modify the existing
  14280. * value instead, use {@link materialOpacity}.
  14281. *
  14282. * @type {?Node<float>}
  14283. * @default null
  14284. */
  14285. this.opacityNode = null;
  14286. /**
  14287. * This node can be used to implement a variety of filter-like effects. The idea is
  14288. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14289. * to create an arbitrary effect and then assign the node composition to this property.
  14290. * Everything behind the object using this material will now be affected by a filter.
  14291. *
  14292. * ```js
  14293. * const material = new NodeMaterial()
  14294. * material.transparent = true;
  14295. *
  14296. * // everything behind the object will be monochromatic
  14297. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14298. * ```
  14299. *
  14300. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14301. *
  14302. * @type {?Node<vec3>}
  14303. * @default null
  14304. */
  14305. this.backdropNode = null;
  14306. /**
  14307. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14308. *
  14309. * @type {?Node<float>}
  14310. * @default null
  14311. */
  14312. this.backdropAlphaNode = null;
  14313. /**
  14314. * The alpha test of node materials is by default inferred from the `alphaTest`
  14315. * property. This node property allows to overwrite the default and define the
  14316. * alpha test with a node instead.
  14317. *
  14318. * If you don't want to overwrite the alpha test but modify the existing
  14319. * value instead, use {@link materialAlphaTest}.
  14320. *
  14321. * @type {?Node<float>}
  14322. * @default null
  14323. */
  14324. this.alphaTestNode = null;
  14325. /**
  14326. * Discards the fragment if the mask value is `false`.
  14327. *
  14328. * @type {?Node<bool>}
  14329. * @default null
  14330. */
  14331. this.maskNode = null;
  14332. /**
  14333. * The local vertex positions are computed based on multiple factors like the
  14334. * attribute data, morphing or skinning. This node property allows to overwrite
  14335. * the default and define local vertex positions with nodes instead.
  14336. *
  14337. * If you don't want to overwrite the vertex positions but modify the existing
  14338. * values instead, use {@link positionLocal}.
  14339. *
  14340. *```js
  14341. * material.positionNode = positionLocal.add( displace );
  14342. * ```
  14343. *
  14344. * @type {?Node<vec3>}
  14345. * @default null
  14346. */
  14347. this.positionNode = null;
  14348. /**
  14349. * This node property is intended for logic which modifies geometry data once or per animation step.
  14350. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14351. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14352. * can be implemented.
  14353. *
  14354. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14355. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14356. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14357. * eventually assigned to `geometryNode`.
  14358. *
  14359. * @type {?Function}
  14360. * @default null
  14361. */
  14362. this.geometryNode = null;
  14363. /**
  14364. * Allows to overwrite depth values in the fragment shader.
  14365. *
  14366. * @type {?Node<float>}
  14367. * @default null
  14368. */
  14369. this.depthNode = null;
  14370. /**
  14371. * Allows to overwrite the position used for shadow map rendering which
  14372. * is by default {@link positionWorld}, the vertex position
  14373. * in world space.
  14374. *
  14375. * @type {?Node<float>}
  14376. * @default null
  14377. */
  14378. this.receivedShadowPositionNode = null;
  14379. /**
  14380. * Allows to overwrite the geometry position used for shadow map projection which
  14381. * is by default {@link positionLocal}, the vertex position in local space.
  14382. *
  14383. * @type {?Node<float>}
  14384. * @default null
  14385. */
  14386. this.castShadowPositionNode = null;
  14387. /**
  14388. * This node can be used to influence how an object using this node material
  14389. * receive shadows.
  14390. *
  14391. * ```js
  14392. * const totalShadows = float( 1 ).toVar();
  14393. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14394. * totalShadows.mulAssign( shadow );
  14395. * //return float( 1 ); // bypass received shadows
  14396. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14397. * } );
  14398. *
  14399. * @type {?(Function|FunctionNode<vec4>)}
  14400. * @default null
  14401. */
  14402. this.receivedShadowNode = null;
  14403. /**
  14404. * This node can be used to influence how an object using this node material
  14405. * casts shadows. To apply a color to shadows, you can simply do:
  14406. *
  14407. * ```js
  14408. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14409. * ```
  14410. *
  14411. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14412. * is also common to use the property with `Fn` function so checks are performed
  14413. * per fragment.
  14414. *
  14415. * ```js
  14416. * materialCustomShadow.castShadowNode = Fn( () => {
  14417. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14418. * return materialColor;
  14419. * } )();
  14420. * ```
  14421. *
  14422. * @type {?Node<vec4>}
  14423. * @default null
  14424. */
  14425. this.castShadowNode = null;
  14426. /**
  14427. * This node can be used to define the final output of the material.
  14428. *
  14429. * TODO: Explain the differences to `fragmentNode`.
  14430. *
  14431. * @type {?Node<vec4>}
  14432. * @default null
  14433. */
  14434. this.outputNode = null;
  14435. /**
  14436. * MRT configuration is done on renderer or pass level. This node allows to
  14437. * overwrite what values are written into MRT targets on material level. This
  14438. * can be useful for implementing selective FX features that should only affect
  14439. * specific objects.
  14440. *
  14441. * @type {?MRTNode}
  14442. * @default null
  14443. */
  14444. this.mrtNode = null;
  14445. /**
  14446. * This node property can be used if you need complete freedom in implementing
  14447. * the fragment shader. Assigning a node will replace the built-in material
  14448. * logic used in the fragment stage.
  14449. *
  14450. * @type {?Node<vec4>}
  14451. * @default null
  14452. */
  14453. this.fragmentNode = null;
  14454. /**
  14455. * This node property can be used if you need complete freedom in implementing
  14456. * the vertex shader. Assigning a node will replace the built-in material logic
  14457. * used in the vertex stage.
  14458. *
  14459. * @type {?Node<vec4>}
  14460. * @default null
  14461. */
  14462. this.vertexNode = null;
  14463. /**
  14464. * This node can be used as a global context management component for this material.
  14465. *
  14466. * @type {?ContextNode}
  14467. * @default null
  14468. */
  14469. this.contextNode = null;
  14470. // Deprecated properties
  14471. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  14472. get: () => {
  14473. return this.receivedShadowPositionNode;
  14474. },
  14475. set: ( value ) => {
  14476. warn( 'NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  14477. this.receivedShadowPositionNode = value;
  14478. }
  14479. } );
  14480. }
  14481. /**
  14482. * Returns an array of child nodes for this material.
  14483. *
  14484. * @private
  14485. * @returns {Array<{property: string, childNode: Node}>}
  14486. */
  14487. _getNodeChildren() {
  14488. const children = [];
  14489. for ( const property of Object.getOwnPropertyNames( this ) ) {
  14490. if ( property.startsWith( '_' ) === true ) continue;
  14491. const object = this[ property ];
  14492. if ( object && object.isNode === true ) {
  14493. children.push( { property, childNode: object } );
  14494. }
  14495. }
  14496. return children;
  14497. }
  14498. /**
  14499. * Allows to define a custom cache key that influence the material key computation
  14500. * for render objects.
  14501. *
  14502. * @return {string} The custom cache key.
  14503. */
  14504. customProgramCacheKey() {
  14505. const values = [];
  14506. for ( const { property, childNode } of this._getNodeChildren() ) {
  14507. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey() );
  14508. }
  14509. return this.type + hashArray( values );
  14510. }
  14511. /**
  14512. * Builds this material with the given node builder.
  14513. *
  14514. * @param {NodeBuilder} builder - The current node builder.
  14515. */
  14516. build( builder ) {
  14517. this.setup( builder );
  14518. }
  14519. /**
  14520. * Setups a node material observer with the given builder.
  14521. *
  14522. * @param {NodeBuilder} builder - The current node builder.
  14523. * @return {NodeMaterialObserver} The node material observer.
  14524. */
  14525. setupObserver( builder ) {
  14526. return new NodeMaterialObserver( builder );
  14527. }
  14528. /**
  14529. * Setups the vertex and fragment stage of this node material.
  14530. *
  14531. * @param {NodeBuilder} builder - The current node builder.
  14532. */
  14533. setup( builder ) {
  14534. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  14535. builder.context.setupPositionView = () => this.setupPositionView( builder );
  14536. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  14537. const renderer = builder.renderer;
  14538. const renderTarget = renderer.getRenderTarget();
  14539. // < CONTEXT >
  14540. if ( renderer.contextNode.isContextNode === true ) {
  14541. builder.context = { ...builder.context, ...renderer.contextNode.getFlowContextData() };
  14542. } else {
  14543. error( 'NodeMaterial: "renderer.contextNode" must be an instance of `context()`.' );
  14544. }
  14545. if ( this.contextNode !== null ) {
  14546. if ( this.contextNode.isContextNode === true ) {
  14547. builder.context = { ...builder.context, ...this.contextNode.getFlowContextData() };
  14548. } else {
  14549. error( 'NodeMaterial: "material.contextNode" must be an instance of `context()`.' );
  14550. }
  14551. }
  14552. // < VERTEX STAGE >
  14553. builder.addStack();
  14554. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  14555. const vertexNode = this.vertexNode || mvp;
  14556. builder.stack.outputNode = vertexNode;
  14557. this.setupHardwareClipping( builder );
  14558. if ( this.geometryNode !== null ) {
  14559. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  14560. }
  14561. builder.addFlow( 'vertex', builder.removeStack() );
  14562. // < FRAGMENT STAGE >
  14563. builder.addStack();
  14564. let resultNode;
  14565. const clippingNode = this.setupClipping( builder );
  14566. if ( this.depthWrite === true || this.depthTest === true ) {
  14567. // only write depth if depth buffer is configured
  14568. if ( renderTarget !== null ) {
  14569. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  14570. } else {
  14571. if ( renderer.depth === true ) this.setupDepth( builder );
  14572. }
  14573. }
  14574. if ( this.fragmentNode === null ) {
  14575. this.setupDiffuseColor( builder );
  14576. this.setupVariants( builder );
  14577. const outgoingLightNode = this.setupLighting( builder );
  14578. if ( clippingNode !== null ) builder.stack.addToStack( clippingNode );
  14579. // force unsigned floats - useful for RenderTargets
  14580. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  14581. resultNode = this.setupOutput( builder, basicOutput );
  14582. // OUTPUT NODE
  14583. output.assign( resultNode );
  14584. //
  14585. const isCustomOutput = this.outputNode !== null;
  14586. if ( isCustomOutput ) resultNode = this.outputNode;
  14587. //
  14588. if ( builder.context.getOutput ) {
  14589. resultNode = builder.context.getOutput( resultNode, builder );
  14590. }
  14591. // MRT
  14592. if ( renderTarget !== null ) {
  14593. const mrt = renderer.getMRT();
  14594. const materialMRT = this.mrtNode;
  14595. if ( mrt !== null ) {
  14596. if ( isCustomOutput ) output.assign( resultNode );
  14597. resultNode = mrt;
  14598. if ( materialMRT !== null ) {
  14599. resultNode = mrt.merge( materialMRT );
  14600. }
  14601. } else if ( materialMRT !== null ) {
  14602. resultNode = materialMRT;
  14603. }
  14604. }
  14605. } else {
  14606. let fragmentNode = this.fragmentNode;
  14607. if ( fragmentNode.isOutputStructNode !== true ) {
  14608. fragmentNode = vec4( fragmentNode );
  14609. }
  14610. resultNode = this.setupOutput( builder, fragmentNode );
  14611. }
  14612. builder.stack.outputNode = resultNode;
  14613. builder.addFlow( 'fragment', builder.removeStack() );
  14614. // < OBSERVER >
  14615. builder.observer = this.setupObserver( builder );
  14616. }
  14617. /**
  14618. * Setups the clipping node.
  14619. *
  14620. * @param {NodeBuilder} builder - The current node builder.
  14621. * @return {ClippingNode} The clipping node.
  14622. */
  14623. setupClipping( builder ) {
  14624. if ( builder.clippingContext === null ) return null;
  14625. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  14626. let result = null;
  14627. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  14628. const samples = builder.renderer.currentSamples;
  14629. if ( this.alphaToCoverage && samples > 1 ) {
  14630. // to be added to flow when the color/alpha value has been determined
  14631. result = clippingAlpha();
  14632. } else {
  14633. builder.stack.addToStack( clipping() );
  14634. }
  14635. }
  14636. return result;
  14637. }
  14638. /**
  14639. * Setups the hardware clipping if available on the current device.
  14640. *
  14641. * @param {NodeBuilder} builder - The current node builder.
  14642. */
  14643. setupHardwareClipping( builder ) {
  14644. this.hardwareClipping = false;
  14645. if ( builder.clippingContext === null ) return;
  14646. const candidateCount = builder.clippingContext.unionPlanes.length;
  14647. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14648. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14649. builder.stack.addToStack( hardwareClipping() );
  14650. this.hardwareClipping = true;
  14651. }
  14652. return;
  14653. }
  14654. /**
  14655. * Setups the depth of this material.
  14656. *
  14657. * @param {NodeBuilder} builder - The current node builder.
  14658. */
  14659. setupDepth( builder ) {
  14660. const { renderer, camera } = builder;
  14661. // Depth
  14662. let depthNode = this.depthNode;
  14663. if ( depthNode === null ) {
  14664. const mrt = renderer.getMRT();
  14665. if ( mrt && mrt.has( 'depth' ) ) {
  14666. depthNode = mrt.get( 'depth' );
  14667. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14668. if ( camera.isPerspectiveCamera ) {
  14669. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14670. } else {
  14671. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14672. }
  14673. }
  14674. }
  14675. if ( depthNode !== null ) {
  14676. depth.assign( depthNode ).toStack();
  14677. }
  14678. }
  14679. /**
  14680. * Setups the position node in view space. This method exists
  14681. * so derived node materials can modify the implementation e.g. sprite materials.
  14682. *
  14683. * @param {NodeBuilder} builder - The current node builder.
  14684. * @return {Node<vec3>} The position in view space.
  14685. */
  14686. setupPositionView( /*builder*/ ) {
  14687. return modelViewMatrix.mul( positionLocal ).xyz;
  14688. }
  14689. /**
  14690. * Setups the position in clip space.
  14691. *
  14692. * @param {NodeBuilder} builder - The current node builder.
  14693. * @return {Node<vec4>} The position in view space.
  14694. */
  14695. setupModelViewProjection( /*builder*/ ) {
  14696. return cameraProjectionMatrix.mul( positionView );
  14697. }
  14698. /**
  14699. * Setups the logic for the vertex stage.
  14700. *
  14701. * @param {NodeBuilder} builder - The current node builder.
  14702. * @return {Node<vec4>} The position in clip space.
  14703. */
  14704. setupVertex( builder ) {
  14705. builder.addStack();
  14706. this.setupPosition( builder );
  14707. builder.context.vertex = builder.removeStack();
  14708. return modelViewProjection;
  14709. }
  14710. /**
  14711. * Setups the computation of the position in local space.
  14712. *
  14713. * @param {NodeBuilder} builder - The current node builder.
  14714. * @return {Node<vec3>} The position in local space.
  14715. */
  14716. setupPosition( builder ) {
  14717. const { object, geometry } = builder;
  14718. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  14719. morphReference( object ).toStack();
  14720. }
  14721. if ( object.isSkinnedMesh === true ) {
  14722. skinning( object ).toStack();
  14723. }
  14724. if ( this.displacementMap ) {
  14725. const displacementMap = materialReference( 'displacementMap', 'texture' );
  14726. const displacementScale = materialReference( 'displacementScale', 'float' );
  14727. const displacementBias = materialReference( 'displacementBias', 'float' );
  14728. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  14729. }
  14730. if ( object.isBatchedMesh ) {
  14731. batch( object ).toStack();
  14732. }
  14733. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  14734. instancedMesh( object ).toStack();
  14735. }
  14736. if ( this.positionNode !== null ) {
  14737. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  14738. }
  14739. return positionLocal;
  14740. }
  14741. /**
  14742. * Setups the computation of the material's diffuse color.
  14743. *
  14744. * @param {NodeBuilder} builder - The current node builder.
  14745. * @param {BufferGeometry} geometry - The geometry.
  14746. */
  14747. setupDiffuseColor( builder ) {
  14748. const { object, geometry } = builder;
  14749. // MASK
  14750. if ( this.maskNode !== null ) {
  14751. // Discard if the mask is `false`
  14752. bool( this.maskNode ).not().discard();
  14753. }
  14754. // COLOR
  14755. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  14756. // VERTEX COLORS
  14757. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  14758. colorNode = colorNode.mul( vertexColor() );
  14759. }
  14760. // INSTANCED COLORS
  14761. if ( object.instanceColor ) {
  14762. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  14763. colorNode = instanceColor.mul( colorNode );
  14764. }
  14765. if ( object.isBatchedMesh && object._colorsTexture ) {
  14766. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14767. colorNode = batchColor.mul( colorNode );
  14768. }
  14769. // DIFFUSE COLOR
  14770. diffuseColor.assign( colorNode );
  14771. // OPACITY
  14772. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14773. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14774. // ALPHA TEST
  14775. let alphaTestNode = null;
  14776. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14777. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14778. if ( this.alphaToCoverage === true ) {
  14779. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  14780. diffuseColor.a.lessThanEqual( 0 ).discard();
  14781. } else {
  14782. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14783. }
  14784. }
  14785. // ALPHA HASH
  14786. if ( this.alphaHash === true ) {
  14787. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14788. }
  14789. // OPAQUE
  14790. if ( builder.isOpaque() ) {
  14791. diffuseColor.a.assign( 1.0 );
  14792. }
  14793. }
  14794. /**
  14795. * Abstract interface method that can be implemented by derived materials
  14796. * to setup material-specific node variables.
  14797. *
  14798. * @abstract
  14799. * @param {NodeBuilder} builder - The current node builder.
  14800. */
  14801. setupVariants( /*builder*/ ) {
  14802. // Interface function.
  14803. }
  14804. /**
  14805. * Setups the outgoing light node variable
  14806. *
  14807. * @return {Node<vec3>} The outgoing light node.
  14808. */
  14809. setupOutgoingLight() {
  14810. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14811. }
  14812. /**
  14813. * Setups the normal node from the material.
  14814. *
  14815. * @return {Node<vec3>} The normal node.
  14816. */
  14817. setupNormal() {
  14818. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14819. }
  14820. /**
  14821. * Setups the environment node from the material.
  14822. *
  14823. * @param {NodeBuilder} builder - The current node builder.
  14824. * @return {Node<vec4>} The environment node.
  14825. */
  14826. setupEnvironment( /*builder*/ ) {
  14827. let node = null;
  14828. if ( this.envNode ) {
  14829. node = this.envNode;
  14830. } else if ( this.envMap ) {
  14831. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14832. }
  14833. return node;
  14834. }
  14835. /**
  14836. * Setups the light map node from the material.
  14837. *
  14838. * @param {NodeBuilder} builder - The current node builder.
  14839. * @return {Node<vec3>} The light map node.
  14840. */
  14841. setupLightMap( builder ) {
  14842. let node = null;
  14843. if ( builder.material.lightMap ) {
  14844. node = new IrradianceNode( materialLightMap );
  14845. }
  14846. return node;
  14847. }
  14848. /**
  14849. * Setups the lights node based on the scene, environment and material.
  14850. *
  14851. * @param {NodeBuilder} builder - The current node builder.
  14852. * @return {LightsNode} The lights node.
  14853. */
  14854. setupLights( builder ) {
  14855. const materialLightsNode = [];
  14856. //
  14857. const envNode = this.setupEnvironment( builder );
  14858. if ( envNode && envNode.isLightingNode ) {
  14859. materialLightsNode.push( envNode );
  14860. }
  14861. const lightMapNode = this.setupLightMap( builder );
  14862. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14863. materialLightsNode.push( lightMapNode );
  14864. }
  14865. let aoNode = builder.context.ao || null;
  14866. if ( this.aoNode !== null || builder.material.aoMap ) {
  14867. const mtlAO = this.aoNode !== null ? this.aoNode : materialAO;
  14868. aoNode = aoNode !== null ? aoNode.mul( mtlAO ) : mtlAO;
  14869. }
  14870. if ( aoNode !== null ) {
  14871. materialLightsNode.push( new AONode( aoNode ) );
  14872. }
  14873. let lightsN = this.lightsNode || builder.lightsNode;
  14874. if ( materialLightsNode.length > 0 ) {
  14875. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14876. }
  14877. return lightsN;
  14878. }
  14879. /**
  14880. * This method should be implemented by most derived materials
  14881. * since it defines the material's lighting model.
  14882. *
  14883. * @abstract
  14884. * @param {NodeBuilder} builder - The current node builder.
  14885. * @return {LightingModel} The lighting model.
  14886. */
  14887. setupLightingModel( /*builder*/ ) {
  14888. // Interface function.
  14889. }
  14890. /**
  14891. * Setups the outgoing light node.
  14892. *
  14893. * @param {NodeBuilder} builder - The current node builder.
  14894. * @return {Node<vec3>} The outgoing light node.
  14895. */
  14896. setupLighting( builder ) {
  14897. const { material } = builder;
  14898. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14899. // OUTGOING LIGHT
  14900. const lights = this.lights === true || this.lightsNode !== null;
  14901. const lightsNode = lights ? this.setupLights( builder ) : null;
  14902. let outgoingLightNode = this.setupOutgoingLight( builder );
  14903. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14904. const lightingModel = this.setupLightingModel( builder ) || null;
  14905. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14906. } else if ( backdropNode !== null ) {
  14907. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14908. }
  14909. // EMISSIVE
  14910. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14911. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14912. outgoingLightNode = outgoingLightNode.add( emissive );
  14913. }
  14914. return outgoingLightNode;
  14915. }
  14916. /**
  14917. * Setup the fog.
  14918. *
  14919. * @param {NodeBuilder} builder - The current node builder.
  14920. * @param {Node<vec4>} outputNode - The existing output node.
  14921. * @return {Node<vec4>} The output node.
  14922. */
  14923. setupFog( builder, outputNode ) {
  14924. const fogNode = builder.fogNode;
  14925. if ( fogNode ) {
  14926. output.assign( outputNode );
  14927. outputNode = vec4( fogNode.toVar() );
  14928. }
  14929. return outputNode;
  14930. }
  14931. /**
  14932. * Setups premultiplied alpha.
  14933. *
  14934. * @param {NodeBuilder} builder - The current node builder.
  14935. * @param {Node<vec4>} outputNode - The existing output node.
  14936. * @return {Node<vec4>} The output node.
  14937. */
  14938. setupPremultipliedAlpha( builder, outputNode ) {
  14939. return premultiplyAlpha( outputNode );
  14940. }
  14941. /**
  14942. * Setups the output node.
  14943. *
  14944. * @param {NodeBuilder} builder - The current node builder.
  14945. * @param {Node<vec4>} outputNode - The existing output node.
  14946. * @return {Node<vec4>} The output node.
  14947. */
  14948. setupOutput( builder, outputNode ) {
  14949. // FOG
  14950. if ( this.fog === true ) {
  14951. outputNode = this.setupFog( builder, outputNode );
  14952. }
  14953. // PREMULTIPLIED ALPHA
  14954. if ( this.premultipliedAlpha === true ) {
  14955. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  14956. }
  14957. return outputNode;
  14958. }
  14959. /**
  14960. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  14961. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  14962. * defining all material properties of the classic type in the node type.
  14963. *
  14964. * @param {Material} material - The material to copy properties with their values to this node material.
  14965. */
  14966. setDefaultValues( material ) {
  14967. // This approach is to reuse the native refreshUniforms*
  14968. // and turn available the use of features like transmission and environment in core
  14969. for ( const property in material ) {
  14970. const value = material[ property ];
  14971. if ( this[ property ] === undefined ) {
  14972. this[ property ] = value;
  14973. if ( value && value.clone ) this[ property ] = value.clone();
  14974. }
  14975. }
  14976. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  14977. for ( const key in descriptors ) {
  14978. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  14979. descriptors[ key ].get !== undefined ) {
  14980. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  14981. }
  14982. }
  14983. }
  14984. /**
  14985. * Serializes this material to JSON.
  14986. *
  14987. * @param {?(Object|string)} meta - The meta information for serialization.
  14988. * @return {Object} The serialized node.
  14989. */
  14990. toJSON( meta ) {
  14991. const isRoot = ( meta === undefined || typeof meta === 'string' );
  14992. if ( isRoot ) {
  14993. meta = {
  14994. textures: {},
  14995. images: {},
  14996. nodes: {}
  14997. };
  14998. }
  14999. const data = Material.prototype.toJSON.call( this, meta );
  15000. data.inputNodes = {};
  15001. for ( const { property, childNode } of this._getNodeChildren() ) {
  15002. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  15003. }
  15004. // TODO: Copied from Object3D.toJSON
  15005. function extractFromCache( cache ) {
  15006. const values = [];
  15007. for ( const key in cache ) {
  15008. const data = cache[ key ];
  15009. delete data.metadata;
  15010. values.push( data );
  15011. }
  15012. return values;
  15013. }
  15014. if ( isRoot ) {
  15015. const textures = extractFromCache( meta.textures );
  15016. const images = extractFromCache( meta.images );
  15017. const nodes = extractFromCache( meta.nodes );
  15018. if ( textures.length > 0 ) data.textures = textures;
  15019. if ( images.length > 0 ) data.images = images;
  15020. if ( nodes.length > 0 ) data.nodes = nodes;
  15021. }
  15022. return data;
  15023. }
  15024. /**
  15025. * Copies the properties of the given node material to this instance.
  15026. *
  15027. * @param {NodeMaterial} source - The material to copy.
  15028. * @return {NodeMaterial} A reference to this node material.
  15029. */
  15030. copy( source ) {
  15031. this.lightsNode = source.lightsNode;
  15032. this.envNode = source.envNode;
  15033. this.aoNode = source.aoNode;
  15034. this.colorNode = source.colorNode;
  15035. this.normalNode = source.normalNode;
  15036. this.opacityNode = source.opacityNode;
  15037. this.backdropNode = source.backdropNode;
  15038. this.backdropAlphaNode = source.backdropAlphaNode;
  15039. this.alphaTestNode = source.alphaTestNode;
  15040. this.maskNode = source.maskNode;
  15041. this.positionNode = source.positionNode;
  15042. this.geometryNode = source.geometryNode;
  15043. this.depthNode = source.depthNode;
  15044. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  15045. this.castShadowPositionNode = source.castShadowPositionNode;
  15046. this.receivedShadowNode = source.receivedShadowNode;
  15047. this.castShadowNode = source.castShadowNode;
  15048. this.outputNode = source.outputNode;
  15049. this.mrtNode = source.mrtNode;
  15050. this.fragmentNode = source.fragmentNode;
  15051. this.vertexNode = source.vertexNode;
  15052. this.contextNode = source.contextNode;
  15053. return super.copy( source );
  15054. }
  15055. }
  15056. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  15057. /**
  15058. * Node material version of {@link LineBasicMaterial}.
  15059. *
  15060. * @augments NodeMaterial
  15061. */
  15062. class LineBasicNodeMaterial extends NodeMaterial {
  15063. static get type() {
  15064. return 'LineBasicNodeMaterial';
  15065. }
  15066. /**
  15067. * Constructs a new line basic node material.
  15068. *
  15069. * @param {Object} [parameters] - The configuration parameter.
  15070. */
  15071. constructor( parameters ) {
  15072. super();
  15073. /**
  15074. * This flag can be used for type testing.
  15075. *
  15076. * @type {boolean}
  15077. * @readonly
  15078. * @default true
  15079. */
  15080. this.isLineBasicNodeMaterial = true;
  15081. this.setDefaultValues( _defaultValues$d );
  15082. this.setValues( parameters );
  15083. }
  15084. }
  15085. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  15086. /**
  15087. * Node material version of {@link LineDashedMaterial}.
  15088. *
  15089. * @augments NodeMaterial
  15090. */
  15091. class LineDashedNodeMaterial extends NodeMaterial {
  15092. static get type() {
  15093. return 'LineDashedNodeMaterial';
  15094. }
  15095. /**
  15096. * Constructs a new line dashed node material.
  15097. *
  15098. * @param {Object} [parameters] - The configuration parameter.
  15099. */
  15100. constructor( parameters ) {
  15101. super();
  15102. /**
  15103. * This flag can be used for type testing.
  15104. *
  15105. * @type {boolean}
  15106. * @readonly
  15107. * @default true
  15108. */
  15109. this.isLineDashedNodeMaterial = true;
  15110. this.setDefaultValues( _defaultValues$c );
  15111. /**
  15112. * The dash offset.
  15113. *
  15114. * @type {number}
  15115. * @default 0
  15116. */
  15117. this.dashOffset = 0;
  15118. /**
  15119. * The offset of dash materials is by default inferred from the `dashOffset`
  15120. * property. This node property allows to overwrite the default
  15121. * and define the offset with a node instead.
  15122. *
  15123. * If you don't want to overwrite the offset but modify the existing
  15124. * value instead, use {@link materialLineDashOffset}.
  15125. *
  15126. * @type {?Node<float>}
  15127. * @default null
  15128. */
  15129. this.offsetNode = null;
  15130. /**
  15131. * The scale of dash materials is by default inferred from the `scale`
  15132. * property. This node property allows to overwrite the default
  15133. * and define the scale with a node instead.
  15134. *
  15135. * If you don't want to overwrite the scale but modify the existing
  15136. * value instead, use {@link materialLineScale}.
  15137. *
  15138. * @type {?Node<float>}
  15139. * @default null
  15140. */
  15141. this.dashScaleNode = null;
  15142. /**
  15143. * The dash size of dash materials is by default inferred from the `dashSize`
  15144. * property. This node property allows to overwrite the default
  15145. * and define the dash size with a node instead.
  15146. *
  15147. * If you don't want to overwrite the dash size but modify the existing
  15148. * value instead, use {@link materialLineDashSize}.
  15149. *
  15150. * @type {?Node<float>}
  15151. * @default null
  15152. */
  15153. this.dashSizeNode = null;
  15154. /**
  15155. * The gap size of dash materials is by default inferred from the `gapSize`
  15156. * property. This node property allows to overwrite the default
  15157. * and define the gap size with a node instead.
  15158. *
  15159. * If you don't want to overwrite the gap size but modify the existing
  15160. * value instead, use {@link materialLineGapSize}.
  15161. *
  15162. * @type {?Node<float>}
  15163. * @default null
  15164. */
  15165. this.gapSizeNode = null;
  15166. this.setValues( parameters );
  15167. }
  15168. /**
  15169. * Setups the dash specific node variables.
  15170. *
  15171. * @param {NodeBuilder} builder - The current node builder.
  15172. */
  15173. setupVariants( /* builder */ ) {
  15174. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15175. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15176. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15177. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15178. dashSize.assign( dashSizeNode );
  15179. gapSize.assign( gapSizeNode );
  15180. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  15181. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  15182. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  15183. }
  15184. }
  15185. let _sharedFramebuffer = null;
  15186. /**
  15187. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  15188. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  15189. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  15190. *
  15191. * @augments ViewportTextureNode
  15192. */
  15193. class ViewportSharedTextureNode extends ViewportTextureNode {
  15194. static get type() {
  15195. return 'ViewportSharedTextureNode';
  15196. }
  15197. /**
  15198. * Constructs a new viewport shared texture node.
  15199. *
  15200. * @param {Node} [uvNode=screenUV] - The uv node.
  15201. * @param {?Node} [levelNode=null] - The level node.
  15202. */
  15203. constructor( uvNode = screenUV, levelNode = null ) {
  15204. if ( _sharedFramebuffer === null ) {
  15205. _sharedFramebuffer = new FramebufferTexture();
  15206. }
  15207. super( uvNode, levelNode, _sharedFramebuffer );
  15208. }
  15209. /**
  15210. * Overwritten so the method always returns the unique shared
  15211. * framebuffer texture.
  15212. *
  15213. * @return {FramebufferTexture} The shared framebuffer texture.
  15214. */
  15215. getTextureForReference() {
  15216. return _sharedFramebuffer;
  15217. }
  15218. updateReference() {
  15219. return this;
  15220. }
  15221. }
  15222. /**
  15223. * TSL function for creating a shared viewport texture node.
  15224. *
  15225. * @tsl
  15226. * @function
  15227. * @param {?Node} [uvNode=screenUV] - The uv node.
  15228. * @param {?Node} [levelNode=null] - The level node.
  15229. * @returns {ViewportSharedTextureNode}
  15230. */
  15231. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  15232. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  15233. /**
  15234. * This node material can be used to render lines with a size larger than one
  15235. * by representing them as instanced meshes.
  15236. *
  15237. * @augments NodeMaterial
  15238. */
  15239. class Line2NodeMaterial extends NodeMaterial {
  15240. static get type() {
  15241. return 'Line2NodeMaterial';
  15242. }
  15243. /**
  15244. * Constructs a new node material for wide line rendering.
  15245. *
  15246. * @param {Object} [parameters={}] - The configuration parameter.
  15247. */
  15248. constructor( parameters = {} ) {
  15249. super();
  15250. /**
  15251. * This flag can be used for type testing.
  15252. *
  15253. * @type {boolean}
  15254. * @readonly
  15255. * @default true
  15256. */
  15257. this.isLine2NodeMaterial = true;
  15258. this.setDefaultValues( _defaultValues$b );
  15259. /**
  15260. * Whether vertex colors should be used or not.
  15261. *
  15262. * @type {boolean}
  15263. * @default false
  15264. */
  15265. this.useColor = parameters.vertexColors;
  15266. /**
  15267. * The dash offset.
  15268. *
  15269. * @type {number}
  15270. * @default 0
  15271. */
  15272. this.dashOffset = 0;
  15273. /**
  15274. * Defines the lines color.
  15275. *
  15276. * @type {?Node<vec3>}
  15277. * @default null
  15278. */
  15279. this.lineColorNode = null;
  15280. /**
  15281. * Defines the offset.
  15282. *
  15283. * @type {?Node<float>}
  15284. * @default null
  15285. */
  15286. this.offsetNode = null;
  15287. /**
  15288. * Defines the dash scale.
  15289. *
  15290. * @type {?Node<float>}
  15291. * @default null
  15292. */
  15293. this.dashScaleNode = null;
  15294. /**
  15295. * Defines the dash size.
  15296. *
  15297. * @type {?Node<float>}
  15298. * @default null
  15299. */
  15300. this.dashSizeNode = null;
  15301. /**
  15302. * Defines the gap size.
  15303. *
  15304. * @type {?Node<float>}
  15305. * @default null
  15306. */
  15307. this.gapSizeNode = null;
  15308. /**
  15309. * Blending is set to `NoBlending` since transparency
  15310. * is not supported, yet.
  15311. *
  15312. * @type {number}
  15313. * @default 0
  15314. */
  15315. this.blending = NoBlending;
  15316. this._useDash = parameters.dashed;
  15317. this._useAlphaToCoverage = true;
  15318. this._useWorldUnits = false;
  15319. this.setValues( parameters );
  15320. }
  15321. /**
  15322. * Setups the vertex and fragment stage of this node material.
  15323. *
  15324. * @param {NodeBuilder} builder - The current node builder.
  15325. */
  15326. setup( builder ) {
  15327. const { renderer } = builder;
  15328. const useAlphaToCoverage = this._useAlphaToCoverage;
  15329. const useColor = this.useColor;
  15330. const useDash = this._useDash;
  15331. const useWorldUnits = this._useWorldUnits;
  15332. const trimSegment = Fn( ( { start, end } ) => {
  15333. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15334. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15335. const nearEstimate = b.mul( -0.5 ).div( a );
  15336. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15337. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  15338. } ).setLayout( {
  15339. name: 'trimSegment',
  15340. type: 'vec4',
  15341. inputs: [
  15342. { name: 'start', type: 'vec4' },
  15343. { name: 'end', type: 'vec4' }
  15344. ]
  15345. } );
  15346. this.vertexNode = Fn( () => {
  15347. const instanceStart = attribute( 'instanceStart' );
  15348. const instanceEnd = attribute( 'instanceEnd' );
  15349. // camera space
  15350. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15351. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15352. if ( useDash ) {
  15353. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15354. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15355. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  15356. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  15357. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  15358. lineDistance = lineDistance.add( offsetNode );
  15359. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  15360. }
  15361. if ( useWorldUnits ) {
  15362. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  15363. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  15364. }
  15365. const aspect = viewport.z.div( viewport.w );
  15366. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15367. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15368. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15369. // perhaps there is a more elegant solution -- WestLangley
  15370. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15371. If( perspective, () => {
  15372. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15373. end.assign( trimSegment( { start: start, end: end } ) );
  15374. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15375. start.assign( trimSegment( { start: end, end: start } ) );
  15376. } );
  15377. } );
  15378. // clip space
  15379. const clipStart = cameraProjectionMatrix.mul( start );
  15380. const clipEnd = cameraProjectionMatrix.mul( end );
  15381. // ndc space
  15382. const ndcStart = clipStart.xyz.div( clipStart.w );
  15383. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15384. // direction
  15385. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15386. // account for clip-space aspect ratio
  15387. dir.x.assign( dir.x.mul( aspect ) );
  15388. dir.assign( dir.normalize() );
  15389. const clip = vec4().toVar();
  15390. if ( useWorldUnits ) {
  15391. // get the offset direction as perpendicular to the view vector
  15392. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15393. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15394. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15395. const worldFwd = worldDir.cross( worldUp );
  15396. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15397. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15398. // height offset
  15399. const hw = materialLineWidth.mul( 0.5 );
  15400. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15401. // don't extend the line if we're rendering dashes because we
  15402. // won't be rendering the endcaps
  15403. if ( ! useDash ) {
  15404. // cap extension
  15405. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15406. // add width to the box
  15407. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15408. // endcaps
  15409. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15410. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15411. } );
  15412. }
  15413. // project the worldpos
  15414. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15415. // shift the depth of the projected points so the line
  15416. // segments overlap neatly
  15417. const clipPose = vec3().toVar();
  15418. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15419. clip.z.assign( clipPose.z.mul( clip.w ) );
  15420. } else {
  15421. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15422. // undo aspect ratio adjustment
  15423. dir.x.assign( dir.x.div( aspect ) );
  15424. offset.x.assign( offset.x.div( aspect ) );
  15425. // sign flip
  15426. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15427. // endcaps
  15428. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15429. offset.assign( offset.sub( dir ) );
  15430. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15431. offset.assign( offset.add( dir ) );
  15432. } );
  15433. // adjust for linewidth
  15434. offset.assign( offset.mul( materialLineWidth ) );
  15435. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15436. offset.assign( offset.div( viewport.w.div( screenDPR ) ) );
  15437. // select end
  15438. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15439. // back to clip space
  15440. offset.assign( offset.mul( clip.w ) );
  15441. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15442. }
  15443. return clip;
  15444. } )();
  15445. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15446. const p13 = p1.sub( p3 );
  15447. const p43 = p4.sub( p3 );
  15448. const p21 = p2.sub( p1 );
  15449. const d1343 = p13.dot( p43 );
  15450. const d4321 = p43.dot( p21 );
  15451. const d1321 = p13.dot( p21 );
  15452. const d4343 = p43.dot( p43 );
  15453. const d2121 = p21.dot( p21 );
  15454. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15455. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15456. const mua = numer.div( denom ).clamp();
  15457. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15458. return vec2( mua, mub );
  15459. } );
  15460. this.colorNode = Fn( () => {
  15461. const vUv = uv$1();
  15462. if ( useDash ) {
  15463. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15464. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15465. dashSize.assign( dashSizeNode );
  15466. gapSize.assign( gapSizeNode );
  15467. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  15468. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15469. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15470. }
  15471. const alpha = float( 1 ).toVar( 'alpha' );
  15472. if ( useWorldUnits ) {
  15473. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15474. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15475. // Find the closest points on the view ray and the line segment
  15476. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15477. const lineDir = worldEnd.sub( worldStart );
  15478. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15479. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15480. const p2 = rayEnd.mul( params.y );
  15481. const delta = p1.sub( p2 );
  15482. const len = delta.length();
  15483. const norm = len.div( materialLineWidth );
  15484. if ( ! useDash ) {
  15485. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15486. const dnorm = norm.fwidth();
  15487. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15488. } else {
  15489. norm.greaterThan( 0.5 ).discard();
  15490. }
  15491. }
  15492. } else {
  15493. // round endcaps
  15494. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15495. const a = vUv.x;
  15496. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15497. const len2 = a.mul( a ).add( b.mul( b ) );
  15498. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15499. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15500. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15501. } );
  15502. } else {
  15503. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15504. const a = vUv.x;
  15505. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15506. const len2 = a.mul( a ).add( b.mul( b ) );
  15507. len2.greaterThan( 1.0 ).discard();
  15508. } );
  15509. }
  15510. }
  15511. let lineColorNode;
  15512. if ( this.lineColorNode ) {
  15513. lineColorNode = this.lineColorNode;
  15514. } else {
  15515. if ( useColor ) {
  15516. const instanceColorStart = attribute( 'instanceColorStart' );
  15517. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15518. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15519. lineColorNode = instanceColor.mul( materialColor );
  15520. } else {
  15521. lineColorNode = materialColor;
  15522. }
  15523. }
  15524. return vec4( lineColorNode, alpha );
  15525. } )();
  15526. if ( this.transparent ) {
  15527. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15528. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15529. }
  15530. super.setup( builder );
  15531. }
  15532. /**
  15533. * Whether the lines should sized in world units or not.
  15534. * When set to `false` the unit is pixel.
  15535. *
  15536. * @type {boolean}
  15537. * @default false
  15538. */
  15539. get worldUnits() {
  15540. return this._useWorldUnits;
  15541. }
  15542. set worldUnits( value ) {
  15543. if ( this._useWorldUnits !== value ) {
  15544. this._useWorldUnits = value;
  15545. this.needsUpdate = true;
  15546. }
  15547. }
  15548. /**
  15549. * Whether the lines should be dashed or not.
  15550. *
  15551. * @type {boolean}
  15552. * @default false
  15553. */
  15554. get dashed() {
  15555. return this._useDash;
  15556. }
  15557. set dashed( value ) {
  15558. if ( this._useDash !== value ) {
  15559. this._useDash = value;
  15560. this.needsUpdate = true;
  15561. }
  15562. }
  15563. /**
  15564. * Whether alpha to coverage should be used or not.
  15565. *
  15566. * @type {boolean}
  15567. * @default true
  15568. */
  15569. get alphaToCoverage() {
  15570. return this._useAlphaToCoverage;
  15571. }
  15572. set alphaToCoverage( value ) {
  15573. if ( this._useAlphaToCoverage !== value ) {
  15574. this._useAlphaToCoverage = value;
  15575. this.needsUpdate = true;
  15576. }
  15577. }
  15578. }
  15579. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  15580. /**
  15581. * Node material version of {@link MeshNormalMaterial}.
  15582. *
  15583. * @augments NodeMaterial
  15584. */
  15585. class MeshNormalNodeMaterial extends NodeMaterial {
  15586. static get type() {
  15587. return 'MeshNormalNodeMaterial';
  15588. }
  15589. /**
  15590. * Constructs a new mesh normal node material.
  15591. *
  15592. * @param {Object} [parameters] - The configuration parameter.
  15593. */
  15594. constructor( parameters ) {
  15595. super();
  15596. /**
  15597. * This flag can be used for type testing.
  15598. *
  15599. * @type {boolean}
  15600. * @readonly
  15601. * @default true
  15602. */
  15603. this.isMeshNormalNodeMaterial = true;
  15604. this.setDefaultValues( _defaultValues$a );
  15605. this.setValues( parameters );
  15606. }
  15607. /**
  15608. * Overwrites the default implementation by computing the diffuse color
  15609. * based on the normal data.
  15610. */
  15611. setupDiffuseColor() {
  15612. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15613. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  15614. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  15615. }
  15616. }
  15617. /**
  15618. * TSL function for creating an equirect uv node.
  15619. *
  15620. * Can be used to compute texture coordinates for projecting an
  15621. * equirectangular texture onto a mesh for using it as the scene's
  15622. * background.
  15623. *
  15624. * ```js
  15625. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  15626. * ```
  15627. *
  15628. * @tsl
  15629. * @function
  15630. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15631. * @returns {Node<vec2>}
  15632. */
  15633. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15634. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15635. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15636. return vec2( u, v );
  15637. } );
  15638. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  15639. /**
  15640. * This class represents a cube render target. It is a special version
  15641. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15642. *
  15643. * @augments WebGLCubeRenderTarget
  15644. */
  15645. class CubeRenderTarget extends WebGLCubeRenderTarget {
  15646. /**
  15647. * Constructs a new cube render target.
  15648. *
  15649. * @param {number} [size=1] - The size of the render target.
  15650. * @param {RenderTarget~Options} [options] - The configuration object.
  15651. */
  15652. constructor( size = 1, options = {} ) {
  15653. super( size, options );
  15654. /**
  15655. * This flag can be used for type testing.
  15656. *
  15657. * @type {boolean}
  15658. * @readonly
  15659. * @default true
  15660. */
  15661. this.isCubeRenderTarget = true;
  15662. }
  15663. /**
  15664. * Converts the given equirectangular texture to a cube map.
  15665. *
  15666. * @param {Renderer} renderer - The renderer.
  15667. * @param {Texture} texture - The equirectangular texture.
  15668. * @return {CubeRenderTarget} A reference to this cube render target.
  15669. */
  15670. fromEquirectangularTexture( renderer, texture$1 ) {
  15671. const currentMinFilter = texture$1.minFilter;
  15672. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15673. texture$1.generateMipmaps = true;
  15674. this.texture.type = texture$1.type;
  15675. this.texture.colorSpace = texture$1.colorSpace;
  15676. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15677. this.texture.minFilter = texture$1.minFilter;
  15678. this.texture.magFilter = texture$1.magFilter;
  15679. const geometry = new BoxGeometry( 5, 5, 5 );
  15680. const uvNode = equirectUV( positionWorldDirection );
  15681. const material = new NodeMaterial();
  15682. material.colorNode = texture( texture$1, uvNode, 0 );
  15683. material.side = BackSide;
  15684. material.blending = NoBlending;
  15685. const mesh = new Mesh( geometry, material );
  15686. const scene = new Scene();
  15687. scene.add( mesh );
  15688. // Avoid blurred poles
  15689. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15690. const camera = new CubeCamera( 1, 10, this );
  15691. const currentMRT = renderer.getMRT();
  15692. renderer.setMRT( null );
  15693. camera.update( renderer, scene );
  15694. renderer.setMRT( currentMRT );
  15695. texture$1.minFilter = currentMinFilter;
  15696. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15697. mesh.geometry.dispose();
  15698. mesh.material.dispose();
  15699. return this;
  15700. }
  15701. }
  15702. const _cache$1 = new WeakMap();
  15703. /**
  15704. * This node can be used to automatically convert environment maps in the
  15705. * equirectangular format into the cube map format.
  15706. *
  15707. * @augments TempNode
  15708. */
  15709. class CubeMapNode extends TempNode {
  15710. static get type() {
  15711. return 'CubeMapNode';
  15712. }
  15713. /**
  15714. * Constructs a new cube map node.
  15715. *
  15716. * @param {Node} envNode - The node representing the environment map.
  15717. */
  15718. constructor( envNode ) {
  15719. super( 'vec3' );
  15720. /**
  15721. * The node representing the environment map.
  15722. *
  15723. * @type {Node}
  15724. */
  15725. this.envNode = envNode;
  15726. /**
  15727. * A reference to the internal cube texture.
  15728. *
  15729. * @private
  15730. * @type {?CubeTexture}
  15731. * @default null
  15732. */
  15733. this._cubeTexture = null;
  15734. /**
  15735. * A reference to the internal cube texture node.
  15736. *
  15737. * @private
  15738. * @type {CubeTextureNode}
  15739. */
  15740. this._cubeTextureNode = cubeTexture( null );
  15741. const defaultTexture = new CubeTexture();
  15742. defaultTexture.isRenderTargetTexture = true;
  15743. /**
  15744. * A default cube texture that acts as a placeholder.
  15745. * It is used when the conversion from equirectangular to cube
  15746. * map has not finished yet for a given texture.
  15747. *
  15748. * @private
  15749. * @type {CubeTexture}
  15750. */
  15751. this._defaultTexture = defaultTexture;
  15752. /**
  15753. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  15754. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15755. *
  15756. * @type {string}
  15757. * @default 'render'
  15758. */
  15759. this.updateBeforeType = NodeUpdateType.RENDER;
  15760. }
  15761. updateBefore( frame ) {
  15762. const { renderer, material } = frame;
  15763. const envNode = this.envNode;
  15764. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15765. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15766. if ( texture && texture.isTexture ) {
  15767. const mapping = texture.mapping;
  15768. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15769. // check for converted cubemap map
  15770. if ( _cache$1.has( texture ) ) {
  15771. const cubeMap = _cache$1.get( texture );
  15772. mapTextureMapping( cubeMap, texture.mapping );
  15773. this._cubeTexture = cubeMap;
  15774. } else {
  15775. // create cube map from equirectangular map
  15776. const image = texture.image;
  15777. if ( isEquirectangularMapReady$1( image ) ) {
  15778. const renderTarget = new CubeRenderTarget( image.height );
  15779. renderTarget.fromEquirectangularTexture( renderer, texture );
  15780. mapTextureMapping( renderTarget.texture, texture.mapping );
  15781. this._cubeTexture = renderTarget.texture;
  15782. _cache$1.set( texture, renderTarget.texture );
  15783. texture.addEventListener( 'dispose', onTextureDispose );
  15784. } else {
  15785. // default cube texture as fallback when equirectangular texture is not yet loaded
  15786. this._cubeTexture = this._defaultTexture;
  15787. }
  15788. }
  15789. //
  15790. this._cubeTextureNode.value = this._cubeTexture;
  15791. } else {
  15792. // envNode already refers to a cube map
  15793. this._cubeTextureNode = this.envNode;
  15794. }
  15795. }
  15796. }
  15797. }
  15798. setup( builder ) {
  15799. this.updateBefore( builder );
  15800. return this._cubeTextureNode;
  15801. }
  15802. }
  15803. /**
  15804. * Returns true if the given equirectangular image has been fully loaded
  15805. * and is ready for further processing.
  15806. *
  15807. * @private
  15808. * @param {Image} image - The equirectangular image to check.
  15809. * @return {boolean} Whether the image is ready or not.
  15810. */
  15811. function isEquirectangularMapReady$1( image ) {
  15812. if ( image === null || image === undefined ) return false;
  15813. return image.height > 0;
  15814. }
  15815. /**
  15816. * This function is executed when `dispose()` is called on the equirectangular
  15817. * texture. In this case, the generated cube map with its render target
  15818. * is deleted as well.
  15819. *
  15820. * @private
  15821. * @param {Object} event - The event object.
  15822. */
  15823. function onTextureDispose( event ) {
  15824. const texture = event.target;
  15825. texture.removeEventListener( 'dispose', onTextureDispose );
  15826. const renderTarget = _cache$1.get( texture );
  15827. if ( renderTarget !== undefined ) {
  15828. _cache$1.delete( texture );
  15829. renderTarget.dispose();
  15830. }
  15831. }
  15832. /**
  15833. * This function makes sure the generated cube map uses the correct
  15834. * texture mapping that corresponds to the equirectangular original.
  15835. *
  15836. * @private
  15837. * @param {Texture} texture - The cube texture.
  15838. * @param {number} mapping - The original texture mapping.
  15839. */
  15840. function mapTextureMapping( texture, mapping ) {
  15841. if ( mapping === EquirectangularReflectionMapping ) {
  15842. texture.mapping = CubeReflectionMapping;
  15843. } else if ( mapping === EquirectangularRefractionMapping ) {
  15844. texture.mapping = CubeRefractionMapping;
  15845. }
  15846. }
  15847. /**
  15848. * TSL function for creating a cube map node.
  15849. *
  15850. * @tsl
  15851. * @function
  15852. * @param {Node} envNode - The node representing the environment map.
  15853. * @returns {CubeMapNode}
  15854. */
  15855. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15856. /**
  15857. * Represents a basic model for Image-based lighting (IBL). The environment
  15858. * is defined via environment maps in the equirectangular or cube map format.
  15859. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15860. * or {@link MeshPhongNodeMaterial}.
  15861. *
  15862. * @augments LightingNode
  15863. */
  15864. class BasicEnvironmentNode extends LightingNode {
  15865. static get type() {
  15866. return 'BasicEnvironmentNode';
  15867. }
  15868. /**
  15869. * Constructs a new basic environment node.
  15870. *
  15871. * @param {Node} [envNode=null] - A node representing the environment.
  15872. */
  15873. constructor( envNode = null ) {
  15874. super();
  15875. /**
  15876. * A node representing the environment.
  15877. *
  15878. * @type {Node}
  15879. * @default null
  15880. */
  15881. this.envNode = envNode;
  15882. }
  15883. setup( builder ) {
  15884. // environment property is used in the finish() method of BasicLightingModel
  15885. builder.context.environment = cubeMapNode( this.envNode );
  15886. }
  15887. }
  15888. /**
  15889. * A specific version of {@link IrradianceNode} that is only relevant
  15890. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15891. * requires a special scaling factor for the light map.
  15892. *
  15893. * @augments LightingNode
  15894. */
  15895. class BasicLightMapNode extends LightingNode {
  15896. static get type() {
  15897. return 'BasicLightMapNode';
  15898. }
  15899. /**
  15900. * Constructs a new basic light map node.
  15901. *
  15902. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15903. */
  15904. constructor( lightMapNode = null ) {
  15905. super();
  15906. /**
  15907. * The light map node.
  15908. *
  15909. * @type {?Node<vec3>}
  15910. */
  15911. this.lightMapNode = lightMapNode;
  15912. }
  15913. setup( builder ) {
  15914. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15915. const RECIPROCAL_PI = float( 1 / Math.PI );
  15916. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15917. }
  15918. }
  15919. /**
  15920. * Abstract class for implementing lighting models. The module defines
  15921. * multiple methods that concrete lighting models can implement. These
  15922. * methods are executed at different points during the light evaluation
  15923. * process.
  15924. */
  15925. class LightingModel {
  15926. /**
  15927. * This method is intended for setting up lighting model and context data
  15928. * which are later used in the evaluation process.
  15929. *
  15930. * @abstract
  15931. * @param {NodeBuilder} builder - The current node builder.
  15932. */
  15933. start( builder ) {
  15934. // lights ( direct )
  15935. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15936. // indirect
  15937. this.indirect( builder );
  15938. }
  15939. /**
  15940. * This method is intended for executing final tasks like final updates
  15941. * to the outgoing light.
  15942. *
  15943. * @abstract
  15944. * @param {NodeBuilder} builder - The current node builder.
  15945. */
  15946. finish( /*builder*/ ) { }
  15947. /**
  15948. * This method is intended for implementing the direct light term and
  15949. * executed during the build process of directional, point and spot light nodes.
  15950. *
  15951. * @abstract
  15952. * @param {Object} lightData - The light data.
  15953. * @param {NodeBuilder} builder - The current node builder.
  15954. */
  15955. direct( /*lightData, builder*/ ) { }
  15956. /**
  15957. * This method is intended for implementing the direct light term for
  15958. * rect area light nodes.
  15959. *
  15960. * @abstract
  15961. * @param {Object} lightData - The light data.
  15962. * @param {NodeBuilder} builder - The current node builder.
  15963. */
  15964. directRectArea( /*lightData, builder*/ ) {}
  15965. /**
  15966. * This method is intended for implementing the indirect light term.
  15967. *
  15968. * @abstract
  15969. * @param {NodeBuilder} builder - The current node builder.
  15970. */
  15971. indirect( /*builder*/ ) { }
  15972. /**
  15973. * This method is intended for implementing the ambient occlusion term.
  15974. * Unlike other methods, this method must be called manually by the lighting
  15975. * model in its indirect term.
  15976. *
  15977. * @abstract
  15978. * @param {NodeBuilder} builder - The current node builder.
  15979. */
  15980. ambientOcclusion( /*input, stack, builder*/ ) { }
  15981. }
  15982. /**
  15983. * Represents the lighting model for unlit materials. The only light contribution
  15984. * is baked indirect lighting modulated with ambient occlusion and the material's
  15985. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  15986. *
  15987. * @augments LightingModel
  15988. */
  15989. class BasicLightingModel extends LightingModel {
  15990. /**
  15991. * Constructs a new basic lighting model.
  15992. */
  15993. constructor() {
  15994. super();
  15995. }
  15996. /**
  15997. * Implements the baked indirect lighting with its modulation.
  15998. *
  15999. * @param {NodeBuilder} builder - The current node builder.
  16000. */
  16001. indirect( { context } ) {
  16002. const ambientOcclusion = context.ambientOcclusion;
  16003. const reflectedLight = context.reflectedLight;
  16004. const irradianceLightMap = context.irradianceLightMap;
  16005. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  16006. // accumulation (baked indirect lighting only)
  16007. if ( irradianceLightMap ) {
  16008. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  16009. } else {
  16010. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  16011. }
  16012. // modulation
  16013. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16014. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  16015. }
  16016. /**
  16017. * Implements the environment mapping.
  16018. *
  16019. * @param {NodeBuilder} builder - The current node builder.
  16020. */
  16021. finish( builder ) {
  16022. const { material, context } = builder;
  16023. const outgoingLight = context.outgoingLight;
  16024. const envNode = builder.context.environment;
  16025. if ( envNode ) {
  16026. switch ( material.combine ) {
  16027. case MultiplyOperation:
  16028. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  16029. break;
  16030. case MixOperation:
  16031. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  16032. break;
  16033. case AddOperation:
  16034. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  16035. break;
  16036. default:
  16037. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  16038. break;
  16039. }
  16040. }
  16041. }
  16042. }
  16043. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  16044. /**
  16045. * Node material version of {@link MeshBasicMaterial}.
  16046. *
  16047. * @augments NodeMaterial
  16048. */
  16049. class MeshBasicNodeMaterial extends NodeMaterial {
  16050. static get type() {
  16051. return 'MeshBasicNodeMaterial';
  16052. }
  16053. /**
  16054. * Constructs a new mesh basic node material.
  16055. *
  16056. * @param {Object} [parameters] - The configuration parameter.
  16057. */
  16058. constructor( parameters ) {
  16059. super();
  16060. /**
  16061. * This flag can be used for type testing.
  16062. *
  16063. * @type {boolean}
  16064. * @readonly
  16065. * @default true
  16066. */
  16067. this.isMeshBasicNodeMaterial = true;
  16068. /**
  16069. * Although the basic material is by definition unlit, we set
  16070. * this property to `true` since we use a lighting model to compute
  16071. * the outgoing light of the fragment shader.
  16072. *
  16073. * @type {boolean}
  16074. * @default true
  16075. */
  16076. this.lights = true;
  16077. this.setDefaultValues( _defaultValues$9 );
  16078. this.setValues( parameters );
  16079. }
  16080. /**
  16081. * Basic materials are not affected by normal and bump maps so we
  16082. * return by default {@link normalViewGeometry}.
  16083. *
  16084. * @return {Node<vec3>} The normal node.
  16085. */
  16086. setupNormal() {
  16087. return directionToFaceDirection( normalViewGeometry ); // see #28839
  16088. }
  16089. /**
  16090. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16091. * to implement the default environment mapping.
  16092. *
  16093. * @param {NodeBuilder} builder - The current node builder.
  16094. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16095. */
  16096. setupEnvironment( builder ) {
  16097. const envNode = super.setupEnvironment( builder );
  16098. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16099. }
  16100. /**
  16101. * This method must be overwritten since light maps are evaluated
  16102. * with a special scaling factor for basic materials.
  16103. *
  16104. * @param {NodeBuilder} builder - The current node builder.
  16105. * @return {?BasicLightMapNode<vec3>} The light map node.
  16106. */
  16107. setupLightMap( builder ) {
  16108. let node = null;
  16109. if ( builder.material.lightMap ) {
  16110. node = new BasicLightMapNode( materialLightMap );
  16111. }
  16112. return node;
  16113. }
  16114. /**
  16115. * The material overwrites this method because `lights` is set to `true` but
  16116. * we still want to return the diffuse color as the outgoing light.
  16117. *
  16118. * @return {Node<vec3>} The outgoing light node.
  16119. */
  16120. setupOutgoingLight() {
  16121. return diffuseColor.rgb;
  16122. }
  16123. /**
  16124. * Setups the lighting model.
  16125. *
  16126. * @return {BasicLightingModel} The lighting model.
  16127. */
  16128. setupLightingModel() {
  16129. return new BasicLightingModel();
  16130. }
  16131. }
  16132. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  16133. // Original approximation by Christophe Schlick '94
  16134. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  16135. // Optimized variant (presented by Epic at SIGGRAPH '13)
  16136. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  16137. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  16138. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  16139. } ); // validated
  16140. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  16141. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  16142. } ); // validated
  16143. const G_BlinnPhong_Implicit = () => float( 0.25 );
  16144. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  16145. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  16146. } );
  16147. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16148. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16149. const dotNH = normalView.dot( halfDir ).clamp();
  16150. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16151. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  16152. const G = G_BlinnPhong_Implicit();
  16153. const D = D_BlinnPhong( { dotNH } );
  16154. return F.mul( G ).mul( D );
  16155. } );
  16156. /**
  16157. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  16158. *
  16159. * @augments BasicLightingModel
  16160. */
  16161. class PhongLightingModel extends BasicLightingModel {
  16162. /**
  16163. * Constructs a new phong lighting model.
  16164. *
  16165. * @param {boolean} [specular=true] - Whether specular is supported or not.
  16166. */
  16167. constructor( specular = true ) {
  16168. super();
  16169. /**
  16170. * Whether specular is supported or not. Set this to `false` if you are
  16171. * looking for a Lambert-like material meaning a material for non-shiny
  16172. * surfaces, without specular highlights.
  16173. *
  16174. * @type {boolean}
  16175. * @default true
  16176. */
  16177. this.specular = specular;
  16178. }
  16179. /**
  16180. * Implements the direct lighting. The specular portion is optional an can be controlled
  16181. * with the {@link PhongLightingModel#specular} flag.
  16182. *
  16183. * @param {Object} lightData - The light data.
  16184. */
  16185. direct( { lightDirection, lightColor, reflectedLight } ) {
  16186. const dotNL = normalView.dot( lightDirection ).clamp();
  16187. const irradiance = dotNL.mul( lightColor );
  16188. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16189. if ( this.specular === true ) {
  16190. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  16191. }
  16192. }
  16193. /**
  16194. * Implements the indirect lighting.
  16195. *
  16196. * @param {NodeBuilder} builder - The current node builder.
  16197. */
  16198. indirect( builder ) {
  16199. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  16200. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16201. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16202. }
  16203. }
  16204. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  16205. /**
  16206. * Node material version of {@link MeshLambertMaterial}.
  16207. *
  16208. * @augments NodeMaterial
  16209. */
  16210. class MeshLambertNodeMaterial extends NodeMaterial {
  16211. static get type() {
  16212. return 'MeshLambertNodeMaterial';
  16213. }
  16214. /**
  16215. * Constructs a new mesh lambert node material.
  16216. *
  16217. * @param {Object} [parameters] - The configuration parameter.
  16218. */
  16219. constructor( parameters ) {
  16220. super();
  16221. /**
  16222. * This flag can be used for type testing.
  16223. *
  16224. * @type {boolean}
  16225. * @readonly
  16226. * @default true
  16227. */
  16228. this.isMeshLambertNodeMaterial = true;
  16229. /**
  16230. * Set to `true` because lambert materials react on lights.
  16231. *
  16232. * @type {boolean}
  16233. * @default true
  16234. */
  16235. this.lights = true;
  16236. this.setDefaultValues( _defaultValues$8 );
  16237. this.setValues( parameters );
  16238. }
  16239. /**
  16240. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16241. * to implement the default environment mapping.
  16242. *
  16243. * @param {NodeBuilder} builder - The current node builder.
  16244. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16245. */
  16246. setupEnvironment( builder ) {
  16247. const envNode = super.setupEnvironment( builder );
  16248. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16249. }
  16250. /**
  16251. * Setups the lighting model.
  16252. *
  16253. * @return {PhongLightingModel} The lighting model.
  16254. */
  16255. setupLightingModel( /*builder*/ ) {
  16256. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  16257. }
  16258. }
  16259. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  16260. /**
  16261. * Node material version of {@link MeshPhongMaterial}.
  16262. *
  16263. * @augments NodeMaterial
  16264. */
  16265. class MeshPhongNodeMaterial extends NodeMaterial {
  16266. static get type() {
  16267. return 'MeshPhongNodeMaterial';
  16268. }
  16269. /**
  16270. * Constructs a new mesh lambert node material.
  16271. *
  16272. * @param {Object} [parameters] - The configuration parameter.
  16273. */
  16274. constructor( parameters ) {
  16275. super();
  16276. /**
  16277. * This flag can be used for type testing.
  16278. *
  16279. * @type {boolean}
  16280. * @readonly
  16281. * @default true
  16282. */
  16283. this.isMeshPhongNodeMaterial = true;
  16284. /**
  16285. * Set to `true` because phong materials react on lights.
  16286. *
  16287. * @type {boolean}
  16288. * @default true
  16289. */
  16290. this.lights = true;
  16291. /**
  16292. * The shininess of phong materials is by default inferred from the `shininess`
  16293. * property. This node property allows to overwrite the default
  16294. * and define the shininess with a node instead.
  16295. *
  16296. * If you don't want to overwrite the shininess but modify the existing
  16297. * value instead, use {@link materialShininess}.
  16298. *
  16299. * @type {?Node<float>}
  16300. * @default null
  16301. */
  16302. this.shininessNode = null;
  16303. /**
  16304. * The specular color of phong materials is by default inferred from the
  16305. * `specular` property. This node property allows to overwrite the default
  16306. * and define the specular color with a node instead.
  16307. *
  16308. * If you don't want to overwrite the specular color but modify the existing
  16309. * value instead, use {@link materialSpecular}.
  16310. *
  16311. * @type {?Node<vec3>}
  16312. * @default null
  16313. */
  16314. this.specularNode = null;
  16315. this.setDefaultValues( _defaultValues$7 );
  16316. this.setValues( parameters );
  16317. }
  16318. /**
  16319. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16320. * to implement the default environment mapping.
  16321. *
  16322. * @param {NodeBuilder} builder - The current node builder.
  16323. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16324. */
  16325. setupEnvironment( builder ) {
  16326. const envNode = super.setupEnvironment( builder );
  16327. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16328. }
  16329. /**
  16330. * Setups the lighting model.
  16331. *
  16332. * @return {PhongLightingModel} The lighting model.
  16333. */
  16334. setupLightingModel( /*builder*/ ) {
  16335. return new PhongLightingModel();
  16336. }
  16337. /**
  16338. * Setups the phong specific node variables.
  16339. *
  16340. * @param {NodeBuilder} builder - The current node builder.
  16341. */
  16342. setupVariants( /*builder*/ ) {
  16343. // SHININESS
  16344. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16345. shininess.assign( shininessNode );
  16346. // SPECULAR COLOR
  16347. const specularNode = this.specularNode || materialSpecular;
  16348. specularColor.assign( specularNode );
  16349. }
  16350. copy( source ) {
  16351. this.shininessNode = source.shininessNode;
  16352. this.specularNode = source.specularNode;
  16353. return super.copy( source );
  16354. }
  16355. }
  16356. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16357. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16358. return float( 0 );
  16359. }
  16360. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16361. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16362. return geometryRoughness;
  16363. } );
  16364. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16365. const { roughness } = inputs;
  16366. const geometryRoughness = getGeometryRoughness();
  16367. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16368. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16369. roughnessFactor = roughnessFactor.min( 1.0 );
  16370. return roughnessFactor;
  16371. } );
  16372. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16373. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16374. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16375. const a2 = alpha.pow2();
  16376. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16377. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16378. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16379. } ).setLayout( {
  16380. name: 'V_GGX_SmithCorrelated',
  16381. type: 'float',
  16382. inputs: [
  16383. { name: 'alpha', type: 'float' },
  16384. { name: 'dotNL', type: 'float' },
  16385. { name: 'dotNV', type: 'float' }
  16386. ]
  16387. } ); // validated
  16388. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16389. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16390. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16391. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16392. const v = div( 0.5, gv.add( gl ) );
  16393. return v;
  16394. } ).setLayout( {
  16395. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16396. type: 'float',
  16397. inputs: [
  16398. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16399. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16400. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16401. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16402. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16403. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16404. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16405. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16406. ]
  16407. } );
  16408. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  16409. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  16410. // alpha is "roughness squared" in Disney’s reparameterization
  16411. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  16412. const a2 = alpha.pow2();
  16413. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  16414. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  16415. } ).setLayout( {
  16416. name: 'D_GGX',
  16417. type: 'float',
  16418. inputs: [
  16419. { name: 'alpha', type: 'float' },
  16420. { name: 'dotNH', type: 'float' }
  16421. ]
  16422. } ); // validated
  16423. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  16424. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16425. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  16426. const a2 = alphaT.mul( alphaB );
  16427. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  16428. const v2 = v.dot( v );
  16429. const w2 = a2.div( v2 );
  16430. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  16431. } ).setLayout( {
  16432. name: 'D_GGX_Anisotropic',
  16433. type: 'float',
  16434. inputs: [
  16435. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16436. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16437. { name: 'dotNH', type: 'float', qualifier: 'in' },
  16438. { name: 'dotTH', type: 'float', qualifier: 'in' },
  16439. { name: 'dotBH', type: 'float', qualifier: 'in' }
  16440. ]
  16441. } );
  16442. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  16443. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16444. const alpha = roughness.pow2(); // UE4's roughness
  16445. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16446. const dotNL = normalView$1.dot( lightDirection ).clamp();
  16447. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16448. const dotNH = normalView$1.dot( halfDir ).clamp();
  16449. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16450. let F = F_Schlick( { f0, f90, dotVH } );
  16451. let V, D;
  16452. if ( defined( USE_IRIDESCENCE ) ) {
  16453. F = iridescence.mix( F, f );
  16454. }
  16455. if ( defined( USE_ANISOTROPY ) ) {
  16456. const dotTL = anisotropyT.dot( lightDirection );
  16457. const dotTV = anisotropyT.dot( positionViewDirection );
  16458. const dotTH = anisotropyT.dot( halfDir );
  16459. const dotBL = anisotropyB.dot( lightDirection );
  16460. const dotBV = anisotropyB.dot( positionViewDirection );
  16461. const dotBH = anisotropyB.dot( halfDir );
  16462. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16463. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16464. } else {
  16465. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16466. D = D_GGX( { alpha, dotNH } );
  16467. }
  16468. return F.mul( V ).mul( D );
  16469. } ); // validated
  16470. /**
  16471. * Precomputed DFG LUT for Image-Based Lighting
  16472. * Resolution: 32x32
  16473. * Samples: 4096 per texel
  16474. * Format: RG16F (2 half floats per texel: scale, bias)
  16475. */
  16476. const DATA = new Uint16Array( [
  16477. 0x2cd9, 0x3b64, 0x2d0e, 0x3b43, 0x2e20, 0x3aa7, 0x3061, 0x39fb, 0x325e, 0x397c, 0x3454, 0x3908, 0x357d, 0x3893, 0x3698, 0x381e, 0x379d, 0x375b, 0x3845, 0x3689, 0x38af, 0x35ca, 0x390d, 0x351e, 0x395f, 0x3484, 0x39a8, 0x33f9, 0x39e6, 0x330a, 0x3a1c, 0x3239, 0x3a4b, 0x3183, 0x3a73, 0x30e5, 0x3a95, 0x305b, 0x3ab1, 0x2fc6, 0x3ac9, 0x2ef7, 0x3ade, 0x2e43, 0x3aee, 0x2da7, 0x3afc, 0x2d1f, 0x3b07, 0x2ca9, 0x3b10, 0x2c42, 0x3b17, 0x2bd1, 0x3b1c, 0x2b34, 0x3b1f, 0x2aaa, 0x3b22, 0x2a31, 0x3b23, 0x29c7, 0x3b23, 0x2968,
  16478. 0x32d4, 0x3a4b, 0x32dc, 0x3a45, 0x3308, 0x3a26, 0x3378, 0x39d0, 0x3425, 0x394a, 0x34c9, 0x38be, 0x359c, 0x383e, 0x3688, 0x3796, 0x3778, 0x36c4, 0x382f, 0x3603, 0x3898, 0x3553, 0x38f7, 0x34b3, 0x394b, 0x3424, 0x3994, 0x334c, 0x39d3, 0x326c, 0x3a08, 0x31a9, 0x3a35, 0x30fe, 0x3a5a, 0x306a, 0x3a78, 0x2fd1, 0x3a90, 0x2ef1, 0x3aa2, 0x2e2e, 0x3ab0, 0x2d86, 0x3aba, 0x2cf3, 0x3ac1, 0x2c74, 0x3ac4, 0x2c05, 0x3ac4, 0x2b49, 0x3ac2, 0x2aa1, 0x3abd, 0x2a0c, 0x3ab7, 0x298b, 0x3aaf, 0x2918, 0x3aa6, 0x28b3, 0x3a9b, 0x285a,
  16479. 0x3559, 0x3954, 0x355a, 0x3951, 0x3566, 0x3944, 0x3582, 0x391e, 0x35b6, 0x38d3, 0x360a, 0x386a, 0x3684, 0x37ed, 0x3720, 0x370d, 0x37d3, 0x3641, 0x3847, 0x3588, 0x38a3, 0x34e2, 0x38fa, 0x344d, 0x3948, 0x3391, 0x398d, 0x32a6, 0x39c8, 0x31d6, 0x39fa, 0x3121, 0x3a22, 0x3082, 0x3a43, 0x2ff0, 0x3a5c, 0x2f01, 0x3a6f, 0x2e32, 0x3a7c, 0x2d7e, 0x3a84, 0x2ce2, 0x3a87, 0x2c5b, 0x3a87, 0x2bcc, 0x3a83, 0x2b00, 0x3a7b, 0x2a4e, 0x3a71, 0x29b3, 0x3a66, 0x292c, 0x3a58, 0x28b4, 0x3a4b, 0x284b, 0x3a3d, 0x27dc, 0x3a2e, 0x2739,
  16480. 0x3709, 0x387c, 0x370a, 0x387b, 0x3710, 0x3874, 0x3720, 0x385f, 0x373d, 0x3834, 0x376a, 0x37e1, 0x37ac, 0x3732, 0x3805, 0x3675, 0x383f, 0x35bc, 0x3883, 0x3511, 0x38cb, 0x3476, 0x3912, 0x33d8, 0x3955, 0x32e2, 0x3991, 0x3208, 0x39c6, 0x3149, 0x39f1, 0x30a1, 0x3a15, 0x300f, 0x3a30, 0x2f21, 0x3a44, 0x2e45, 0x3a51, 0x2d87, 0x3a59, 0x2ce2, 0x3a5b, 0x2c53, 0x3a58, 0x2bb0, 0x3a52, 0x2ada, 0x3a49, 0x2a1f, 0x3a40, 0x297d, 0x3a34, 0x28f0, 0x3a25, 0x2874, 0x3a13, 0x2807, 0x3a00, 0x274e, 0x39eb, 0x26a6, 0x39d5, 0x2611,
  16481. 0x3840, 0x3780, 0x3840, 0x377e, 0x3842, 0x3776, 0x3846, 0x375e, 0x384f, 0x372a, 0x385b, 0x36d3, 0x386c, 0x3659, 0x3885, 0x35c7, 0x38a8, 0x352d, 0x38d4, 0x3497, 0x3906, 0x340c, 0x393b, 0x331a, 0x3970, 0x323a, 0x39a0, 0x3172, 0x39cb, 0x30c3, 0x39ef, 0x302a, 0x3a0c, 0x2f4a, 0x3a21, 0x2e63, 0x3a2f, 0x2d9b, 0x3a37, 0x2ced, 0x3a39, 0x2c57, 0x3a37, 0x2baa, 0x3a34, 0x2ac9, 0x3a2c, 0x2a05, 0x3a20, 0x295d, 0x3a11, 0x28ca, 0x39ff, 0x2849, 0x39eb, 0x27b2, 0x39d5, 0x26ed, 0x39be, 0x2640, 0x39a5, 0x25aa, 0x398b, 0x2523,
  16482. 0x38e2, 0x363b, 0x38e2, 0x363b, 0x38e3, 0x3635, 0x38e6, 0x3626, 0x38ea, 0x3606, 0x38f0, 0x35cd, 0x38f8, 0x3579, 0x3903, 0x350e, 0x3915, 0x3495, 0x392d, 0x3418, 0x394c, 0x3340, 0x3970, 0x3261, 0x3995, 0x3197, 0x39b8, 0x30e4, 0x39d8, 0x3046, 0x39f3, 0x2f76, 0x3a08, 0x2e86, 0x3a16, 0x2db5, 0x3a1e, 0x2cff, 0x3a22, 0x2c61, 0x3a24, 0x2bb3, 0x3a20, 0x2ac7, 0x3a17, 0x29fc, 0x3a0a, 0x294c, 0x39fa, 0x28b2, 0x39e7, 0x282e, 0x39d1, 0x2773, 0x39b9, 0x26a9, 0x399f, 0x25fa, 0x3985, 0x255f, 0x3968, 0x24d6, 0x394a, 0x245d,
  16483. 0x396e, 0x3524, 0x396e, 0x3524, 0x396e, 0x3520, 0x396f, 0x3517, 0x3971, 0x3502, 0x3973, 0x34dd, 0x3975, 0x34a5, 0x3978, 0x3458, 0x397e, 0x33f9, 0x3987, 0x3332, 0x3997, 0x326b, 0x39aa, 0x31ac, 0x39c0, 0x30fb, 0x39d7, 0x305c, 0x39eb, 0x2f9e, 0x39fc, 0x2ea7, 0x3a07, 0x2dcf, 0x3a0f, 0x2d13, 0x3a16, 0x2c70, 0x3a17, 0x2bc4, 0x3a14, 0x2ad0, 0x3a0a, 0x29fc, 0x39fd, 0x2945, 0x39ed, 0x28a6, 0x39d9, 0x281d, 0x39c2, 0x274a, 0x39a9, 0x267c, 0x398e, 0x25c7, 0x3971, 0x2528, 0x3952, 0x249e, 0x3931, 0x2425, 0x3910, 0x2374,
  16484. 0x39e5, 0x3436, 0x39e5, 0x3435, 0x39e5, 0x3434, 0x39e5, 0x342e, 0x39e5, 0x3420, 0x39e5, 0x3408, 0x39e3, 0x33c4, 0x39e1, 0x3359, 0x39df, 0x32d3, 0x39de, 0x323a, 0x39e1, 0x319a, 0x39e7, 0x30fb, 0x39f0, 0x3065, 0x39f9, 0x2fb6, 0x3a02, 0x2ec0, 0x3a08, 0x2de6, 0x3a0d, 0x2d26, 0x3a12, 0x2c7e, 0x3a13, 0x2bda, 0x3a0e, 0x2adc, 0x3a05, 0x2a02, 0x39f8, 0x2945, 0x39e7, 0x28a1, 0x39d3, 0x2813, 0x39bc, 0x2730, 0x39a2, 0x265c, 0x3985, 0x25a3, 0x3966, 0x2501, 0x3945, 0x2475, 0x3923, 0x23f3, 0x3901, 0x231c, 0x38dd, 0x225e,
  16485. 0x3a4b, 0x32d6, 0x3a4a, 0x32d6, 0x3a4a, 0x32d4, 0x3a4a, 0x32cc, 0x3a48, 0x32bb, 0x3a47, 0x329d, 0x3a43, 0x326b, 0x3a3d, 0x3222, 0x3a36, 0x31c2, 0x3a2e, 0x314f, 0x3a28, 0x30d2, 0x3a23, 0x3052, 0x3a20, 0x2fab, 0x3a1e, 0x2ec2, 0x3a1b, 0x2def, 0x3a19, 0x2d31, 0x3a1a, 0x2c89, 0x3a18, 0x2beb, 0x3a11, 0x2aea, 0x3a07, 0x2a0a, 0x39fa, 0x2948, 0x39e9, 0x28a1, 0x39d4, 0x280f, 0x39bd, 0x2721, 0x39a2, 0x2647, 0x3985, 0x258b, 0x3964, 0x24e5, 0x3942, 0x2455, 0x391f, 0x23b3, 0x38fb, 0x22d8, 0x38d4, 0x2219, 0x38ad, 0x2172,
  16486. 0x3aa0, 0x3180, 0x3aa0, 0x3180, 0x3aa0, 0x317f, 0x3a9f, 0x317b, 0x3a9d, 0x3170, 0x3a99, 0x315d, 0x3a95, 0x313d, 0x3a8d, 0x310c, 0x3a82, 0x30ca, 0x3a76, 0x3077, 0x3a69, 0x3019, 0x3a5c, 0x2f68, 0x3a4f, 0x2e9e, 0x3a42, 0x2dde, 0x3a37, 0x2d2b, 0x3a30, 0x2c89, 0x3a29, 0x2bef, 0x3a1f, 0x2af0, 0x3a12, 0x2a0f, 0x3a03, 0x294a, 0x39f1, 0x28a0, 0x39dc, 0x280c, 0x39c5, 0x2717, 0x39a9, 0x2638, 0x398b, 0x2578, 0x396a, 0x24d0, 0x3947, 0x243f, 0x3923, 0x2380, 0x38fc, 0x22a4, 0x38d4, 0x21e4, 0x38ac, 0x213c, 0x3883, 0x20a8,
  16487. 0x3ae8, 0x3062, 0x3ae8, 0x3062, 0x3ae7, 0x3061, 0x3ae6, 0x305f, 0x3ae4, 0x305a, 0x3ae0, 0x304f, 0x3ada, 0x303b, 0x3ad1, 0x301b, 0x3ac5, 0x2fdd, 0x3ab6, 0x2f6a, 0x3aa4, 0x2ede, 0x3a91, 0x2e45, 0x3a7c, 0x2da5, 0x3a67, 0x2d0a, 0x3a57, 0x2c77, 0x3a48, 0x2bdc, 0x3a38, 0x2ae5, 0x3a27, 0x2a0a, 0x3a16, 0x2947, 0x3a02, 0x289d, 0x39eb, 0x2808, 0x39d3, 0x270d, 0x39b6, 0x262b, 0x3997, 0x256a, 0x3976, 0x24bf, 0x3952, 0x242b, 0x392d, 0x2358, 0x3904, 0x227a, 0x38db, 0x21b8, 0x38b2, 0x2110, 0x3887, 0x207d, 0x385b, 0x1ff6,
  16488. 0x3b23, 0x2ee8, 0x3b23, 0x2ee8, 0x3b22, 0x2ee8, 0x3b21, 0x2ee7, 0x3b1f, 0x2ee3, 0x3b1a, 0x2ed6, 0x3b14, 0x2ec1, 0x3b0b, 0x2e99, 0x3afe, 0x2e60, 0x3aee, 0x2e12, 0x3ad8, 0x2dad, 0x3ac1, 0x2d3d, 0x3aa5, 0x2cc3, 0x3a8b, 0x2c48, 0x3a76, 0x2ba2, 0x3a60, 0x2ac0, 0x3a49, 0x29f2, 0x3a32, 0x2938, 0x3a1b, 0x2893, 0x3a02, 0x27ff, 0x39e8, 0x26ff, 0x39ca, 0x261e, 0x39aa, 0x255b, 0x3988, 0x24b0, 0x3964, 0x241c, 0x393d, 0x2336, 0x3913, 0x2257, 0x38e9, 0x2195, 0x38be, 0x20eb, 0x3891, 0x2059, 0x3864, 0x1fae, 0x3837, 0x1ecd,
  16489. 0x3b54, 0x2d61, 0x3b54, 0x2d61, 0x3b53, 0x2d61, 0x3b52, 0x2d62, 0x3b4f, 0x2d61, 0x3b4b, 0x2d5c, 0x3b45, 0x2d51, 0x3b3b, 0x2d3d, 0x3b2e, 0x2d1a, 0x3b1d, 0x2ce7, 0x3b06, 0x2ca3, 0x3aeb, 0x2c52, 0x3acb, 0x2bee, 0x3ab0, 0x2b31, 0x3a94, 0x2a74, 0x3a77, 0x29bf, 0x3a5a, 0x2915, 0x3a3f, 0x287a, 0x3a22, 0x27de, 0x3a05, 0x26e4, 0x39e5, 0x2609, 0x39c3, 0x2547, 0x39a0, 0x249f, 0x397b, 0x240c, 0x3953, 0x2314, 0x3928, 0x2238, 0x38fd, 0x2175, 0x38d0, 0x20cb, 0x38a2, 0x2038, 0x3873, 0x1f71, 0x3844, 0x1e90, 0x3815, 0x1dce,
  16490. 0x3b7c, 0x2c22, 0x3b7c, 0x2c22, 0x3b7b, 0x2c23, 0x3b7a, 0x2c25, 0x3b77, 0x2c27, 0x3b73, 0x2c26, 0x3b6d, 0x2c23, 0x3b64, 0x2c1a, 0x3b57, 0x2c07, 0x3b46, 0x2bd1, 0x3b2e, 0x2b79, 0x3b0f, 0x2b07, 0x3aef, 0x2a86, 0x3ad1, 0x29f8, 0x3ab0, 0x2967, 0x3a8e, 0x28d7, 0x3a6d, 0x284e, 0x3a4c, 0x279f, 0x3a2b, 0x26b7, 0x3a08, 0x25e5, 0x39e4, 0x252c, 0x39be, 0x2488, 0x3998, 0x23f0, 0x396f, 0x22f2, 0x3943, 0x2215, 0x3917, 0x2155, 0x38e8, 0x20ae, 0x38b9, 0x201c, 0x3888, 0x1f38, 0x3857, 0x1e5a, 0x3826, 0x1d9a, 0x37eb, 0x1cf0,
  16491. 0x3b9c, 0x2a43, 0x3b9c, 0x2a43, 0x3b9b, 0x2a46, 0x3b9a, 0x2a4a, 0x3b98, 0x2a50, 0x3b93, 0x2a54, 0x3b8e, 0x2a59, 0x3b85, 0x2a56, 0x3b79, 0x2a45, 0x3b67, 0x2a24, 0x3b4f, 0x29ee, 0x3b2f, 0x29a4, 0x3b10, 0x294b, 0x3aef, 0x28e5, 0x3ac9, 0x2877, 0x3aa4, 0x2809, 0x3a7e, 0x2739, 0x3a59, 0x266d, 0x3a34, 0x25af, 0x3a0c, 0x2503, 0x39e4, 0x2468, 0x39bb, 0x23bb, 0x3990, 0x22c6, 0x3963, 0x21f0, 0x3936, 0x2133, 0x3906, 0x208f, 0x38d5, 0x1ffd, 0x38a3, 0x1f04, 0x3870, 0x1e28, 0x383d, 0x1d69, 0x380b, 0x1cc3, 0x37b0, 0x1c32,
  16492. 0x3bb5, 0x28aa, 0x3bb5, 0x28ab, 0x3bb5, 0x28ad, 0x3bb4, 0x28b2, 0x3bb2, 0x28b9, 0x3bae, 0x28c2, 0x3ba8, 0x28ca, 0x3ba0, 0x28d1, 0x3b94, 0x28cd, 0x3b83, 0x28c1, 0x3b6a, 0x28a3, 0x3b4b, 0x2876, 0x3b2d, 0x283d, 0x3b09, 0x27ea, 0x3ae1, 0x274b, 0x3ab9, 0x26a6, 0x3a8f, 0x25fe, 0x3a67, 0x255d, 0x3a3d, 0x24c5, 0x3a11, 0x2439, 0x39e6, 0x2371, 0x39b9, 0x228d, 0x398a, 0x21c1, 0x395a, 0x210b, 0x3929, 0x206c, 0x38f7, 0x1fc1, 0x38c3, 0x1ecb, 0x388f, 0x1df6, 0x385a, 0x1d3a, 0x3825, 0x1c99, 0x37e1, 0x1c08, 0x3779, 0x1b1b,
  16493. 0x3bc9, 0x26d3, 0x3bc9, 0x26d4, 0x3bc9, 0x26d9, 0x3bc8, 0x26e3, 0x3bc6, 0x26ef, 0x3bc2, 0x2705, 0x3bbd, 0x271a, 0x3bb6, 0x2731, 0x3baa, 0x273c, 0x3b9a, 0x273d, 0x3b81, 0x2726, 0x3b65, 0x26f7, 0x3b46, 0x26af, 0x3b20, 0x2650, 0x3af7, 0x25e1, 0x3acd, 0x256a, 0x3aa1, 0x24eb, 0x3a75, 0x246f, 0x3a46, 0x23ee, 0x3a17, 0x230d, 0x39e9, 0x223e, 0x39b7, 0x2183, 0x3985, 0x20d8, 0x3953, 0x2043, 0x391e, 0x1f7a, 0x38e9, 0x1e8d, 0x38b3, 0x1dbf, 0x387c, 0x1d0b, 0x3845, 0x1c6c, 0x380e, 0x1bc4, 0x37b0, 0x1ad2, 0x3745, 0x19fd,
  16494. 0x3bd9, 0x24e4, 0x3bd9, 0x24e5, 0x3bd9, 0x24e8, 0x3bd8, 0x24f2, 0x3bd5, 0x24fe, 0x3bd2, 0x2512, 0x3bce, 0x252b, 0x3bc6, 0x2544, 0x3bbc, 0x255a, 0x3bac, 0x256b, 0x3b93, 0x2569, 0x3b7a, 0x2557, 0x3b5b, 0x252f, 0x3b34, 0x24f7, 0x3b0c, 0x24ad, 0x3adf, 0x2458, 0x3ab1, 0x23f8, 0x3a82, 0x233f, 0x3a4f, 0x2286, 0x3a1e, 0x21d5, 0x39eb, 0x2130, 0x39b6, 0x2098, 0x3982, 0x200e, 0x394b, 0x1f25, 0x3914, 0x1e45, 0x38dc, 0x1d83, 0x38a3, 0x1cd6, 0x386b, 0x1c3d, 0x3831, 0x1b71, 0x37f2, 0x1a87, 0x3782, 0x19bc, 0x3714, 0x1909,
  16495. 0x3be5, 0x22d8, 0x3be5, 0x22d9, 0x3be4, 0x22df, 0x3be4, 0x22ef, 0x3be1, 0x2305, 0x3bde, 0x232a, 0x3bda, 0x2358, 0x3bd4, 0x2392, 0x3bcb, 0x23ca, 0x3bbb, 0x23f4, 0x3ba3, 0x2405, 0x3b8c, 0x2405, 0x3b6c, 0x23ec, 0x3b47, 0x23ae, 0x3b1d, 0x2353, 0x3af0, 0x22e2, 0x3ac0, 0x2261, 0x3a8e, 0x21d9, 0x3a5a, 0x214e, 0x3a26, 0x20c7, 0x39ee, 0x2045, 0x39b7, 0x1f97, 0x397f, 0x1eba, 0x3945, 0x1df0, 0x390b, 0x1d3a, 0x38d0, 0x1c9a, 0x3895, 0x1c0a, 0x385a, 0x1b18, 0x381f, 0x1a39, 0x37c9, 0x1975, 0x3756, 0x18cc, 0x36e6, 0x1836,
  16496. 0x3bed, 0x20a8, 0x3bed, 0x20a9, 0x3bed, 0x20ae, 0x3bed, 0x20bb, 0x3beb, 0x20cf, 0x3be8, 0x20ef, 0x3be4, 0x2119, 0x3bde, 0x214f, 0x3bd6, 0x2189, 0x3bc6, 0x21b8, 0x3bb1, 0x21de, 0x3b9a, 0x21f2, 0x3b7b, 0x21f2, 0x3b57, 0x21d8, 0x3b2d, 0x21a4, 0x3b00, 0x215f, 0x3acf, 0x2108, 0x3a99, 0x20a8, 0x3a64, 0x2043, 0x3a2c, 0x1fba, 0x39f2, 0x1ef3, 0x39b8, 0x1e36, 0x397c, 0x1d86, 0x3940, 0x1ce5, 0x3903, 0x1c52, 0x38c6, 0x1b9e, 0x3888, 0x1ab3, 0x384a, 0x19e4, 0x380e, 0x192b, 0x37a3, 0x188b, 0x372d, 0x17f7, 0x36ba, 0x1701,
  16497. 0x3bf4, 0x1e23, 0x3bf4, 0x1e25, 0x3bf4, 0x1e2d, 0x3bf3, 0x1e41, 0x3bf1, 0x1e64, 0x3bef, 0x1e9c, 0x3beb, 0x1ee1, 0x3be6, 0x1f40, 0x3bde, 0x1fa7, 0x3bce, 0x2001, 0x3bbd, 0x202f, 0x3ba6, 0x204e, 0x3b88, 0x205f, 0x3b64, 0x205b, 0x3b3b, 0x2044, 0x3b0e, 0x201f, 0x3adb, 0x1fcf, 0x3aa6, 0x1f4e, 0x3a6e, 0x1ec1, 0x3a33, 0x1e2b, 0x39f7, 0x1d95, 0x39ba, 0x1d06, 0x397b, 0x1c7d, 0x393c, 0x1bfc, 0x38fc, 0x1b13, 0x38bc, 0x1a40, 0x387c, 0x1983, 0x383c, 0x18da, 0x37fa, 0x1842, 0x377f, 0x177f, 0x3706, 0x1695, 0x3691, 0x15c8,
  16498. 0x3bf8, 0x1bca, 0x3bf8, 0x1bcc, 0x3bf8, 0x1bd8, 0x3bf8, 0x1bf7, 0x3bf6, 0x1c1b, 0x3bf4, 0x1c45, 0x3bf1, 0x1c83, 0x3bec, 0x1cce, 0x3be4, 0x1d21, 0x3bd5, 0x1d78, 0x3bc5, 0x1dd1, 0x3bb0, 0x1e17, 0x3b93, 0x1e4a, 0x3b70, 0x1e5f, 0x3b48, 0x1e57, 0x3b1b, 0x1e35, 0x3ae7, 0x1df6, 0x3ab2, 0x1da4, 0x3a77, 0x1d44, 0x3a3a, 0x1cdb, 0x39fc, 0x1c6e, 0x39bb, 0x1c03, 0x397a, 0x1b35, 0x3938, 0x1a72, 0x38f5, 0x19bb, 0x38b3, 0x1914, 0x3870, 0x187d, 0x382e, 0x17eb, 0x37db, 0x16f9, 0x375c, 0x1621, 0x36e1, 0x1565, 0x3669, 0x14be,
  16499. 0x3bfb, 0x18b9, 0x3bfb, 0x18ba, 0x3bfb, 0x18c3, 0x3bfb, 0x18da, 0x3bf9, 0x190a, 0x3bf7, 0x1948, 0x3bf5, 0x19ac, 0x3bf0, 0x1a20, 0x3be9, 0x1ab3, 0x3bdb, 0x1b49, 0x3bcd, 0x1be6, 0x3bb7, 0x1c34, 0x3b9c, 0x1c6d, 0x3b7a, 0x1c8e, 0x3b54, 0x1c9e, 0x3b26, 0x1c96, 0x3af2, 0x1c75, 0x3abc, 0x1c47, 0x3a80, 0x1c09, 0x3a42, 0x1b85, 0x3a01, 0x1aec, 0x39be, 0x1a50, 0x397a, 0x19b5, 0x3935, 0x1921, 0x38f0, 0x1895, 0x38aa, 0x1814, 0x3866, 0x173a, 0x3821, 0x1665, 0x37be, 0x15a4, 0x373c, 0x14f9, 0x36be, 0x1460, 0x3644, 0x13b3,
  16500. 0x3bfd, 0x156b, 0x3bfd, 0x156c, 0x3bfd, 0x1578, 0x3bfd, 0x1598, 0x3bfc, 0x15dd, 0x3bfa, 0x163c, 0x3bf7, 0x16cb, 0x3bf3, 0x177b, 0x3beb, 0x1833, 0x3be0, 0x18ad, 0x3bd2, 0x192e, 0x3bbd, 0x19a6, 0x3ba4, 0x1a0c, 0x3b83, 0x1a5a, 0x3b5d, 0x1a8c, 0x3b30, 0x1a9b, 0x3afd, 0x1a86, 0x3ac6, 0x1a5c, 0x3a89, 0x1a11, 0x3a49, 0x19b7, 0x3a06, 0x194f, 0x39c1, 0x18e3, 0x397a, 0x1873, 0x3933, 0x1805, 0x38eb, 0x173a, 0x38a3, 0x1676, 0x385c, 0x15bf, 0x3816, 0x1519, 0x37a2, 0x1482, 0x371d, 0x13f7, 0x369c, 0x1306, 0x3620, 0x1231,
  16501. 0x3bff, 0x11cb, 0x3bff, 0x11cd, 0x3bfe, 0x11dd, 0x3bfe, 0x1219, 0x3bfd, 0x126b, 0x3bfb, 0x12e9, 0x3bf9, 0x13c5, 0x3bf5, 0x1460, 0x3bee, 0x150f, 0x3be3, 0x15c9, 0x3bd6, 0x168a, 0x3bc3, 0x174f, 0x3baa, 0x1806, 0x3b8b, 0x184f, 0x3b66, 0x1888, 0x3b39, 0x18a6, 0x3b07, 0x18ad, 0x3acf, 0x189c, 0x3a92, 0x1876, 0x3a50, 0x1840, 0x3a0c, 0x17fd, 0x39c4, 0x176a, 0x397b, 0x16ce, 0x3931, 0x1634, 0x38e6, 0x1599, 0x389c, 0x1508, 0x3852, 0x147f, 0x380a, 0x1401, 0x3788, 0x131c, 0x36ff, 0x124a, 0x367c, 0x1190, 0x35fe, 0x10ea,
  16502. 0x3bff, 0x0daa, 0x3bff, 0x0dad, 0x3bff, 0x0dc0, 0x3bff, 0x0e0e, 0x3bfe, 0x0e87, 0x3bfc, 0x0f14, 0x3bfb, 0x1029, 0x3bf7, 0x10d1, 0x3bf0, 0x11d3, 0x3be6, 0x12c9, 0x3bd9, 0x13fc, 0x3bc7, 0x1499, 0x3bb0, 0x152a, 0x3b92, 0x15ab, 0x3b6e, 0x1615, 0x3b42, 0x165a, 0x3b10, 0x1681, 0x3ad8, 0x1683, 0x3a9a, 0x1665, 0x3a57, 0x1629, 0x3a11, 0x15dd, 0x39c8, 0x1580, 0x397c, 0x1518, 0x3930, 0x14ae, 0x38e3, 0x1441, 0x3896, 0x13b1, 0x384a, 0x12e9, 0x37ff, 0x122f, 0x376f, 0x1182, 0x36e3, 0x10e5, 0x365e, 0x1057, 0x35de, 0x0fac,
  16503. 0x3c00, 0x08ea, 0x3c00, 0x08ed, 0x3c00, 0x0902, 0x3c00, 0x0961, 0x3bff, 0x09f3, 0x3bfd, 0x0abc, 0x3bfb, 0x0c1f, 0x3bf8, 0x0d15, 0x3bf1, 0x0e5b, 0x3be8, 0x0fb4, 0x3bdc, 0x10b0, 0x3bcb, 0x1190, 0x3bb5, 0x126c, 0x3b97, 0x132c, 0x3b74, 0x13de, 0x3b4a, 0x1432, 0x3b18, 0x145e, 0x3ae0, 0x1472, 0x3aa2, 0x146f, 0x3a5f, 0x1456, 0x3a17, 0x142e, 0x39cc, 0x13ee, 0x397e, 0x136b, 0x392f, 0x12e1, 0x38df, 0x124f, 0x3890, 0x11bd, 0x3842, 0x1131, 0x37eb, 0x10ac, 0x3757, 0x102e, 0x36c9, 0x0f76, 0x3640, 0x0ea3, 0x35bf, 0x0de4,
  16504. 0x3c00, 0x039b, 0x3c00, 0x039d, 0x3c00, 0x03b2, 0x3c00, 0x041c, 0x3bff, 0x04be, 0x3bfd, 0x05d6, 0x3bfc, 0x0764, 0x3bf8, 0x08e2, 0x3bf2, 0x0a67, 0x3bea, 0x0c1b, 0x3bde, 0x0d41, 0x3bcd, 0x0e5f, 0x3bb8, 0x0f8c, 0x3b9c, 0x1057, 0x3b7a, 0x10e5, 0x3b51, 0x1155, 0x3b20, 0x11a5, 0x3ae8, 0x11da, 0x3aaa, 0x11ef, 0x3a66, 0x11e5, 0x3a1d, 0x11c1, 0x39d0, 0x1185, 0x3980, 0x113b, 0x392e, 0x10e5, 0x38dc, 0x1087, 0x388b, 0x1028, 0x383b, 0x0f94, 0x37d9, 0x0edb, 0x3741, 0x0e2c, 0x36af, 0x0d89, 0x3625, 0x0cf2, 0x35a1, 0x0c69,
  16505. 0x3c00, 0x0107, 0x3c00, 0x0108, 0x3c00, 0x0110, 0x3c00, 0x0145, 0x3bff, 0x0197, 0x3bfe, 0x0224, 0x3bfc, 0x030c, 0x3bf8, 0x0478, 0x3bf3, 0x062c, 0x3beb, 0x0833, 0x3be0, 0x0979, 0x3bd0, 0x0aeb, 0x3bbc, 0x0c3d, 0x3ba0, 0x0d01, 0x3b80, 0x0dbd, 0x3b57, 0x0e69, 0x3b27, 0x0eeb, 0x3af0, 0x0f53, 0x3ab1, 0x0f8a, 0x3a6c, 0x0f9f, 0x3a22, 0x0f8b, 0x39d4, 0x0f5b, 0x3982, 0x0f0f, 0x392f, 0x0eac, 0x38da, 0x0e3d, 0x3886, 0x0dc9, 0x3834, 0x0d51, 0x37c7, 0x0cd9, 0x372c, 0x0c65, 0x3697, 0x0bef, 0x360a, 0x0b20, 0x3585, 0x0a62,
  16506. 0x3c00, 0x0031, 0x3c00, 0x0031, 0x3c00, 0x0034, 0x3c00, 0x004b, 0x3bff, 0x006f, 0x3bfe, 0x00c9, 0x3bfc, 0x011b, 0x3bf9, 0x0207, 0x3bf4, 0x02d6, 0x3bec, 0x0415, 0x3be1, 0x0587, 0x3bd2, 0x0703, 0x3bbf, 0x087d, 0x3ba5, 0x096a, 0x3b85, 0x0a59, 0x3b5d, 0x0b32, 0x3b2e, 0x0bee, 0x3af7, 0x0c44, 0x3ab8, 0x0c7c, 0x3a73, 0x0c9c, 0x3a28, 0x0ca4, 0x39d8, 0x0c98, 0x3985, 0x0c77, 0x392f, 0x0c4a, 0x38d9, 0x0c10, 0x3882, 0x0ba0, 0x382e, 0x0b14, 0x37b6, 0x0a84, 0x3717, 0x09f5, 0x3680, 0x0969, 0x35f0, 0x08e6, 0x356a, 0x086a,
  16507. 0x3c00, 0x0004, 0x3c00, 0x0004, 0x3c00, 0x0004, 0x3c00, 0x000d, 0x3bff, 0x0021, 0x3bfe, 0x003b, 0x3bfd, 0x0070, 0x3bf9, 0x00c7, 0x3bf4, 0x012e, 0x3bed, 0x01c8, 0x3be3, 0x0274, 0x3bd4, 0x033b, 0x3bc1, 0x043a, 0x3ba8, 0x0534, 0x3b89, 0x0641, 0x3b62, 0x073b, 0x3b34, 0x0815, 0x3afd, 0x087c, 0x3abf, 0x08d0, 0x3a7a, 0x090a, 0x3a2e, 0x092c, 0x39dd, 0x0936, 0x3988, 0x0928, 0x3930, 0x0907, 0x38d7, 0x08d7, 0x387f, 0x089b, 0x3828, 0x0855, 0x37a7, 0x080b, 0x3704, 0x077b, 0x366a, 0x06e1, 0x35d8, 0x0649, 0x3550, 0x05b8,
  16508. 0x3c00, 0x0000, 0x3c00, 0x0000, 0x3c00, 0x0000, 0x3c00, 0x0003, 0x3bff, 0x0012, 0x3bfe, 0x001a, 0x3bfd, 0x0035, 0x3bfa, 0x0050, 0x3bf4, 0x0061, 0x3bed, 0x00a5, 0x3be4, 0x00ee, 0x3bd6, 0x0146, 0x3bc3, 0x01ab, 0x3bab, 0x0211, 0x3b8d, 0x028e, 0x3b67, 0x0303, 0x3b39, 0x0375, 0x3b04, 0x03e2, 0x3ac6, 0x0441, 0x3a80, 0x0492, 0x3a34, 0x04cd, 0x39e1, 0x04f2, 0x398b, 0x0504, 0x3931, 0x0502, 0x38d6, 0x04ec, 0x387c, 0x04c7, 0x3822, 0x0496, 0x3798, 0x045c, 0x36f2, 0x041a, 0x3655, 0x03d5, 0x35c1, 0x038e, 0x3537, 0x0347
  16509. ] );
  16510. let lut = null;
  16511. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16512. if ( lut === null ) {
  16513. lut = new DataTexture( DATA, 32, 32, RGFormat, HalfFloatType );
  16514. lut.minFilter = LinearFilter;
  16515. lut.magFilter = LinearFilter;
  16516. lut.wrapS = ClampToEdgeWrapping;
  16517. lut.wrapT = ClampToEdgeWrapping;
  16518. lut.generateMipmaps = false;
  16519. lut.needsUpdate = true;
  16520. }
  16521. const uv = vec2( roughness, dotNV );
  16522. return texture( lut, uv ).rg;
  16523. } );
  16524. // GGX BRDF with multi-scattering energy compensation for direct lighting
  16525. // This provides more accurate energy conservation, especially for rough materials
  16526. // Based on "Practical Multiple Scattering Compensation for Microfacet Models"
  16527. // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf
  16528. const BRDF_GGX_Multiscatter = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16529. // Single-scattering BRDF (standard GGX)
  16530. const singleScatter = BRDF_GGX( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } );
  16531. // Multi-scattering compensation
  16532. const dotNL = normalView.dot( lightDirection ).clamp();
  16533. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16534. // Precomputed DFG values for view and light directions
  16535. const dfgV = DFGApprox( { roughness: _roughness, dotNV } );
  16536. const dfgL = DFGApprox( { roughness: _roughness, dotNV: dotNL } );
  16537. // Single-scattering energy for view and light
  16538. const FssEss_V = f0.mul( dfgV.x ).add( f90.mul( dfgV.y ) );
  16539. const FssEss_L = f0.mul( dfgL.x ).add( f90.mul( dfgL.y ) );
  16540. const Ess_V = dfgV.x.add( dfgV.y );
  16541. const Ess_L = dfgL.x.add( dfgL.y );
  16542. // Energy lost to multiple scattering
  16543. const Ems_V = float( 1.0 ).sub( Ess_V );
  16544. const Ems_L = float( 1.0 ).sub( Ess_L );
  16545. // Average Fresnel reflectance
  16546. const Favg = f0.add( f0.oneMinus().mul( 0.047619 ) ); // 1/21
  16547. // Multiple scattering contribution
  16548. // Uses geometric mean of view and light contributions for better energy distribution
  16549. 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 ) );
  16550. // Energy compensation factor
  16551. const compensationFactor = Ems_V.mul( Ems_L );
  16552. const multiScatter = Fms.mul( compensationFactor );
  16553. return singleScatter.add( multiScatter );
  16554. } );
  16555. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  16556. const { dotNV, specularColor, specularF90, roughness } = inputs;
  16557. const fab = DFGApprox( { dotNV, roughness } );
  16558. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16559. } );
  16560. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  16561. const x = dotVH.oneMinus().saturate();
  16562. const x2 = x.mul( x );
  16563. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  16564. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  16565. } ).setLayout( {
  16566. name: 'Schlick_to_F0',
  16567. type: 'vec3',
  16568. inputs: [
  16569. { name: 'f', type: 'vec3' },
  16570. { name: 'f90', type: 'float' },
  16571. { name: 'dotVH', type: 'float' }
  16572. ]
  16573. } );
  16574. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16575. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  16576. const alpha = roughness.pow2();
  16577. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  16578. const invAlpha = float( 1.0 ).div( alpha );
  16579. const cos2h = dotNH.pow2();
  16580. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  16581. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  16582. } ).setLayout( {
  16583. name: 'D_Charlie',
  16584. type: 'float',
  16585. inputs: [
  16586. { name: 'roughness', type: 'float' },
  16587. { name: 'dotNH', type: 'float' }
  16588. ]
  16589. } );
  16590. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16591. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  16592. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  16593. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  16594. } ).setLayout( {
  16595. name: 'V_Neubelt',
  16596. type: 'float',
  16597. inputs: [
  16598. { name: 'dotNV', type: 'float' },
  16599. { name: 'dotNL', type: 'float' }
  16600. ]
  16601. } );
  16602. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16603. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16604. const dotNL = normalView.dot( lightDirection ).clamp();
  16605. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16606. const dotNH = normalView.dot( halfDir ).clamp();
  16607. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  16608. const V = V_Neubelt( { dotNV, dotNL } );
  16609. return sheen.mul( D ).mul( V );
  16610. } );
  16611. // Rect Area Light
  16612. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  16613. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  16614. // code: https://github.com/selfshadow/ltc_code/
  16615. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  16616. const LUT_SIZE = 64.0;
  16617. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  16618. const LUT_BIAS = 0.5 / LUT_SIZE;
  16619. const dotNV = N.dot( V ).saturate();
  16620. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  16621. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  16622. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  16623. return uv;
  16624. } ).setLayout( {
  16625. name: 'LTC_Uv',
  16626. type: 'vec2',
  16627. inputs: [
  16628. { name: 'N', type: 'vec3' },
  16629. { name: 'V', type: 'vec3' },
  16630. { name: 'roughness', type: 'float' }
  16631. ]
  16632. } );
  16633. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  16634. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  16635. // An approximation of the form factor of a horizon-clipped rectangle.
  16636. const l = f.length();
  16637. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  16638. } ).setLayout( {
  16639. name: 'LTC_ClippedSphereFormFactor',
  16640. type: 'float',
  16641. inputs: [
  16642. { name: 'f', type: 'vec3' }
  16643. ]
  16644. } );
  16645. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  16646. const x = v1.dot( v2 );
  16647. const y = x.abs().toVar();
  16648. // rational polynomial approximation to theta / sin( theta ) / 2PI
  16649. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  16650. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  16651. const v = a.div( b );
  16652. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  16653. return v1.cross( v2 ).mul( theta_sintheta );
  16654. } ).setLayout( {
  16655. name: 'LTC_EdgeVectorFormFactor',
  16656. type: 'vec3',
  16657. inputs: [
  16658. { name: 'v1', type: 'vec3' },
  16659. { name: 'v2', type: 'vec3' }
  16660. ]
  16661. } );
  16662. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  16663. // bail if point is on back side of plane of light
  16664. // assumes ccw winding order of light vertices
  16665. const v1 = p1.sub( p0 ).toVar();
  16666. const v2 = p3.sub( p0 ).toVar();
  16667. const lightNormal = v1.cross( v2 );
  16668. const result = vec3().toVar();
  16669. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16670. // construct orthonormal basis around N
  16671. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  16672. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  16673. // compute transform
  16674. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  16675. // transform rect
  16676. // & project rect onto sphere
  16677. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  16678. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  16679. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  16680. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  16681. // calculate vector form factor
  16682. const vectorFormFactor = vec3( 0 ).toVar();
  16683. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16684. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16685. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16686. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16687. // adjust for horizon clipping
  16688. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  16689. } );
  16690. return result;
  16691. } ).setLayout( {
  16692. name: 'LTC_Evaluate',
  16693. type: 'vec3',
  16694. inputs: [
  16695. { name: 'N', type: 'vec3' },
  16696. { name: 'V', type: 'vec3' },
  16697. { name: 'P', type: 'vec3' },
  16698. { name: 'mInv', type: 'mat3' },
  16699. { name: 'p0', type: 'vec3' },
  16700. { name: 'p1', type: 'vec3' },
  16701. { name: 'p2', type: 'vec3' },
  16702. { name: 'p3', type: 'vec3' }
  16703. ]
  16704. } );
  16705. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16706. // bail if point is on back side of plane of light
  16707. // assumes ccw winding order of light vertices
  16708. const v1 = p1.sub( p0 ).toVar();
  16709. const v2 = p3.sub( p0 ).toVar();
  16710. const lightNormal = v1.cross( v2 );
  16711. const result = vec3().toVar();
  16712. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16713. // transform rect
  16714. // & project rect onto sphere
  16715. const coords0 = p0.sub( P ).normalize().toVar();
  16716. const coords1 = p1.sub( P ).normalize().toVar();
  16717. const coords2 = p2.sub( P ).normalize().toVar();
  16718. const coords3 = p3.sub( P ).normalize().toVar();
  16719. // calculate vector form factor
  16720. const vectorFormFactor = vec3( 0 ).toVar();
  16721. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16722. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16723. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16724. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16725. // adjust for horizon clipping
  16726. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16727. } );
  16728. return result;
  16729. } ).setLayout( {
  16730. name: 'LTC_Evaluate',
  16731. type: 'vec3',
  16732. inputs: [
  16733. { name: 'P', type: 'vec3' },
  16734. { name: 'p0', type: 'vec3' },
  16735. { name: 'p1', type: 'vec3' },
  16736. { name: 'p2', type: 'vec3' },
  16737. { name: 'p3', type: 'vec3' }
  16738. ]
  16739. } );
  16740. // Mipped Bicubic Texture Filtering by N8
  16741. // https://www.shadertoy.com/view/Dl2SDW
  16742. const bC = 1.0 / 6.0;
  16743. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  16744. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  16745. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  16746. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  16747. const g0 = ( a ) => w0( a ).add( w1( a ) );
  16748. const g1 = ( a ) => w2( a ).add( w3( a ) );
  16749. // h0 and h1 are the two offset functions
  16750. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  16751. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  16752. const bicubic = ( textureNode, texelSize, lod ) => {
  16753. const uv = textureNode.uvNode;
  16754. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  16755. const iuv = floor( uvScaled );
  16756. const fuv = fract( uvScaled );
  16757. const g0x = g0( fuv.x );
  16758. const g1x = g1( fuv.x );
  16759. const h0x = h0( fuv.x );
  16760. const h1x = h1( fuv.x );
  16761. const h0y = h0( fuv.y );
  16762. const h1y = h1( fuv.y );
  16763. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16764. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16765. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16766. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16767. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  16768. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  16769. return a.add( b );
  16770. };
  16771. /**
  16772. * Applies mipped bicubic texture filtering to the given texture node.
  16773. *
  16774. * @tsl
  16775. * @function
  16776. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16777. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  16778. * @return {Node} The filtered texture sample.
  16779. */
  16780. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  16781. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  16782. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  16783. const fLodSizeInv = div( 1.0, fLodSize );
  16784. const cLodSizeInv = div( 1.0, cLodSize );
  16785. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  16786. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  16787. return fract( lodNode ).mix( fSample, cSample );
  16788. } );
  16789. /**
  16790. * Applies mipped bicubic texture filtering to the given texture node.
  16791. *
  16792. * @tsl
  16793. * @function
  16794. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16795. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  16796. * @return {Node} The filtered texture sample.
  16797. */
  16798. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  16799. const lod = strength.mul( maxMipLevel( textureNode ) );
  16800. return textureBicubicLevel( textureNode, lod );
  16801. } );
  16802. //
  16803. // Transmission
  16804. //
  16805. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  16806. // Direction of refracted light.
  16807. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  16808. // Compute rotation-independent scaling of the model matrix.
  16809. const modelScale = vec3(
  16810. length( modelMatrix[ 0 ].xyz ),
  16811. length( modelMatrix[ 1 ].xyz ),
  16812. length( modelMatrix[ 2 ].xyz )
  16813. );
  16814. // The thickness is specified in local space.
  16815. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  16816. } ).setLayout( {
  16817. name: 'getVolumeTransmissionRay',
  16818. type: 'vec3',
  16819. inputs: [
  16820. { name: 'n', type: 'vec3' },
  16821. { name: 'v', type: 'vec3' },
  16822. { name: 'thickness', type: 'float' },
  16823. { name: 'ior', type: 'float' },
  16824. { name: 'modelMatrix', type: 'mat4' }
  16825. ]
  16826. } );
  16827. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16828. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16829. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16830. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16831. } ).setLayout( {
  16832. name: 'applyIorToRoughness',
  16833. type: 'float',
  16834. inputs: [
  16835. { name: 'roughness', type: 'float' },
  16836. { name: 'ior', type: 'float' }
  16837. ]
  16838. } );
  16839. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16840. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16841. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16842. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16843. const transmissionSample = vTexture.sample( fragCoord );
  16844. //const transmissionSample = viewportMipTexture( fragCoord );
  16845. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16846. return textureBicubicLevel( transmissionSample, lod );
  16847. } );
  16848. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16849. If( attenuationDistance.notEqual( 0 ), () => {
  16850. // Compute light attenuation using Beer's law.
  16851. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16852. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16853. return transmittance;
  16854. } );
  16855. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16856. return vec3( 1.0 );
  16857. } ).setLayout( {
  16858. name: 'volumeAttenuation',
  16859. type: 'vec3',
  16860. inputs: [
  16861. { name: 'transmissionDistance', type: 'float' },
  16862. { name: 'attenuationColor', type: 'vec3' },
  16863. { name: 'attenuationDistance', type: 'float' }
  16864. ]
  16865. } );
  16866. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16867. let transmittedLight, transmittance;
  16868. if ( dispersion ) {
  16869. transmittedLight = vec4().toVar();
  16870. transmittance = vec3().toVar();
  16871. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16872. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16873. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16874. const ior = iors.element( i );
  16875. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16876. const refractedRayExit = position.add( transmissionRay );
  16877. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16878. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16879. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16880. refractionCoords.addAssign( 1.0 );
  16881. refractionCoords.divAssign( 2.0 );
  16882. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16883. // Sample framebuffer to get pixel the refracted ray hits.
  16884. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16885. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16886. transmittedLight.a.addAssign( transmissionSample.a );
  16887. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16888. } );
  16889. transmittedLight.a.divAssign( 3.0 );
  16890. } else {
  16891. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16892. const refractedRayExit = position.add( transmissionRay );
  16893. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16894. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16895. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16896. refractionCoords.addAssign( 1.0 );
  16897. refractionCoords.divAssign( 2.0 );
  16898. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16899. // Sample framebuffer to get pixel the refracted ray hits.
  16900. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16901. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16902. }
  16903. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16904. const dotNV = n.dot( v ).clamp();
  16905. // Get the specular component.
  16906. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16907. dotNV,
  16908. specularColor,
  16909. specularF90,
  16910. roughness
  16911. } ) );
  16912. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16913. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16914. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16915. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16916. } );
  16917. //
  16918. // Iridescence
  16919. //
  16920. // XYZ to linear-sRGB color space
  16921. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16922. 3.2404542, -0.969266, 0.0556434,
  16923. -1.5371385, 1.8760108, -0.2040259,
  16924. -0.4985314, 0.0415560, 1.0572252
  16925. );
  16926. // Assume air interface for top
  16927. // Note: We don't handle the case fresnel0 == 1
  16928. const Fresnel0ToIor = ( fresnel0 ) => {
  16929. const sqrtF0 = fresnel0.sqrt();
  16930. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16931. };
  16932. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16933. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16934. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16935. };
  16936. // Fresnel equations for dielectric/dielectric interfaces.
  16937. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16938. // Evaluation XYZ sensitivity curves in Fourier space
  16939. const evalSensitivity = ( OPD, shift ) => {
  16940. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16941. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  16942. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  16943. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  16944. 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() );
  16945. 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() );
  16946. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  16947. const rgb = XYZ_TO_REC709.mul( xyz );
  16948. return rgb;
  16949. };
  16950. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  16951. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  16952. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  16953. // Evaluate the cosTheta on the base layer (Snell law)
  16954. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  16955. // Handle TIR:
  16956. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  16957. If( cosTheta2Sq.lessThan( 0 ), () => {
  16958. return vec3( 1.0 );
  16959. } );
  16960. const cosTheta2 = cosTheta2Sq.sqrt();
  16961. // First interface
  16962. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  16963. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  16964. //const R21 = R12;
  16965. const T121 = R12.oneMinus();
  16966. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  16967. const phi21 = float( Math.PI ).sub( phi12 );
  16968. // Second interface
  16969. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  16970. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  16971. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  16972. const phi23 = vec3(
  16973. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16974. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16975. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  16976. );
  16977. // Phase shift
  16978. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  16979. const phi = vec3( phi21 ).add( phi23 );
  16980. // Compound terms
  16981. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  16982. const r123 = R123.sqrt();
  16983. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  16984. // Reflectance term for m = 0 (DC term amplitude)
  16985. const C0 = R12.add( Rs );
  16986. const I = C0.toVar();
  16987. // Reflectance term for m > 0 (pairs of diracs)
  16988. const Cm = Rs.sub( T121 ).toVar();
  16989. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  16990. Cm.mulAssign( r123 );
  16991. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  16992. I.addAssign( Cm.mul( Sm ) );
  16993. } );
  16994. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  16995. return I.max( vec3( 0.0 ) );
  16996. } ).setLayout( {
  16997. name: 'evalIridescence',
  16998. type: 'vec3',
  16999. inputs: [
  17000. { name: 'outsideIOR', type: 'float' },
  17001. { name: 'eta2', type: 'float' },
  17002. { name: 'cosTheta1', type: 'float' },
  17003. { name: 'thinFilmThickness', type: 'float' },
  17004. { name: 'baseF0', type: 'vec3' }
  17005. ]
  17006. } );
  17007. //
  17008. // Sheen
  17009. //
  17010. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  17011. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF".
  17012. // The low roughness fit (< 0.25) uses an inversesqrt/log model to accurately capture the sharp peak.
  17013. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  17014. const dotNV = normal.dot( viewDir ).saturate();
  17015. const r2 = roughness.mul( roughness );
  17016. const a = roughness.lessThan( 0.25 ).select(
  17017. inverseSqrt( roughness ).mul( -1.57 ),
  17018. r2.mul( -3.33 ).add( roughness.mul( 6.27 ) ).sub( 4.40 )
  17019. );
  17020. const b = roughness.lessThan( 0.25 ).select(
  17021. log( roughness ).mul( -0.46 ).sub( 0.64 ),
  17022. r2.mul( 0.92 ).sub( roughness.mul( 1.79 ) ).add( 0.35 )
  17023. );
  17024. const DG = a.mul( dotNV ).add( b ).exp();
  17025. return DG.saturate();
  17026. } );
  17027. const clearcoatF0 = vec3( 0.04 );
  17028. const clearcoatF90 = float( 1 );
  17029. /**
  17030. * Represents the lighting model for a PBR material.
  17031. *
  17032. * @augments LightingModel
  17033. */
  17034. class PhysicalLightingModel extends LightingModel {
  17035. /**
  17036. * Constructs a new physical lighting model.
  17037. *
  17038. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17039. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17040. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17041. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17042. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17043. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17044. */
  17045. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  17046. super();
  17047. /**
  17048. * Whether clearcoat is supported or not.
  17049. *
  17050. * @type {boolean}
  17051. * @default false
  17052. */
  17053. this.clearcoat = clearcoat;
  17054. /**
  17055. * Whether sheen is supported or not.
  17056. *
  17057. * @type {boolean}
  17058. * @default false
  17059. */
  17060. this.sheen = sheen;
  17061. /**
  17062. * Whether iridescence is supported or not.
  17063. *
  17064. * @type {boolean}
  17065. * @default false
  17066. */
  17067. this.iridescence = iridescence;
  17068. /**
  17069. * Whether anisotropy is supported or not.
  17070. *
  17071. * @type {boolean}
  17072. * @default false
  17073. */
  17074. this.anisotropy = anisotropy;
  17075. /**
  17076. * Whether transmission is supported or not.
  17077. *
  17078. * @type {boolean}
  17079. * @default false
  17080. */
  17081. this.transmission = transmission;
  17082. /**
  17083. * Whether dispersion is supported or not.
  17084. *
  17085. * @type {boolean}
  17086. * @default false
  17087. */
  17088. this.dispersion = dispersion;
  17089. /**
  17090. * The clear coat radiance.
  17091. *
  17092. * @type {?Node}
  17093. * @default null
  17094. */
  17095. this.clearcoatRadiance = null;
  17096. /**
  17097. * The clear coat specular direct.
  17098. *
  17099. * @type {?Node}
  17100. * @default null
  17101. */
  17102. this.clearcoatSpecularDirect = null;
  17103. /**
  17104. * The clear coat specular indirect.
  17105. *
  17106. * @type {?Node}
  17107. * @default null
  17108. */
  17109. this.clearcoatSpecularIndirect = null;
  17110. /**
  17111. * The sheen specular direct.
  17112. *
  17113. * @type {?Node}
  17114. * @default null
  17115. */
  17116. this.sheenSpecularDirect = null;
  17117. /**
  17118. * The sheen specular indirect.
  17119. *
  17120. * @type {?Node}
  17121. * @default null
  17122. */
  17123. this.sheenSpecularIndirect = null;
  17124. /**
  17125. * The iridescence Fresnel.
  17126. *
  17127. * @type {?Node}
  17128. * @default null
  17129. */
  17130. this.iridescenceFresnel = null;
  17131. /**
  17132. * The iridescence F0.
  17133. *
  17134. * @type {?Node}
  17135. * @default null
  17136. */
  17137. this.iridescenceF0 = null;
  17138. /**
  17139. * The iridescence F0 dielectric.
  17140. *
  17141. * @type {?Node}
  17142. * @default null
  17143. */
  17144. this.iridescenceF0Dielectric = null;
  17145. /**
  17146. * The iridescence F0 metallic.
  17147. *
  17148. * @type {?Node}
  17149. * @default null
  17150. */
  17151. this.iridescenceF0Metallic = null;
  17152. }
  17153. /**
  17154. * Depending on what features are requested, the method prepares certain node variables
  17155. * which are later used for lighting computations.
  17156. *
  17157. * @param {NodeBuilder} builder - The current node builder.
  17158. */
  17159. start( builder ) {
  17160. if ( this.clearcoat === true ) {
  17161. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  17162. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  17163. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  17164. }
  17165. if ( this.sheen === true ) {
  17166. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  17167. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  17168. }
  17169. if ( this.iridescence === true ) {
  17170. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  17171. const iridescenceFresnelDielectric = evalIridescence( {
  17172. outsideIOR: float( 1.0 ),
  17173. eta2: iridescenceIOR,
  17174. cosTheta1: dotNVi,
  17175. thinFilmThickness: iridescenceThickness,
  17176. baseF0: specularColor
  17177. } );
  17178. const iridescenceFresnelMetallic = evalIridescence( {
  17179. outsideIOR: float( 1.0 ),
  17180. eta2: iridescenceIOR,
  17181. cosTheta1: dotNVi,
  17182. thinFilmThickness: iridescenceThickness,
  17183. baseF0: diffuseColor.rgb
  17184. } );
  17185. this.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, metalness );
  17186. this.iridescenceF0Dielectric = Schlick_to_F0( { f: iridescenceFresnelDielectric, f90: 1.0, dotVH: dotNVi } );
  17187. this.iridescenceF0Metallic = Schlick_to_F0( { f: iridescenceFresnelMetallic, f90: 1.0, dotVH: dotNVi } );
  17188. this.iridescenceF0 = mix( this.iridescenceF0Dielectric, this.iridescenceF0Metallic, metalness );
  17189. }
  17190. if ( this.transmission === true ) {
  17191. const position = positionWorld;
  17192. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  17193. const n = normalWorld;
  17194. const context = builder.context;
  17195. context.backdrop = getIBLVolumeRefraction(
  17196. n,
  17197. v,
  17198. roughness,
  17199. diffuseContribution,
  17200. specularColorBlended,
  17201. specularF90, // specularF90
  17202. position, // positionWorld
  17203. modelWorldMatrix, // modelMatrix
  17204. cameraViewMatrix, // viewMatrix
  17205. cameraProjectionMatrix, // projMatrix
  17206. ior,
  17207. thickness,
  17208. attenuationColor,
  17209. attenuationDistance,
  17210. this.dispersion ? dispersion : null
  17211. );
  17212. context.backdropAlpha = transmission;
  17213. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  17214. }
  17215. super.start( builder );
  17216. }
  17217. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  17218. // Approximates multi-scattering in order to preserve energy.
  17219. // http://www.jcgt.org/published/0008/01/03/
  17220. computeMultiscattering( singleScatter, multiScatter, specularF90, f0, iridescenceF0 = null ) {
  17221. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17222. const fab = DFGApprox( { roughness, dotNV } );
  17223. const Fr = iridescenceF0 ? iridescence.mix( f0, iridescenceF0 ) : f0;
  17224. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17225. const Ess = fab.x.add( fab.y );
  17226. const Ems = Ess.oneMinus();
  17227. const Favg = Fr.add( Fr.oneMinus().mul( 0.047619 ) ); // 1/21
  17228. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  17229. singleScatter.addAssign( FssEss );
  17230. multiScatter.addAssign( Fms.mul( Ems ) );
  17231. }
  17232. /**
  17233. * Implements the direct light.
  17234. *
  17235. * @param {Object} lightData - The light data.
  17236. * @param {NodeBuilder} builder - The current node builder.
  17237. */
  17238. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  17239. const dotNL = normalView.dot( lightDirection ).clamp();
  17240. const irradiance = dotNL.mul( lightColor ).toVar();
  17241. if ( this.sheen === true ) {
  17242. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  17243. const sheenAlbedoV = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17244. const sheenAlbedoL = IBLSheenBRDF( { normal: normalView, viewDir: lightDirection, roughness: sheenRoughness } );
  17245. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedoV.max( sheenAlbedoL ) ).oneMinus();
  17246. irradiance.mulAssign( sheenEnergyComp );
  17247. }
  17248. if ( this.clearcoat === true ) {
  17249. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  17250. const ccIrradiance = dotNLcc.mul( lightColor );
  17251. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  17252. }
  17253. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ) );
  17254. 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 } ) ) );
  17255. }
  17256. /**
  17257. * This method is intended for implementing the direct light term for
  17258. * rect area light nodes.
  17259. *
  17260. * @param {Object} input - The input data.
  17261. * @param {NodeBuilder} builder - The current node builder.
  17262. */
  17263. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  17264. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17265. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17266. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17267. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17268. const N = normalView;
  17269. const V = positionViewDirection;
  17270. const P = positionView.toVar();
  17271. const uv = LTC_Uv( { N, V, roughness } );
  17272. const t1 = ltc_1.sample( uv ).toVar();
  17273. const t2 = ltc_2.sample( uv ).toVar();
  17274. const mInv = mat3(
  17275. vec3( t1.x, 0, t1.y ),
  17276. vec3( 0, 1, 0 ),
  17277. vec3( t1.z, 0, t1.w )
  17278. ).toVar();
  17279. // LTC Fresnel Approximation by Stephen Hill
  17280. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  17281. const fresnel = specularColorBlended.mul( t2.x ).add( specularColorBlended.oneMinus().mul( t2.y ) ).toVar();
  17282. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  17283. 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 } ) ) );
  17284. }
  17285. /**
  17286. * Implements the indirect lighting.
  17287. *
  17288. * @param {NodeBuilder} builder - The current node builder.
  17289. */
  17290. indirect( builder ) {
  17291. this.indirectDiffuse( builder );
  17292. this.indirectSpecular( builder );
  17293. this.ambientOcclusion( builder );
  17294. }
  17295. /**
  17296. * Implements the indirect diffuse term.
  17297. *
  17298. * @param {NodeBuilder} builder - The current node builder.
  17299. */
  17300. indirectDiffuse( builder ) {
  17301. const { irradiance, reflectedLight } = builder.context;
  17302. const diffuse = irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ).toVar();
  17303. if ( this.sheen === true ) {
  17304. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17305. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17306. diffuse.mulAssign( sheenEnergyComp );
  17307. }
  17308. reflectedLight.indirectDiffuse.addAssign( diffuse );
  17309. }
  17310. /**
  17311. * Implements the indirect specular term.
  17312. *
  17313. * @param {NodeBuilder} builder - The current node builder.
  17314. */
  17315. indirectSpecular( builder ) {
  17316. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  17317. if ( this.sheen === true ) {
  17318. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  17319. sheen,
  17320. IBLSheenBRDF( {
  17321. normal: normalView,
  17322. viewDir: positionViewDirection,
  17323. roughness: sheenRoughness
  17324. } )
  17325. ) );
  17326. }
  17327. if ( this.clearcoat === true ) {
  17328. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17329. const clearcoatEnv = EnvironmentBRDF( {
  17330. dotNV: dotNVcc,
  17331. specularColor: clearcoatF0,
  17332. specularF90: clearcoatF90,
  17333. roughness: clearcoatRoughness
  17334. } );
  17335. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  17336. }
  17337. // Both indirect specular and indirect diffuse light accumulate here
  17338. // Compute multiscattering separately for dielectric and metallic, then mix
  17339. const singleScatteringDielectric = vec3().toVar( 'singleScatteringDielectric' );
  17340. const multiScatteringDielectric = vec3().toVar( 'multiScatteringDielectric' );
  17341. const singleScatteringMetallic = vec3().toVar( 'singleScatteringMetallic' );
  17342. const multiScatteringMetallic = vec3().toVar( 'multiScatteringMetallic' );
  17343. this.computeMultiscattering( singleScatteringDielectric, multiScatteringDielectric, specularF90, specularColor, this.iridescenceF0Dielectric );
  17344. this.computeMultiscattering( singleScatteringMetallic, multiScatteringMetallic, specularF90, diffuseColor.rgb, this.iridescenceF0Metallic );
  17345. // Mix based on metalness
  17346. const singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, metalness );
  17347. const multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, metalness );
  17348. // Diffuse energy conservation uses dielectric path
  17349. const totalScatteringDielectric = singleScatteringDielectric.add( multiScatteringDielectric );
  17350. const diffuse = diffuseContribution.mul( totalScatteringDielectric.oneMinus() );
  17351. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  17352. const indirectSpecular = radiance.mul( singleScattering ).add( multiScattering.mul( cosineWeightedIrradiance ) ).toVar();
  17353. const indirectDiffuse = diffuse.mul( cosineWeightedIrradiance ).toVar();
  17354. if ( this.sheen === true ) {
  17355. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17356. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17357. indirectSpecular.mulAssign( sheenEnergyComp );
  17358. indirectDiffuse.mulAssign( sheenEnergyComp );
  17359. }
  17360. reflectedLight.indirectSpecular.addAssign( indirectSpecular );
  17361. reflectedLight.indirectDiffuse.addAssign( indirectDiffuse );
  17362. }
  17363. /**
  17364. * Implements the ambient occlusion term.
  17365. *
  17366. * @param {NodeBuilder} builder - The current node builder.
  17367. */
  17368. ambientOcclusion( builder ) {
  17369. const { ambientOcclusion, reflectedLight } = builder.context;
  17370. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17371. const aoNV = dotNV.add( ambientOcclusion );
  17372. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  17373. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  17374. if ( this.clearcoat === true ) {
  17375. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  17376. }
  17377. if ( this.sheen === true ) {
  17378. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  17379. }
  17380. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17381. reflectedLight.indirectSpecular.mulAssign( aoNode );
  17382. }
  17383. /**
  17384. * Used for final lighting accumulations depending on the requested features.
  17385. *
  17386. * @param {NodeBuilder} builder - The current node builder.
  17387. */
  17388. finish( { context } ) {
  17389. const { outgoingLight } = context;
  17390. if ( this.clearcoat === true ) {
  17391. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17392. const Fcc = F_Schlick( {
  17393. dotVH: dotNVcc,
  17394. f0: clearcoatF0,
  17395. f90: clearcoatF90
  17396. } );
  17397. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  17398. outgoingLight.assign( clearcoatLight );
  17399. }
  17400. if ( this.sheen === true ) {
  17401. const sheenLight = outgoingLight.add( this.sheenSpecularDirect, this.sheenSpecularIndirect.mul( 1.0 / Math.PI ) );
  17402. outgoingLight.assign( sheenLight );
  17403. }
  17404. }
  17405. }
  17406. // These defines must match with PMREMGenerator
  17407. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17408. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17409. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17410. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17411. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17412. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17413. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17414. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17415. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  17416. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  17417. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  17418. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  17419. // These shader functions convert between the UV coordinates of a single face of
  17420. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  17421. // sampling a textureCube (not generally normalized ).
  17422. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  17423. const absDirection = vec3( abs( direction ) ).toVar();
  17424. const face = float( -1 ).toVar();
  17425. If( absDirection.x.greaterThan( absDirection.z ), () => {
  17426. If( absDirection.x.greaterThan( absDirection.y ), () => {
  17427. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  17428. } ).Else( () => {
  17429. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17430. } );
  17431. } ).Else( () => {
  17432. If( absDirection.z.greaterThan( absDirection.y ), () => {
  17433. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  17434. } ).Else( () => {
  17435. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17436. } );
  17437. } );
  17438. return face;
  17439. } ).setLayout( {
  17440. name: 'getFace',
  17441. type: 'float',
  17442. inputs: [
  17443. { name: 'direction', type: 'vec3' }
  17444. ]
  17445. } );
  17446. // RH coordinate system; PMREM face-indexing convention
  17447. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  17448. const uv = vec2().toVar();
  17449. If( face.equal( 0.0 ), () => {
  17450. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  17451. } ).ElseIf( face.equal( 1.0 ), () => {
  17452. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  17453. } ).ElseIf( face.equal( 2.0 ), () => {
  17454. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  17455. } ).ElseIf( face.equal( 3.0 ), () => {
  17456. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  17457. } ).ElseIf( face.equal( 4.0 ), () => {
  17458. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  17459. } ).Else( () => {
  17460. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  17461. } );
  17462. return mul( 0.5, uv.add( 1.0 ) );
  17463. } ).setLayout( {
  17464. name: 'getUV',
  17465. type: 'vec2',
  17466. inputs: [
  17467. { name: 'direction', type: 'vec3' },
  17468. { name: 'face', type: 'float' }
  17469. ]
  17470. } );
  17471. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  17472. const mip = float( 0.0 ).toVar();
  17473. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  17474. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  17475. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  17476. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  17477. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  17478. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  17479. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  17480. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  17481. } ).Else( () => {
  17482. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  17483. } );
  17484. return mip;
  17485. } ).setLayout( {
  17486. name: 'roughnessToMip',
  17487. type: 'float',
  17488. inputs: [
  17489. { name: 'roughness', type: 'float' }
  17490. ]
  17491. } );
  17492. // RH coordinate system; PMREM face-indexing convention
  17493. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  17494. const uv = uv_immutable.toVar();
  17495. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  17496. const direction = vec3( uv, 1.0 ).toVar();
  17497. If( face.equal( 0.0 ), () => {
  17498. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  17499. } ).ElseIf( face.equal( 1.0 ), () => {
  17500. direction.assign( direction.xzy );
  17501. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  17502. } ).ElseIf( face.equal( 2.0 ), () => {
  17503. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  17504. } ).ElseIf( face.equal( 3.0 ), () => {
  17505. direction.assign( direction.zyx );
  17506. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  17507. } ).ElseIf( face.equal( 4.0 ), () => {
  17508. direction.assign( direction.xzy );
  17509. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  17510. } ).ElseIf( face.equal( 5.0 ), () => {
  17511. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  17512. } );
  17513. return direction;
  17514. } ).setLayout( {
  17515. name: 'getDirection',
  17516. type: 'vec3',
  17517. inputs: [
  17518. { name: 'uv', type: 'vec2' },
  17519. { name: 'face', type: 'float' }
  17520. ]
  17521. } );
  17522. //
  17523. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17524. const roughness = float( roughness_immutable );
  17525. const sampleDir = vec3( sampleDir_immutable );
  17526. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  17527. const mipF = fract( mip );
  17528. const mipInt = floor( mip );
  17529. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17530. If( mipF.notEqual( 0.0 ), () => {
  17531. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17532. color0.assign( mix( color0, color1, mipF ) );
  17533. } );
  17534. return color0;
  17535. } );
  17536. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17537. const mipInt = float( mipInt_immutable ).toVar();
  17538. const direction = vec3( direction_immutable );
  17539. const face = float( getFace( direction ) ).toVar();
  17540. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  17541. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  17542. const faceSize = float( exp2( mipInt ) ).toVar();
  17543. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  17544. If( face.greaterThan( 2.0 ), () => {
  17545. uv.y.addAssign( faceSize );
  17546. face.subAssign( 3.0 );
  17547. } );
  17548. uv.x.addAssign( face.mul( faceSize ) );
  17549. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  17550. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  17551. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  17552. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  17553. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  17554. } );
  17555. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17556. const cosTheta = cos( theta );
  17557. // Rodrigues' axis-angle rotation
  17558. const sampleDirection = outputDirection.mul( cosTheta )
  17559. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  17560. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  17561. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17562. } );
  17563. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17564. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  17565. If( axis.equal( vec3( 0.0 ) ), () => {
  17566. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  17567. } );
  17568. axis.assign( normalize( axis ) );
  17569. const gl_FragColor = vec3().toVar();
  17570. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17571. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  17572. If( i.greaterThanEqual( samples ), () => {
  17573. Break();
  17574. } );
  17575. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  17576. 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 } ) ) );
  17577. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17578. } );
  17579. return vec4( gl_FragColor, 1 );
  17580. } );
  17581. // GGX VNDF importance sampling functions
  17582. // Van der Corput radical inverse for generating quasi-random sequences
  17583. const radicalInverse_VdC = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  17584. const bits = uint( bits_immutable ).toVar();
  17585. bits.assign( bits.shiftLeft( uint( 16 ) ).bitOr( bits.shiftRight( uint( 16 ) ) ) );
  17586. bits.assign( bits.bitAnd( uint( 0x55555555 ) ).shiftLeft( uint( 1 ) ).bitOr( bits.bitAnd( uint( 0xAAAAAAAA ) ).shiftRight( uint( 1 ) ) ) );
  17587. bits.assign( bits.bitAnd( uint( 0x33333333 ) ).shiftLeft( uint( 2 ) ).bitOr( bits.bitAnd( uint( 0xCCCCCCCC ) ).shiftRight( uint( 2 ) ) ) );
  17588. bits.assign( bits.bitAnd( uint( 0x0F0F0F0F ) ).shiftLeft( uint( 4 ) ).bitOr( bits.bitAnd( uint( 0xF0F0F0F0 ) ).shiftRight( uint( 4 ) ) ) );
  17589. bits.assign( bits.bitAnd( uint( 0x00FF00FF ) ).shiftLeft( uint( 8 ) ).bitOr( bits.bitAnd( uint( 0xFF00FF00 ) ).shiftRight( uint( 8 ) ) ) );
  17590. return float( bits ).mul( 2.3283064365386963e-10 ); // / 0x100000000
  17591. } );
  17592. // Hammersley sequence for quasi-Monte Carlo sampling
  17593. const hammersley = /*@__PURE__*/ Fn( ( [ i, N ] ) => {
  17594. return vec2( float( i ).div( float( N ) ), radicalInverse_VdC( i ) );
  17595. } );
  17596. // GGX VNDF importance sampling (Eric Heitz 2018)
  17597. // "Sampling the GGX Distribution of Visible Normals"
  17598. // https://jcgt.org/published/0007/04/01/
  17599. const importanceSampleGGX_VNDF = /*@__PURE__*/ Fn( ( [ Xi, V_immutable, roughness_immutable ] ) => {
  17600. const V = vec3( V_immutable ).toVar();
  17601. const roughness = float( roughness_immutable );
  17602. const alpha = roughness.mul( roughness ).toVar();
  17603. // Section 3.2: Transform view direction to hemisphere configuration
  17604. const Vh = normalize( vec3( alpha.mul( V.x ), alpha.mul( V.y ), V.z ) ).toVar();
  17605. // Section 4.1: Orthonormal basis
  17606. const lensq = Vh.x.mul( Vh.x ).add( Vh.y.mul( Vh.y ) );
  17607. 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();
  17608. const T2 = cross( Vh, T1 ).toVar();
  17609. // Section 4.2: Parameterization of projected area
  17610. const r = sqrt( Xi.x );
  17611. const phi = mul( 2.0, 3.14159265359 ).mul( Xi.y );
  17612. const t1 = r.mul( cos( phi ) ).toVar();
  17613. const t2 = r.mul( sin( phi ) ).toVar();
  17614. const s = mul( 0.5, Vh.z.add( 1.0 ) );
  17615. t2.assign( s.oneMinus().mul( sqrt( t1.mul( t1 ).oneMinus() ) ).add( s.mul( t2 ) ) );
  17616. // Section 4.3: Reprojection onto hemisphere
  17617. 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() ) ) ) );
  17618. // Section 3.4: Transform back to ellipsoid configuration
  17619. return normalize( vec3( alpha.mul( Nh.x ), alpha.mul( Nh.y ), max$1( 0.0, Nh.z ) ) );
  17620. } );
  17621. // GGX convolution using VNDF importance sampling
  17622. const ggxConvolution = /*@__PURE__*/ Fn( ( { roughness, mipInt, envMap, N_immutable, GGX_SAMPLES, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17623. const N = vec3( N_immutable ).toVar();
  17624. const prefilteredColor = vec3( 0.0 ).toVar();
  17625. const totalWeight = float( 0.0 ).toVar();
  17626. // For very low roughness, just sample the environment directly
  17627. If( roughness.lessThan( 0.001 ), () => {
  17628. prefilteredColor.assign( bilinearCubeUV( envMap, N, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) );
  17629. } ).Else( () => {
  17630. // Tangent space basis for VNDF sampling
  17631. const up = select( abs( N.z ).lessThan( 0.999 ), vec3( 0.0, 0.0, 1.0 ), vec3( 1.0, 0.0, 0.0 ) );
  17632. const tangent = normalize( cross( up, N ) ).toVar();
  17633. const bitangent = cross( N, tangent ).toVar();
  17634. Loop( { start: uint( 0 ), end: GGX_SAMPLES }, ( { i } ) => {
  17635. const Xi = hammersley( i, GGX_SAMPLES );
  17636. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  17637. const H_tangent = importanceSampleGGX_VNDF( Xi, vec3( 0.0, 0.0, 1.0 ), roughness );
  17638. // Transform H back to world space
  17639. const H = normalize( tangent.mul( H_tangent.x ).add( bitangent.mul( H_tangent.y ) ).add( N.mul( H_tangent.z ) ) );
  17640. const L = normalize( H.mul( dot( N, H ).mul( 2.0 ) ).sub( N ) );
  17641. const NdotL = max$1( dot( N, L ), 0.0 );
  17642. If( NdotL.greaterThan( 0.0 ), () => {
  17643. // Sample environment at fixed mip level
  17644. // VNDF importance sampling handles the distribution filtering
  17645. const sampleColor = bilinearCubeUV( envMap, L, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17646. // Weight by NdotL for the split-sum approximation
  17647. // VNDF PDF naturally accounts for the visible microfacet distribution
  17648. prefilteredColor.addAssign( sampleColor.mul( NdotL ) );
  17649. totalWeight.addAssign( NdotL );
  17650. } );
  17651. } );
  17652. If( totalWeight.greaterThan( 0.0 ), () => {
  17653. prefilteredColor.assign( prefilteredColor.div( totalWeight ) );
  17654. } );
  17655. } );
  17656. return vec4( prefilteredColor, 1.0 );
  17657. } );
  17658. const LOD_MIN = 4;
  17659. // The standard deviations (radians) associated with the extra mips.
  17660. // Used for scene blur in fromScene() method.
  17661. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  17662. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  17663. // samples and exit early, but not recompile the shader.
  17664. // Used for scene blur in fromScene() method.
  17665. const MAX_SAMPLES = 20;
  17666. // GGX VNDF importance sampling configuration
  17667. const GGX_SAMPLES = 512;
  17668. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  17669. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  17670. const _clearColor$2 = /*@__PURE__*/ new Color();
  17671. let _oldTarget = null;
  17672. let _oldActiveCubeFace = 0;
  17673. let _oldActiveMipmapLevel = 0;
  17674. const _origin = /*@__PURE__*/ new Vector3();
  17675. // maps blur materials to their uniforms dictionary
  17676. const _uniformsMap = new WeakMap();
  17677. // WebGPU Face indices
  17678. const _faceLib = [
  17679. 3, 1, 5,
  17680. 0, 4, 2
  17681. ];
  17682. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  17683. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  17684. /**
  17685. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  17686. * (PMREM) from a cubeMap environment texture. This allows different levels of
  17687. * blur to be quickly accessed based on material roughness. It is packed into a
  17688. * special CubeUV format that allows us to perform custom interpolation so that
  17689. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  17690. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  17691. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  17692. * higher roughness levels. In this way we maintain resolution to smoothly
  17693. * interpolate diffuse lighting while limiting sampling computation.
  17694. *
  17695. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  17696. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  17697. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  17698. * used in material rendering for physically-based image-based lighting.
  17699. */
  17700. class PMREMGenerator {
  17701. /**
  17702. * Constructs a new PMREM generator.
  17703. *
  17704. * @param {Renderer} renderer - The renderer.
  17705. */
  17706. constructor( renderer ) {
  17707. this._renderer = renderer;
  17708. this._pingPongRenderTarget = null;
  17709. this._lodMax = 0;
  17710. this._cubeSize = 0;
  17711. this._sizeLods = [];
  17712. this._sigmas = [];
  17713. this._lodMeshes = [];
  17714. this._blurMaterial = null;
  17715. this._ggxMaterial = null;
  17716. this._cubemapMaterial = null;
  17717. this._equirectMaterial = null;
  17718. this._backgroundBox = null;
  17719. }
  17720. get _hasInitialized() {
  17721. return this._renderer.hasInitialized();
  17722. }
  17723. /**
  17724. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17725. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17726. * in radians to be applied to the scene before PMREM generation. Optional near
  17727. * and far planes ensure the scene is rendered in its entirety.
  17728. *
  17729. * @param {Scene} scene - The scene to be captured.
  17730. * @param {number} [sigma=0] - The blur radius in radians.
  17731. * @param {number} [near=0.1] - The near plane distance.
  17732. * @param {number} [far=100] - The far plane distance.
  17733. * @param {Object} [options={}] - The configuration options.
  17734. * @param {number} [options.size=256] - The texture size of the PMREM.
  17735. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  17736. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17737. * @return {RenderTarget} The resulting PMREM.
  17738. * @see {@link PMREMGenerator#fromScene}
  17739. */
  17740. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17741. const {
  17742. size = 256,
  17743. position = _origin,
  17744. renderTarget = null,
  17745. } = options;
  17746. this._setSize( size );
  17747. if ( this._hasInitialized === false ) {
  17748. warn( 'PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17749. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17750. options.renderTarget = cubeUVRenderTarget;
  17751. this.fromSceneAsync( scene, sigma, near, far, options );
  17752. return cubeUVRenderTarget;
  17753. }
  17754. _oldTarget = this._renderer.getRenderTarget();
  17755. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17756. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17757. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17758. cubeUVRenderTarget.depthBuffer = true;
  17759. this._init( cubeUVRenderTarget );
  17760. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  17761. if ( sigma > 0 ) {
  17762. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  17763. }
  17764. this._applyPMREM( cubeUVRenderTarget );
  17765. this._cleanup( cubeUVRenderTarget );
  17766. return cubeUVRenderTarget;
  17767. }
  17768. /**
  17769. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17770. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17771. * in radians to be applied to the scene before PMREM generation. Optional near
  17772. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  17773. * is placed at the origin).
  17774. *
  17775. * @deprecated
  17776. * @param {Scene} scene - The scene to be captured.
  17777. * @param {number} [sigma=0] - The blur radius in radians.
  17778. * @param {number} [near=0.1] - The near plane distance.
  17779. * @param {number} [far=100] - The far plane distance.
  17780. * @param {Object} [options={}] - The configuration options.
  17781. * @param {number} [options.size=256] - The texture size of the PMREM.
  17782. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  17783. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17784. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  17785. * @see {@link PMREMGenerator#fromScene}
  17786. */
  17787. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17788. warnOnce( 'PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17789. await this._renderer.init();
  17790. return this.fromScene( scene, sigma, near, far, options );
  17791. }
  17792. /**
  17793. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17794. * or HDR. The ideal input image size is 1k (1024 x 512),
  17795. * as this matches best with the 256 x 256 cubemap output.
  17796. *
  17797. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17798. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17799. * @return {RenderTarget} The resulting PMREM.
  17800. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  17801. */
  17802. fromEquirectangular( equirectangular, renderTarget = null ) {
  17803. if ( this._hasInitialized === false ) {
  17804. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17805. this._setSizeFromTexture( equirectangular );
  17806. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17807. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  17808. return cubeUVRenderTarget;
  17809. }
  17810. return this._fromTexture( equirectangular, renderTarget );
  17811. }
  17812. /**
  17813. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17814. * or HDR. The ideal input image size is 1k (1024 x 512),
  17815. * as this matches best with the 256 x 256 cubemap output.
  17816. *
  17817. * @deprecated
  17818. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17819. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17820. * @return {Promise<RenderTarget>} The resulting PMREM.
  17821. * @see {@link PMREMGenerator#fromEquirectangular}
  17822. */
  17823. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  17824. warnOnce( 'PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17825. await this._renderer.init();
  17826. return this._fromTexture( equirectangular, renderTarget );
  17827. }
  17828. /**
  17829. * Generates a PMREM from an cubemap texture, which can be either LDR
  17830. * or HDR. The ideal input cube size is 256 x 256,
  17831. * as this matches best with the 256 x 256 cubemap output.
  17832. *
  17833. * @param {Texture} cubemap - The cubemap texture to be converted.
  17834. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17835. * @return {RenderTarget} The resulting PMREM.
  17836. * @see {@link PMREMGenerator#fromCubemapAsync}
  17837. */
  17838. fromCubemap( cubemap, renderTarget = null ) {
  17839. if ( this._hasInitialized === false ) {
  17840. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  17841. this._setSizeFromTexture( cubemap );
  17842. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17843. this.fromCubemapAsync( cubemap, renderTarget );
  17844. return cubeUVRenderTarget;
  17845. }
  17846. return this._fromTexture( cubemap, renderTarget );
  17847. }
  17848. /**
  17849. * Generates a PMREM from an cubemap texture, which can be either LDR
  17850. * or HDR. The ideal input cube size is 256 x 256,
  17851. * with the 256 x 256 cubemap output.
  17852. *
  17853. * @deprecated
  17854. * @param {Texture} cubemap - The cubemap texture to be converted.
  17855. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17856. * @return {Promise<RenderTarget>} The resulting PMREM.
  17857. * @see {@link PMREMGenerator#fromCubemap}
  17858. */
  17859. async fromCubemapAsync( cubemap, renderTarget = null ) {
  17860. warnOnce( 'PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17861. await this._renderer.init();
  17862. return this._fromTexture( cubemap, renderTarget );
  17863. }
  17864. /**
  17865. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  17866. * your texture's network fetch for increased concurrency.
  17867. *
  17868. * @returns {Promise}
  17869. */
  17870. async compileCubemapShader() {
  17871. if ( this._cubemapMaterial === null ) {
  17872. this._cubemapMaterial = _getCubemapMaterial();
  17873. await this._compileMaterial( this._cubemapMaterial );
  17874. }
  17875. }
  17876. /**
  17877. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  17878. * your texture's network fetch for increased concurrency.
  17879. *
  17880. * @returns {Promise}
  17881. */
  17882. async compileEquirectangularShader() {
  17883. if ( this._equirectMaterial === null ) {
  17884. this._equirectMaterial = _getEquirectMaterial();
  17885. await this._compileMaterial( this._equirectMaterial );
  17886. }
  17887. }
  17888. /**
  17889. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  17890. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  17891. * one of them will cause any others to also become unusable.
  17892. */
  17893. dispose() {
  17894. this._dispose();
  17895. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  17896. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  17897. if ( this._backgroundBox !== null ) {
  17898. this._backgroundBox.geometry.dispose();
  17899. this._backgroundBox.material.dispose();
  17900. }
  17901. }
  17902. // private interface
  17903. _setSizeFromTexture( texture ) {
  17904. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  17905. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  17906. } else { // Equirectangular
  17907. this._setSize( texture.image.width / 4 );
  17908. }
  17909. }
  17910. _setSize( cubeSize ) {
  17911. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  17912. this._cubeSize = Math.pow( 2, this._lodMax );
  17913. }
  17914. _dispose() {
  17915. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  17916. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  17917. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  17918. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  17919. this._lodMeshes[ i ].geometry.dispose();
  17920. }
  17921. }
  17922. _cleanup( outputTarget ) {
  17923. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  17924. outputTarget.scissorTest = false;
  17925. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  17926. }
  17927. _fromTexture( texture, renderTarget ) {
  17928. this._setSizeFromTexture( texture );
  17929. _oldTarget = this._renderer.getRenderTarget();
  17930. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17931. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17932. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17933. this._init( cubeUVRenderTarget );
  17934. this._textureToCubeUV( texture, cubeUVRenderTarget );
  17935. this._applyPMREM( cubeUVRenderTarget );
  17936. this._cleanup( cubeUVRenderTarget );
  17937. return cubeUVRenderTarget;
  17938. }
  17939. _allocateTarget() {
  17940. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  17941. const height = 4 * this._cubeSize;
  17942. const cubeUVRenderTarget = _createRenderTarget( width, height );
  17943. return cubeUVRenderTarget;
  17944. }
  17945. _init( renderTarget ) {
  17946. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17947. if ( this._pingPongRenderTarget !== null ) {
  17948. this._dispose();
  17949. }
  17950. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  17951. const { _lodMax } = this;
  17952. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  17953. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  17954. this._ggxMaterial = _getGGXShader( _lodMax, renderTarget.width, renderTarget.height );
  17955. }
  17956. }
  17957. async _compileMaterial( material ) {
  17958. const mesh = new Mesh( new BufferGeometry(), material );
  17959. await this._renderer.compile( mesh, _flatCamera );
  17960. }
  17961. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  17962. const cubeCamera = _cubeCamera;
  17963. cubeCamera.near = near;
  17964. cubeCamera.far = far;
  17965. // px, py, pz, nx, ny, nz
  17966. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  17967. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  17968. const renderer = this._renderer;
  17969. const originalAutoClear = renderer.autoClear;
  17970. renderer.getClearColor( _clearColor$2 );
  17971. renderer.autoClear = false;
  17972. if ( this._backgroundBox === null ) {
  17973. this._backgroundBox = new Mesh(
  17974. new BoxGeometry(),
  17975. new MeshBasicMaterial( {
  17976. name: 'PMREM.Background',
  17977. side: BackSide,
  17978. depthWrite: false,
  17979. depthTest: false,
  17980. } )
  17981. );
  17982. }
  17983. const backgroundBox = this._backgroundBox;
  17984. const backgroundMaterial = backgroundBox.material;
  17985. let useSolidColor = false;
  17986. const background = scene.background;
  17987. if ( background ) {
  17988. if ( background.isColor ) {
  17989. backgroundMaterial.color.copy( background );
  17990. scene.background = null;
  17991. useSolidColor = true;
  17992. }
  17993. } else {
  17994. backgroundMaterial.color.copy( _clearColor$2 );
  17995. useSolidColor = true;
  17996. }
  17997. renderer.setRenderTarget( cubeUVRenderTarget );
  17998. renderer.clear();
  17999. if ( useSolidColor ) {
  18000. renderer.render( backgroundBox, cubeCamera );
  18001. }
  18002. for ( let i = 0; i < 6; i ++ ) {
  18003. const col = i % 3;
  18004. if ( col === 0 ) {
  18005. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18006. cubeCamera.position.set( position.x, position.y, position.z );
  18007. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  18008. } else if ( col === 1 ) {
  18009. cubeCamera.up.set( 0, 0, upSign[ i ] );
  18010. cubeCamera.position.set( position.x, position.y, position.z );
  18011. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  18012. } else {
  18013. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18014. cubeCamera.position.set( position.x, position.y, position.z );
  18015. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  18016. }
  18017. const size = this._cubeSize;
  18018. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  18019. renderer.render( scene, cubeCamera );
  18020. }
  18021. renderer.autoClear = originalAutoClear;
  18022. scene.background = background;
  18023. }
  18024. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  18025. const renderer = this._renderer;
  18026. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  18027. if ( isCubeTexture ) {
  18028. if ( this._cubemapMaterial === null ) {
  18029. this._cubemapMaterial = _getCubemapMaterial( texture );
  18030. }
  18031. } else {
  18032. if ( this._equirectMaterial === null ) {
  18033. this._equirectMaterial = _getEquirectMaterial( texture );
  18034. }
  18035. }
  18036. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  18037. material.fragmentNode.value = texture;
  18038. const mesh = this._lodMeshes[ 0 ];
  18039. mesh.material = material;
  18040. const size = this._cubeSize;
  18041. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  18042. renderer.setRenderTarget( cubeUVRenderTarget );
  18043. renderer.render( mesh, _flatCamera );
  18044. }
  18045. _applyPMREM( cubeUVRenderTarget ) {
  18046. const renderer = this._renderer;
  18047. const autoClear = renderer.autoClear;
  18048. renderer.autoClear = false;
  18049. const n = this._lodMeshes.length;
  18050. // Use GGX VNDF importance sampling
  18051. for ( let i = 1; i < n; i ++ ) {
  18052. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  18053. }
  18054. renderer.autoClear = autoClear;
  18055. }
  18056. /**
  18057. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  18058. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  18059. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  18060. * applies incremental roughness filtering to avoid over-blurring.
  18061. *
  18062. * @private
  18063. * @param {RenderTarget} cubeUVRenderTarget
  18064. * @param {number} lodIn - Source LOD level to read from
  18065. * @param {number} lodOut - Target LOD level to write to
  18066. */
  18067. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  18068. const renderer = this._renderer;
  18069. const pingPongRenderTarget = this._pingPongRenderTarget;
  18070. const ggxMaterial = this._ggxMaterial;
  18071. const ggxMesh = this._lodMeshes[ lodOut ];
  18072. ggxMesh.material = ggxMaterial;
  18073. const ggxUniforms = _uniformsMap.get( ggxMaterial );
  18074. // Calculate incremental roughness between LOD levels
  18075. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  18076. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  18077. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  18078. // Apply blur strength mapping for better quality across the roughness range
  18079. const blurStrength = 0.0 + targetRoughness * 1.25;
  18080. const adjustedRoughness = incrementalRoughness * blurStrength;
  18081. // Calculate viewport position based on output LOD level
  18082. const { _lodMax } = this;
  18083. const outputSize = this._sizeLods[ lodOut ];
  18084. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18085. const y = 4 * ( this._cubeSize - outputSize );
  18086. // Read from previous LOD with incremental roughness
  18087. cubeUVRenderTarget.texture.frame = ( cubeUVRenderTarget.texture.frame || 0 ) + 1;
  18088. ggxUniforms.envMap.value = cubeUVRenderTarget.texture;
  18089. ggxUniforms.roughness.value = adjustedRoughness;
  18090. ggxUniforms.mipInt.value = _lodMax - lodIn; // Sample from input LOD
  18091. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18092. renderer.setRenderTarget( pingPongRenderTarget );
  18093. renderer.render( ggxMesh, _flatCamera );
  18094. // Copy from pingPong back to cubeUV (simple direct copy)
  18095. pingPongRenderTarget.texture.frame = ( pingPongRenderTarget.texture.frame || 0 ) + 1;
  18096. ggxUniforms.envMap.value = pingPongRenderTarget.texture;
  18097. ggxUniforms.roughness.value = 0.0; // Direct copy
  18098. ggxUniforms.mipInt.value = _lodMax - lodOut; // Read from the level we just wrote
  18099. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18100. renderer.setRenderTarget( cubeUVRenderTarget );
  18101. renderer.render( ggxMesh, _flatCamera );
  18102. }
  18103. /**
  18104. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  18105. * vertically and horizontally, but this breaks down on a cube. Here we apply
  18106. * the blur latitudinally (around the poles), and then longitudinally (towards
  18107. * the poles) to approximate the orthogonally-separable blur. It is least
  18108. * accurate at the poles, but still does a decent job.
  18109. *
  18110. * Used for initial scene blur in fromScene() method when sigma > 0.
  18111. *
  18112. * @private
  18113. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  18114. * @param {number} lodIn - The input level-of-detail.
  18115. * @param {number} lodOut - The output level-of-detail.
  18116. * @param {number} sigma - The blur radius in radians.
  18117. * @param {Vector3} [poleAxis] - The pole axis.
  18118. */
  18119. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  18120. const pingPongRenderTarget = this._pingPongRenderTarget;
  18121. this._halfBlur(
  18122. cubeUVRenderTarget,
  18123. pingPongRenderTarget,
  18124. lodIn,
  18125. lodOut,
  18126. sigma,
  18127. 'latitudinal',
  18128. poleAxis );
  18129. this._halfBlur(
  18130. pingPongRenderTarget,
  18131. cubeUVRenderTarget,
  18132. lodOut,
  18133. lodOut,
  18134. sigma,
  18135. 'longitudinal',
  18136. poleAxis );
  18137. }
  18138. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  18139. const renderer = this._renderer;
  18140. const blurMaterial = this._blurMaterial;
  18141. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  18142. error( 'blur direction must be either latitudinal or longitudinal!' );
  18143. }
  18144. // Number of standard deviations at which to cut off the discrete approximation.
  18145. const STANDARD_DEVIATIONS = 3;
  18146. const blurMesh = this._lodMeshes[ lodOut ];
  18147. blurMesh.material = blurMaterial;
  18148. const blurUniforms = _uniformsMap.get( blurMaterial );
  18149. const pixels = this._sizeLods[ lodIn ] - 1;
  18150. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  18151. const sigmaPixels = sigmaRadians / radiansPerPixel;
  18152. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  18153. if ( samples > MAX_SAMPLES ) {
  18154. warn( `sigmaRadians, ${
  18155. sigmaRadians}, is too large and will clip, as it requested ${
  18156. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  18157. }
  18158. const weights = [];
  18159. let sum = 0;
  18160. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  18161. const x = i / sigmaPixels;
  18162. const weight = Math.exp( - x * x / 2 );
  18163. weights.push( weight );
  18164. if ( i === 0 ) {
  18165. sum += weight;
  18166. } else if ( i < samples ) {
  18167. sum += 2 * weight;
  18168. }
  18169. }
  18170. for ( let i = 0; i < weights.length; i ++ ) {
  18171. weights[ i ] = weights[ i ] / sum;
  18172. }
  18173. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  18174. blurUniforms.envMap.value = targetIn.texture;
  18175. blurUniforms.samples.value = samples;
  18176. blurUniforms.weights.array = weights;
  18177. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  18178. if ( poleAxis ) {
  18179. blurUniforms.poleAxis.value = poleAxis;
  18180. }
  18181. const { _lodMax } = this;
  18182. blurUniforms.dTheta.value = radiansPerPixel;
  18183. blurUniforms.mipInt.value = _lodMax - lodIn;
  18184. const outputSize = this._sizeLods[ lodOut ];
  18185. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18186. const y = 4 * ( this._cubeSize - outputSize );
  18187. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  18188. renderer.setRenderTarget( targetOut );
  18189. renderer.render( blurMesh, _flatCamera );
  18190. }
  18191. }
  18192. function _createPlanes( lodMax ) {
  18193. const sizeLods = [];
  18194. const sigmas = [];
  18195. const lodMeshes = [];
  18196. let lod = lodMax;
  18197. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  18198. for ( let i = 0; i < totalLods; i ++ ) {
  18199. const sizeLod = Math.pow( 2, lod );
  18200. sizeLods.push( sizeLod );
  18201. let sigma = 1.0 / sizeLod;
  18202. if ( i > lodMax - LOD_MIN ) {
  18203. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  18204. } else if ( i === 0 ) {
  18205. sigma = 0;
  18206. }
  18207. sigmas.push( sigma );
  18208. const texelSize = 1.0 / ( sizeLod - 2 );
  18209. const min = - texelSize;
  18210. const max = 1 + texelSize;
  18211. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  18212. const cubeFaces = 6;
  18213. const vertices = 6;
  18214. const positionSize = 3;
  18215. const uvSize = 2;
  18216. const faceIndexSize = 1;
  18217. const position = new Float32Array( positionSize * vertices * cubeFaces );
  18218. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  18219. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  18220. for ( let face = 0; face < cubeFaces; face ++ ) {
  18221. const x = ( face % 3 ) * 2 / 3 - 1;
  18222. const y = face > 2 ? 0 : -1;
  18223. const coordinates = [
  18224. x, y, 0,
  18225. x + 2 / 3, y, 0,
  18226. x + 2 / 3, y + 1, 0,
  18227. x, y, 0,
  18228. x + 2 / 3, y + 1, 0,
  18229. x, y + 1, 0
  18230. ];
  18231. const faceIdx = _faceLib[ face ];
  18232. position.set( coordinates, positionSize * vertices * faceIdx );
  18233. uv.set( uv1, uvSize * vertices * faceIdx );
  18234. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  18235. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  18236. }
  18237. const planes = new BufferGeometry();
  18238. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  18239. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  18240. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  18241. lodMeshes.push( new Mesh( planes, null ) );
  18242. if ( lod > LOD_MIN ) {
  18243. lod --;
  18244. }
  18245. }
  18246. return { lodMeshes, sizeLods, sigmas };
  18247. }
  18248. function _createRenderTarget( width, height ) {
  18249. const params = {
  18250. magFilter: LinearFilter,
  18251. minFilter: LinearFilter,
  18252. generateMipmaps: false,
  18253. type: HalfFloatType,
  18254. format: RGBAFormat,
  18255. colorSpace: LinearSRGBColorSpace,
  18256. //depthBuffer: false
  18257. };
  18258. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  18259. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  18260. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  18261. cubeUVRenderTarget.texture.isPMREMTexture = true;
  18262. cubeUVRenderTarget.scissorTest = true;
  18263. return cubeUVRenderTarget;
  18264. }
  18265. function _setViewport( target, x, y, width, height ) {
  18266. target.viewport.set( x, y, width, height );
  18267. target.scissor.set( x, y, width, height );
  18268. }
  18269. function _getMaterial( type ) {
  18270. const material = new NodeMaterial();
  18271. material.depthTest = false;
  18272. material.depthWrite = false;
  18273. material.blending = NoBlending;
  18274. material.name = `PMREM_${ type }`;
  18275. return material;
  18276. }
  18277. function _getBlurShader( lodMax, width, height ) {
  18278. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  18279. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  18280. const dTheta = uniform( 0 );
  18281. const n = float( MAX_SAMPLES );
  18282. const latitudinal = uniform( 0 ); // false, bool
  18283. const samples = uniform( 1 ); // int
  18284. const envMap = texture();
  18285. const mipInt = uniform( 0 ); // int
  18286. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18287. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18288. const CUBEUV_MAX_MIP = float( lodMax );
  18289. const materialUniforms = {
  18290. n,
  18291. latitudinal,
  18292. weights,
  18293. poleAxis,
  18294. outputDirection: _outputDirection,
  18295. dTheta,
  18296. samples,
  18297. envMap,
  18298. mipInt,
  18299. CUBEUV_TEXEL_WIDTH,
  18300. CUBEUV_TEXEL_HEIGHT,
  18301. CUBEUV_MAX_MIP
  18302. };
  18303. const material = _getMaterial( 'blur' );
  18304. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  18305. _uniformsMap.set( material, materialUniforms );
  18306. return material;
  18307. }
  18308. function _getGGXShader( lodMax, width, height ) {
  18309. const envMap = texture();
  18310. const roughness = uniform( 0 );
  18311. const mipInt = uniform( 0 );
  18312. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18313. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18314. const CUBEUV_MAX_MIP = float( lodMax );
  18315. const materialUniforms = {
  18316. envMap,
  18317. roughness,
  18318. mipInt,
  18319. CUBEUV_TEXEL_WIDTH,
  18320. CUBEUV_TEXEL_HEIGHT,
  18321. CUBEUV_MAX_MIP
  18322. };
  18323. const material = _getMaterial( 'ggx' );
  18324. material.fragmentNode = ggxConvolution( {
  18325. ...materialUniforms,
  18326. N_immutable: _outputDirection,
  18327. GGX_SAMPLES: uint( GGX_SAMPLES )
  18328. } );
  18329. _uniformsMap.set( material, materialUniforms );
  18330. return material;
  18331. }
  18332. function _getCubemapMaterial( envTexture ) {
  18333. const material = _getMaterial( 'cubemap' );
  18334. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  18335. return material;
  18336. }
  18337. function _getEquirectMaterial( envTexture ) {
  18338. const material = _getMaterial( 'equirect' );
  18339. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  18340. return material;
  18341. }
  18342. const _cache = new WeakMap();
  18343. /**
  18344. * Generates the cubeUV size based on the given image height.
  18345. *
  18346. * @private
  18347. * @param {number} imageHeight - The image height.
  18348. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  18349. */
  18350. function _generateCubeUVSize( imageHeight ) {
  18351. const maxMip = Math.log2( imageHeight ) - 2;
  18352. const texelHeight = 1.0 / imageHeight;
  18353. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  18354. return { texelWidth, texelHeight, maxMip };
  18355. }
  18356. /**
  18357. * Generates a PMREM from the given texture.
  18358. *
  18359. * @private
  18360. * @param {Texture} texture - The texture to create the PMREM for.
  18361. * @param {Renderer} renderer - The renderer.
  18362. * @param {PMREMGenerator} generator - The PMREM generator.
  18363. * @return {?Texture} The PMREM.
  18364. */
  18365. function _getPMREMFromTexture( texture, renderer, generator ) {
  18366. const cache = _getCache( renderer );
  18367. let cacheTexture = cache.get( texture );
  18368. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  18369. if ( pmremVersion !== texture.pmremVersion ) {
  18370. const image = texture.image;
  18371. if ( texture.isCubeTexture ) {
  18372. if ( isCubeMapReady( image ) ) {
  18373. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  18374. } else {
  18375. return null;
  18376. }
  18377. } else {
  18378. if ( isEquirectangularMapReady( image ) ) {
  18379. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  18380. } else {
  18381. return null;
  18382. }
  18383. }
  18384. cacheTexture.pmremVersion = texture.pmremVersion;
  18385. cache.set( texture, cacheTexture );
  18386. }
  18387. return cacheTexture.texture;
  18388. }
  18389. /**
  18390. * Returns a cache that stores generated PMREMs for the respective textures.
  18391. * A cache must be maintained per renderer since PMREMs are render target textures
  18392. * which can't be shared across render contexts.
  18393. *
  18394. * @private
  18395. * @param {Renderer} renderer - The renderer.
  18396. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  18397. */
  18398. function _getCache( renderer ) {
  18399. let rendererCache = _cache.get( renderer );
  18400. if ( rendererCache === undefined ) {
  18401. rendererCache = new WeakMap();
  18402. _cache.set( renderer, rendererCache );
  18403. }
  18404. return rendererCache;
  18405. }
  18406. /**
  18407. * This node represents a PMREM which is a special type of preprocessed
  18408. * environment map intended for PBR materials.
  18409. *
  18410. * ```js
  18411. * const material = new MeshStandardNodeMaterial();
  18412. * material.envNode = pmremTexture( envMap );
  18413. * ```
  18414. *
  18415. * @augments TempNode
  18416. */
  18417. class PMREMNode extends TempNode {
  18418. static get type() {
  18419. return 'PMREMNode';
  18420. }
  18421. /**
  18422. * Constructs a new function overloading node.
  18423. *
  18424. * @param {Texture} value - The input texture.
  18425. * @param {Node<vec2>} [uvNode=null] - The uv node.
  18426. * @param {Node<float>} [levelNode=null] - The level node.
  18427. */
  18428. constructor( value, uvNode = null, levelNode = null ) {
  18429. super( 'vec3' );
  18430. /**
  18431. * Reference to the input texture.
  18432. *
  18433. * @private
  18434. * @type {Texture}
  18435. */
  18436. this._value = value;
  18437. /**
  18438. * Reference to the generated PMREM.
  18439. *
  18440. * @private
  18441. * @type {Texture | null}
  18442. * @default null
  18443. */
  18444. this._pmrem = null;
  18445. /**
  18446. * The uv node.
  18447. *
  18448. * @type {Node<vec2>}
  18449. */
  18450. this.uvNode = uvNode;
  18451. /**
  18452. * The level node.
  18453. *
  18454. * @type {Node<float>}
  18455. */
  18456. this.levelNode = levelNode;
  18457. /**
  18458. * Reference to a PMREM generator.
  18459. *
  18460. * @private
  18461. * @type {?PMREMGenerator}
  18462. * @default null
  18463. */
  18464. this._generator = null;
  18465. const defaultTexture = new Texture();
  18466. defaultTexture.isRenderTargetTexture = true;
  18467. /**
  18468. * The texture node holding the generated PMREM.
  18469. *
  18470. * @private
  18471. * @type {TextureNode}
  18472. */
  18473. this._texture = texture( defaultTexture );
  18474. /**
  18475. * A uniform representing the PMREM's width.
  18476. *
  18477. * @private
  18478. * @type {UniformNode<float>}
  18479. */
  18480. this._width = uniform( 0 );
  18481. /**
  18482. * A uniform representing the PMREM's height.
  18483. *
  18484. * @private
  18485. * @type {UniformNode<float>}
  18486. */
  18487. this._height = uniform( 0 );
  18488. /**
  18489. * A uniform representing the PMREM's max Mip.
  18490. *
  18491. * @private
  18492. * @type {UniformNode<float>}
  18493. */
  18494. this._maxMip = uniform( 0 );
  18495. /**
  18496. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  18497. *
  18498. * @type {string}
  18499. * @default 'render'
  18500. */
  18501. this.updateBeforeType = NodeUpdateType.RENDER;
  18502. }
  18503. set value( value ) {
  18504. this._value = value;
  18505. this._pmrem = null;
  18506. }
  18507. /**
  18508. * The node's texture value.
  18509. *
  18510. * @type {Texture}
  18511. */
  18512. get value() {
  18513. return this._value;
  18514. }
  18515. /**
  18516. * Uses the given PMREM texture to update internal values.
  18517. *
  18518. * @param {Texture} texture - The PMREM texture.
  18519. */
  18520. updateFromTexture( texture ) {
  18521. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  18522. this._texture.value = texture;
  18523. this._width.value = cubeUVSize.texelWidth;
  18524. this._height.value = cubeUVSize.texelHeight;
  18525. this._maxMip.value = cubeUVSize.maxMip;
  18526. }
  18527. updateBefore( frame ) {
  18528. let pmrem = this._pmrem;
  18529. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  18530. const texture = this._value;
  18531. if ( pmremVersion !== texture.pmremVersion ) {
  18532. if ( texture.isPMREMTexture === true ) {
  18533. pmrem = texture;
  18534. } else {
  18535. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  18536. }
  18537. if ( pmrem !== null ) {
  18538. this._pmrem = pmrem;
  18539. this.updateFromTexture( pmrem );
  18540. }
  18541. }
  18542. }
  18543. setup( builder ) {
  18544. if ( this._generator === null ) {
  18545. this._generator = new PMREMGenerator( builder.renderer );
  18546. }
  18547. this.updateBefore( builder );
  18548. //
  18549. let uvNode = this.uvNode;
  18550. if ( uvNode === null && builder.context.getUV ) {
  18551. uvNode = builder.context.getUV( this, builder );
  18552. }
  18553. //
  18554. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  18555. //
  18556. let levelNode = this.levelNode;
  18557. if ( levelNode === null && builder.context.getTextureLevel ) {
  18558. levelNode = builder.context.getTextureLevel( this );
  18559. }
  18560. //
  18561. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  18562. }
  18563. dispose() {
  18564. super.dispose();
  18565. if ( this._generator !== null ) this._generator.dispose();
  18566. }
  18567. }
  18568. /**
  18569. * Returns `true` if the given cube map image has been fully loaded.
  18570. *
  18571. * @private
  18572. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  18573. * @return {boolean} Whether the given cube map is ready or not.
  18574. */
  18575. function isCubeMapReady( image ) {
  18576. if ( image === null || image === undefined ) return false;
  18577. let count = 0;
  18578. const length = 6;
  18579. for ( let i = 0; i < length; i ++ ) {
  18580. if ( image[ i ] !== undefined ) count ++;
  18581. }
  18582. return count === length;
  18583. }
  18584. /**
  18585. * Returns `true` if the given equirectangular image has been fully loaded.
  18586. *
  18587. * @private
  18588. * @param {(Image|Object)} image - The equirectangular image.
  18589. * @return {boolean} Whether the given cube map is ready or not.
  18590. */
  18591. function isEquirectangularMapReady( image ) {
  18592. if ( image === null || image === undefined ) return false;
  18593. return image.height > 0;
  18594. }
  18595. /**
  18596. * TSL function for creating a PMREM node.
  18597. *
  18598. * @tsl
  18599. * @function
  18600. * @param {Texture} value - The input texture.
  18601. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  18602. * @param {?Node<float>} [levelNode=null] - The level node.
  18603. * @returns {PMREMNode}
  18604. */
  18605. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  18606. const _envNodeCache = new WeakMap();
  18607. /**
  18608. * Represents a physical model for Image-based lighting (IBL). The environment
  18609. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  18610. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  18611. *
  18612. * @augments LightingNode
  18613. */
  18614. class EnvironmentNode extends LightingNode {
  18615. static get type() {
  18616. return 'EnvironmentNode';
  18617. }
  18618. /**
  18619. * Constructs a new environment node.
  18620. *
  18621. * @param {Node} [envNode=null] - A node representing the environment.
  18622. */
  18623. constructor( envNode = null ) {
  18624. super();
  18625. /**
  18626. * A node representing the environment.
  18627. *
  18628. * @type {?Node}
  18629. * @default null
  18630. */
  18631. this.envNode = envNode;
  18632. }
  18633. setup( builder ) {
  18634. const { material } = builder;
  18635. let envNode = this.envNode;
  18636. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  18637. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  18638. let cacheEnvNode = _envNodeCache.get( value );
  18639. if ( cacheEnvNode === undefined ) {
  18640. cacheEnvNode = pmremTexture( value );
  18641. _envNodeCache.set( value, cacheEnvNode );
  18642. }
  18643. envNode = cacheEnvNode;
  18644. }
  18645. //
  18646. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  18647. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  18648. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  18649. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  18650. const isolateRadiance = isolate( radiance );
  18651. const isolateIrradiance = isolate( irradiance );
  18652. //
  18653. builder.context.radiance.addAssign( isolateRadiance );
  18654. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  18655. //
  18656. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  18657. if ( clearcoatRadiance ) {
  18658. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  18659. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  18660. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  18661. }
  18662. }
  18663. }
  18664. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  18665. let reflectVec = null;
  18666. return {
  18667. getUV: () => {
  18668. if ( reflectVec === null ) {
  18669. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  18670. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  18671. reflectVec = pow4( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  18672. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  18673. }
  18674. return reflectVec;
  18675. },
  18676. getTextureLevel: () => {
  18677. return roughnessNode;
  18678. }
  18679. };
  18680. };
  18681. const createIrradianceContext = ( normalWorldNode ) => {
  18682. return {
  18683. getUV: () => {
  18684. return normalWorldNode;
  18685. },
  18686. getTextureLevel: () => {
  18687. return float( 1.0 );
  18688. }
  18689. };
  18690. };
  18691. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  18692. /**
  18693. * Node material version of {@link MeshStandardMaterial}.
  18694. *
  18695. * @augments NodeMaterial
  18696. */
  18697. class MeshStandardNodeMaterial extends NodeMaterial {
  18698. static get type() {
  18699. return 'MeshStandardNodeMaterial';
  18700. }
  18701. /**
  18702. * Constructs a new mesh standard node material.
  18703. *
  18704. * @param {Object} [parameters] - The configuration parameter.
  18705. */
  18706. constructor( parameters ) {
  18707. super();
  18708. /**
  18709. * This flag can be used for type testing.
  18710. *
  18711. * @type {boolean}
  18712. * @readonly
  18713. * @default true
  18714. */
  18715. this.isMeshStandardNodeMaterial = true;
  18716. /**
  18717. * Set to `true` because standard materials react on lights.
  18718. *
  18719. * @type {boolean}
  18720. * @default true
  18721. */
  18722. this.lights = true;
  18723. /**
  18724. * The emissive color of standard materials is by default inferred from the `emissive`,
  18725. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  18726. * overwrite the default and define the emissive color with a node instead.
  18727. *
  18728. * If you don't want to overwrite the emissive color but modify the existing
  18729. * value instead, use {@link materialEmissive}.
  18730. *
  18731. * @type {?Node<vec3>}
  18732. * @default null
  18733. */
  18734. this.emissiveNode = null;
  18735. /**
  18736. * The metalness of standard materials is by default inferred from the `metalness`,
  18737. * and `metalnessMap` properties. This node property allows to
  18738. * overwrite the default and define the metalness with a node instead.
  18739. *
  18740. * If you don't want to overwrite the metalness but modify the existing
  18741. * value instead, use {@link materialMetalness}.
  18742. *
  18743. * @type {?Node<float>}
  18744. * @default null
  18745. */
  18746. this.metalnessNode = null;
  18747. /**
  18748. * The roughness of standard materials is by default inferred from the `roughness`,
  18749. * and `roughnessMap` properties. This node property allows to
  18750. * overwrite the default and define the roughness with a node instead.
  18751. *
  18752. * If you don't want to overwrite the roughness but modify the existing
  18753. * value instead, use {@link materialRoughness}.
  18754. *
  18755. * @type {?Node<float>}
  18756. * @default null
  18757. */
  18758. this.roughnessNode = null;
  18759. this.setDefaultValues( _defaultValues$6 );
  18760. this.setValues( parameters );
  18761. }
  18762. /**
  18763. * Overwritten since this type of material uses {@link EnvironmentNode}
  18764. * to implement the PBR (PMREM based) environment mapping. Besides, the
  18765. * method honors `Scene.environment`.
  18766. *
  18767. * @param {NodeBuilder} builder - The current node builder.
  18768. * @return {?EnvironmentNode<vec3>} The environment node.
  18769. */
  18770. setupEnvironment( builder ) {
  18771. let envNode = super.setupEnvironment( builder );
  18772. if ( envNode === null && builder.environmentNode ) {
  18773. envNode = builder.environmentNode;
  18774. }
  18775. return envNode ? new EnvironmentNode( envNode ) : null;
  18776. }
  18777. /**
  18778. * Setups the lighting model.
  18779. *
  18780. * @return {PhysicalLightingModel} The lighting model.
  18781. */
  18782. setupLightingModel( /*builder*/ ) {
  18783. return new PhysicalLightingModel();
  18784. }
  18785. /**
  18786. * Setups the specular related node variables.
  18787. */
  18788. setupSpecular() {
  18789. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  18790. specularColor.assign( vec3( 0.04 ) );
  18791. specularColorBlended.assign( specularColorNode );
  18792. specularF90.assign( 1.0 );
  18793. }
  18794. /**
  18795. * Setups the standard specific node variables.
  18796. *
  18797. * @param {NodeBuilder} builder - The current node builder.
  18798. */
  18799. setupVariants() {
  18800. // METALNESS
  18801. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  18802. metalness.assign( metalnessNode );
  18803. // ROUGHNESS
  18804. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  18805. roughnessNode = getRoughness( { roughness: roughnessNode } );
  18806. roughness.assign( roughnessNode );
  18807. // SPECULAR COLOR
  18808. this.setupSpecular();
  18809. // DIFFUSE COLOR
  18810. diffuseContribution.assign( diffuseColor.rgb.mul( metalnessNode.oneMinus() ) );
  18811. }
  18812. copy( source ) {
  18813. this.emissiveNode = source.emissiveNode;
  18814. this.metalnessNode = source.metalnessNode;
  18815. this.roughnessNode = source.roughnessNode;
  18816. return super.copy( source );
  18817. }
  18818. }
  18819. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  18820. /**
  18821. * Node material version of {@link MeshPhysicalMaterial}.
  18822. *
  18823. * @augments MeshStandardNodeMaterial
  18824. */
  18825. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  18826. static get type() {
  18827. return 'MeshPhysicalNodeMaterial';
  18828. }
  18829. /**
  18830. * Constructs a new mesh physical node material.
  18831. *
  18832. * @param {Object} [parameters] - The configuration parameter.
  18833. */
  18834. constructor( parameters ) {
  18835. super();
  18836. /**
  18837. * This flag can be used for type testing.
  18838. *
  18839. * @type {boolean}
  18840. * @readonly
  18841. * @default true
  18842. */
  18843. this.isMeshPhysicalNodeMaterial = true;
  18844. /**
  18845. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  18846. * and `clearcoatMap` properties. This node property allows to overwrite the default
  18847. * and define the clearcoat with a node instead.
  18848. *
  18849. * If you don't want to overwrite the clearcoat but modify the existing
  18850. * value instead, use {@link materialClearcoat}.
  18851. *
  18852. * @type {?Node<float>}
  18853. * @default null
  18854. */
  18855. this.clearcoatNode = null;
  18856. /**
  18857. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  18858. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  18859. * and define the clearcoat roughness with a node instead.
  18860. *
  18861. * If you don't want to overwrite the clearcoat roughness but modify the existing
  18862. * value instead, use {@link materialClearcoatRoughness}.
  18863. *
  18864. * @type {?Node<float>}
  18865. * @default null
  18866. */
  18867. this.clearcoatRoughnessNode = null;
  18868. /**
  18869. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  18870. * property. This node property allows to overwrite the default
  18871. * and define the clearcoat normal with a node instead.
  18872. *
  18873. * If you don't want to overwrite the clearcoat normal but modify the existing
  18874. * value instead, use {@link materialClearcoatNormal}.
  18875. *
  18876. * @type {?Node<vec3>}
  18877. * @default null
  18878. */
  18879. this.clearcoatNormalNode = null;
  18880. /**
  18881. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  18882. * and `sheenColorMap` properties. This node property allows to overwrite the default
  18883. * and define the sheen with a node instead.
  18884. *
  18885. * If you don't want to overwrite the sheen but modify the existing
  18886. * value instead, use {@link materialSheen}.
  18887. *
  18888. * @type {?Node<vec3>}
  18889. * @default null
  18890. */
  18891. this.sheenNode = null;
  18892. /**
  18893. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  18894. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  18895. * and define the sheen roughness with a node instead.
  18896. *
  18897. * If you don't want to overwrite the sheen roughness but modify the existing
  18898. * value instead, use {@link materialSheenRoughness}.
  18899. *
  18900. * @type {?Node<float>}
  18901. * @default null
  18902. */
  18903. this.sheenRoughnessNode = null;
  18904. /**
  18905. * The iridescence of physical materials is by default inferred from the `iridescence`
  18906. * property. This node property allows to overwrite the default
  18907. * and define the iridescence with a node instead.
  18908. *
  18909. * If you don't want to overwrite the iridescence but modify the existing
  18910. * value instead, use {@link materialIridescence}.
  18911. *
  18912. * @type {?Node<float>}
  18913. * @default null
  18914. */
  18915. this.iridescenceNode = null;
  18916. /**
  18917. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  18918. * property. This node property allows to overwrite the default
  18919. * and define the iridescence IOR with a node instead.
  18920. *
  18921. * If you don't want to overwrite the iridescence IOR but modify the existing
  18922. * value instead, use {@link materialIridescenceIOR}.
  18923. *
  18924. * @type {?Node<float>}
  18925. * @default null
  18926. */
  18927. this.iridescenceIORNode = null;
  18928. /**
  18929. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  18930. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  18931. * and define the iridescence thickness with a node instead.
  18932. *
  18933. * If you don't want to overwrite the iridescence thickness but modify the existing
  18934. * value instead, use {@link materialIridescenceThickness}.
  18935. *
  18936. * @type {?Node<float>}
  18937. * @default null
  18938. */
  18939. this.iridescenceThicknessNode = null;
  18940. /**
  18941. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  18942. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  18943. * and define the specular intensity with a node instead.
  18944. *
  18945. * If you don't want to overwrite the specular intensity but modify the existing
  18946. * value instead, use {@link materialSpecularIntensity}.
  18947. *
  18948. * @type {?Node<float>}
  18949. * @default null
  18950. */
  18951. this.specularIntensityNode = null;
  18952. /**
  18953. * The specular color of physical materials is by default inferred from the `specularColor`
  18954. * and `specularColorMap` properties. This node property allows to overwrite the default
  18955. * and define the specular color with a node instead.
  18956. *
  18957. * If you don't want to overwrite the specular color but modify the existing
  18958. * value instead, use {@link materialSpecularColor}.
  18959. *
  18960. * @type {?Node<vec3>}
  18961. * @default null
  18962. */
  18963. this.specularColorNode = null;
  18964. /**
  18965. * The ior of physical materials is by default inferred from the `ior`
  18966. * property. This node property allows to overwrite the default
  18967. * and define the ior with a node instead.
  18968. *
  18969. * If you don't want to overwrite the ior but modify the existing
  18970. * value instead, use {@link materialIOR}.
  18971. *
  18972. * @type {?Node<float>}
  18973. * @default null
  18974. */
  18975. this.iorNode = null;
  18976. /**
  18977. * The transmission of physical materials is by default inferred from the `transmission` and
  18978. * `transmissionMap` properties. This node property allows to overwrite the default
  18979. * and define the transmission with a node instead.
  18980. *
  18981. * If you don't want to overwrite the transmission but modify the existing
  18982. * value instead, use {@link materialTransmission}.
  18983. *
  18984. * @type {?Node<float>}
  18985. * @default null
  18986. */
  18987. this.transmissionNode = null;
  18988. /**
  18989. * The thickness of physical materials is by default inferred from the `thickness` and
  18990. * `thicknessMap` properties. This node property allows to overwrite the default
  18991. * and define the thickness with a node instead.
  18992. *
  18993. * If you don't want to overwrite the thickness but modify the existing
  18994. * value instead, use {@link materialThickness}.
  18995. *
  18996. * @type {?Node<float>}
  18997. * @default null
  18998. */
  18999. this.thicknessNode = null;
  19000. /**
  19001. * The attenuation distance of physical materials is by default inferred from the
  19002. * `attenuationDistance` property. This node property allows to overwrite the default
  19003. * and define the attenuation distance with a node instead.
  19004. *
  19005. * If you don't want to overwrite the attenuation distance but modify the existing
  19006. * value instead, use {@link materialAttenuationDistance}.
  19007. *
  19008. * @type {?Node<float>}
  19009. * @default null
  19010. */
  19011. this.attenuationDistanceNode = null;
  19012. /**
  19013. * The attenuation color of physical materials is by default inferred from the
  19014. * `attenuationColor` property. This node property allows to overwrite the default
  19015. * and define the attenuation color with a node instead.
  19016. *
  19017. * If you don't want to overwrite the attenuation color but modify the existing
  19018. * value instead, use {@link materialAttenuationColor}.
  19019. *
  19020. * @type {?Node<vec3>}
  19021. * @default null
  19022. */
  19023. this.attenuationColorNode = null;
  19024. /**
  19025. * The dispersion of physical materials is by default inferred from the
  19026. * `dispersion` property. This node property allows to overwrite the default
  19027. * and define the dispersion with a node instead.
  19028. *
  19029. * If you don't want to overwrite the dispersion but modify the existing
  19030. * value instead, use {@link materialDispersion}.
  19031. *
  19032. * @type {?Node<float>}
  19033. * @default null
  19034. */
  19035. this.dispersionNode = null;
  19036. /**
  19037. * The anisotropy of physical materials is by default inferred from the
  19038. * `anisotropy` property. This node property allows to overwrite the default
  19039. * and define the anisotropy with a node instead.
  19040. *
  19041. * If you don't want to overwrite the anisotropy but modify the existing
  19042. * value instead, use {@link materialAnisotropy}.
  19043. *
  19044. * @type {?Node<float>}
  19045. * @default null
  19046. */
  19047. this.anisotropyNode = null;
  19048. this.setDefaultValues( _defaultValues$5 );
  19049. this.setValues( parameters );
  19050. }
  19051. /**
  19052. * Whether the lighting model should use clearcoat or not.
  19053. *
  19054. * @type {boolean}
  19055. * @default true
  19056. */
  19057. get useClearcoat() {
  19058. return this.clearcoat > 0 || this.clearcoatNode !== null;
  19059. }
  19060. /**
  19061. * Whether the lighting model should use iridescence or not.
  19062. *
  19063. * @type {boolean}
  19064. * @default true
  19065. */
  19066. get useIridescence() {
  19067. return this.iridescence > 0 || this.iridescenceNode !== null;
  19068. }
  19069. /**
  19070. * Whether the lighting model should use sheen or not.
  19071. *
  19072. * @type {boolean}
  19073. * @default true
  19074. */
  19075. get useSheen() {
  19076. return this.sheen > 0 || this.sheenNode !== null;
  19077. }
  19078. /**
  19079. * Whether the lighting model should use anisotropy or not.
  19080. *
  19081. * @type {boolean}
  19082. * @default true
  19083. */
  19084. get useAnisotropy() {
  19085. return this.anisotropy > 0 || this.anisotropyNode !== null;
  19086. }
  19087. /**
  19088. * Whether the lighting model should use transmission or not.
  19089. *
  19090. * @type {boolean}
  19091. * @default true
  19092. */
  19093. get useTransmission() {
  19094. return this.transmission > 0 || this.transmissionNode !== null;
  19095. }
  19096. /**
  19097. * Whether the lighting model should use dispersion or not.
  19098. *
  19099. * @type {boolean}
  19100. * @default true
  19101. */
  19102. get useDispersion() {
  19103. return this.dispersion > 0 || this.dispersionNode !== null;
  19104. }
  19105. /**
  19106. * Setups the specular related node variables.
  19107. */
  19108. setupSpecular() {
  19109. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  19110. ior.assign( iorNode );
  19111. specularColor.assign( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ) );
  19112. specularColorBlended.assign( mix( specularColor, diffuseColor.rgb, metalness ) );
  19113. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  19114. }
  19115. /**
  19116. * Setups the lighting model.
  19117. *
  19118. * @return {PhysicalLightingModel} The lighting model.
  19119. */
  19120. setupLightingModel( /*builder*/ ) {
  19121. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  19122. }
  19123. /**
  19124. * Setups the physical specific node variables.
  19125. *
  19126. * @param {NodeBuilder} builder - The current node builder.
  19127. */
  19128. setupVariants( builder ) {
  19129. super.setupVariants( builder );
  19130. // CLEARCOAT
  19131. if ( this.useClearcoat ) {
  19132. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  19133. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  19134. clearcoat.assign( clearcoatNode );
  19135. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  19136. }
  19137. // SHEEN
  19138. if ( this.useSheen ) {
  19139. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  19140. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  19141. sheen.assign( sheenNode );
  19142. sheenRoughness.assign( sheenRoughnessNode );
  19143. }
  19144. // IRIDESCENCE
  19145. if ( this.useIridescence ) {
  19146. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  19147. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  19148. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  19149. iridescence.assign( iridescenceNode );
  19150. iridescenceIOR.assign( iridescenceIORNode );
  19151. iridescenceThickness.assign( iridescenceThicknessNode );
  19152. }
  19153. // ANISOTROPY
  19154. if ( this.useAnisotropy ) {
  19155. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  19156. anisotropy.assign( anisotropyV.length() );
  19157. If( anisotropy.equal( 0.0 ), () => {
  19158. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  19159. } ).Else( () => {
  19160. anisotropyV.divAssign( vec2( anisotropy ) );
  19161. anisotropy.assign( anisotropy.saturate() );
  19162. } );
  19163. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  19164. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  19165. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  19166. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  19167. }
  19168. // TRANSMISSION
  19169. if ( this.useTransmission ) {
  19170. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  19171. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  19172. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  19173. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  19174. transmission.assign( transmissionNode );
  19175. thickness.assign( thicknessNode );
  19176. attenuationDistance.assign( attenuationDistanceNode );
  19177. attenuationColor.assign( attenuationColorNode );
  19178. if ( this.useDispersion ) {
  19179. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  19180. dispersion.assign( dispersionNode );
  19181. }
  19182. }
  19183. }
  19184. /**
  19185. * Setups the clearcoat normal node.
  19186. *
  19187. * @return {Node<vec3>} The clearcoat normal.
  19188. */
  19189. setupClearcoatNormal() {
  19190. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  19191. }
  19192. setup( builder ) {
  19193. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  19194. super.setup( builder );
  19195. }
  19196. copy( source ) {
  19197. this.clearcoatNode = source.clearcoatNode;
  19198. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  19199. this.clearcoatNormalNode = source.clearcoatNormalNode;
  19200. this.sheenNode = source.sheenNode;
  19201. this.sheenRoughnessNode = source.sheenRoughnessNode;
  19202. this.iridescenceNode = source.iridescenceNode;
  19203. this.iridescenceIORNode = source.iridescenceIORNode;
  19204. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  19205. this.specularIntensityNode = source.specularIntensityNode;
  19206. this.specularColorNode = source.specularColorNode;
  19207. this.transmissionNode = source.transmissionNode;
  19208. this.thicknessNode = source.thicknessNode;
  19209. this.attenuationDistanceNode = source.attenuationDistanceNode;
  19210. this.attenuationColorNode = source.attenuationColorNode;
  19211. this.dispersionNode = source.dispersionNode;
  19212. this.anisotropyNode = source.anisotropyNode;
  19213. return super.copy( source );
  19214. }
  19215. }
  19216. /**
  19217. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  19218. *
  19219. * @augments PhysicalLightingModel
  19220. */
  19221. class SSSLightingModel extends PhysicalLightingModel {
  19222. /**
  19223. * Constructs a new physical lighting model.
  19224. *
  19225. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  19226. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  19227. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  19228. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  19229. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  19230. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  19231. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  19232. */
  19233. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  19234. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  19235. /**
  19236. * Whether the lighting model should use SSS or not.
  19237. *
  19238. * @type {boolean}
  19239. * @default false
  19240. */
  19241. this.useSSS = sss;
  19242. }
  19243. /**
  19244. * Extends the default implementation with a SSS term.
  19245. *
  19246. * 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/)
  19247. *
  19248. * @param {Object} input - The input data.
  19249. * @param {NodeBuilder} builder - The current node builder.
  19250. */
  19251. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19252. if ( this.useSSS === true ) {
  19253. const material = builder.material;
  19254. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  19255. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  19256. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  19257. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  19258. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  19259. }
  19260. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  19261. }
  19262. }
  19263. /**
  19264. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  19265. * that implements a Subsurface scattering (SSS) term.
  19266. *
  19267. * @augments MeshPhysicalNodeMaterial
  19268. */
  19269. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  19270. static get type() {
  19271. return 'MeshSSSNodeMaterial';
  19272. }
  19273. /**
  19274. * Constructs a new mesh SSS node material.
  19275. *
  19276. * @param {Object} [parameters] - The configuration parameter.
  19277. */
  19278. constructor( parameters ) {
  19279. super( parameters );
  19280. /**
  19281. * Represents the thickness color.
  19282. *
  19283. * @type {?Node<vec3>}
  19284. * @default null
  19285. */
  19286. this.thicknessColorNode = null;
  19287. /**
  19288. * Represents the distortion factor.
  19289. *
  19290. * @type {?Node<float>}
  19291. */
  19292. this.thicknessDistortionNode = float( 0.1 );
  19293. /**
  19294. * Represents the thickness ambient factor.
  19295. *
  19296. * @type {?Node<float>}
  19297. */
  19298. this.thicknessAmbientNode = float( 0.0 );
  19299. /**
  19300. * Represents the thickness attenuation.
  19301. *
  19302. * @type {?Node<float>}
  19303. */
  19304. this.thicknessAttenuationNode = float( .1 );
  19305. /**
  19306. * Represents the thickness power.
  19307. *
  19308. * @type {?Node<float>}
  19309. */
  19310. this.thicknessPowerNode = float( 2.0 );
  19311. /**
  19312. * Represents the thickness scale.
  19313. *
  19314. * @type {?Node<float>}
  19315. */
  19316. this.thicknessScaleNode = float( 10.0 );
  19317. }
  19318. /**
  19319. * Whether the lighting model should use SSS or not.
  19320. *
  19321. * @type {boolean}
  19322. * @default true
  19323. */
  19324. get useSSS() {
  19325. return this.thicknessColorNode !== null;
  19326. }
  19327. /**
  19328. * Setups the lighting model.
  19329. *
  19330. * @return {SSSLightingModel} The lighting model.
  19331. */
  19332. setupLightingModel( /*builder*/ ) {
  19333. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  19334. }
  19335. copy( source ) {
  19336. this.thicknessColorNode = source.thicknessColorNode;
  19337. this.thicknessDistortionNode = source.thicknessDistortionNode;
  19338. this.thicknessAmbientNode = source.thicknessAmbientNode;
  19339. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  19340. this.thicknessPowerNode = source.thicknessPowerNode;
  19341. this.thicknessScaleNode = source.thicknessScaleNode;
  19342. return super.copy( source );
  19343. }
  19344. }
  19345. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  19346. // dotNL will be from -1.0 to 1.0
  19347. const dotNL = normal.dot( lightDirection );
  19348. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  19349. if ( builder.material.gradientMap ) {
  19350. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  19351. return vec3( gradientMap.r );
  19352. } else {
  19353. const fw = coord.fwidth().mul( 0.5 );
  19354. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  19355. }
  19356. } );
  19357. /**
  19358. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  19359. *
  19360. * @augments LightingModel
  19361. */
  19362. class ToonLightingModel extends LightingModel {
  19363. /**
  19364. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  19365. * reduced to a small number of discrete shades to create a comic-like, flat look.
  19366. *
  19367. * @param {Object} lightData - The light data.
  19368. * @param {NodeBuilder} builder - The current node builder.
  19369. */
  19370. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19371. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  19372. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  19373. }
  19374. /**
  19375. * Implements the indirect lighting.
  19376. *
  19377. * @param {NodeBuilder} builder - The current node builder.
  19378. */
  19379. indirect( builder ) {
  19380. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  19381. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  19382. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  19383. }
  19384. }
  19385. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  19386. /**
  19387. * Node material version of {@link MeshToonMaterial}.
  19388. *
  19389. * @augments NodeMaterial
  19390. */
  19391. class MeshToonNodeMaterial extends NodeMaterial {
  19392. static get type() {
  19393. return 'MeshToonNodeMaterial';
  19394. }
  19395. /**
  19396. * Constructs a new mesh toon node material.
  19397. *
  19398. * @param {Object} [parameters] - The configuration parameter.
  19399. */
  19400. constructor( parameters ) {
  19401. super();
  19402. /**
  19403. * This flag can be used for type testing.
  19404. *
  19405. * @type {boolean}
  19406. * @readonly
  19407. * @default true
  19408. */
  19409. this.isMeshToonNodeMaterial = true;
  19410. /**
  19411. * Set to `true` because toon materials react on lights.
  19412. *
  19413. * @type {boolean}
  19414. * @default true
  19415. */
  19416. this.lights = true;
  19417. this.setDefaultValues( _defaultValues$4 );
  19418. this.setValues( parameters );
  19419. }
  19420. /**
  19421. * Setups the lighting model.
  19422. *
  19423. * @return {ToonLightingModel} The lighting model.
  19424. */
  19425. setupLightingModel( /*builder*/ ) {
  19426. return new ToonLightingModel();
  19427. }
  19428. }
  19429. /**
  19430. * TSL function for creating a matcap uv node.
  19431. *
  19432. * Can be used to compute texture coordinates for projecting a
  19433. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  19434. *
  19435. * @tsl
  19436. * @function
  19437. * @returns {Node<vec2>} The matcap UV coordinates.
  19438. */
  19439. const matcapUV = /*@__PURE__*/ Fn( () => {
  19440. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  19441. const y = positionViewDirection.cross( x );
  19442. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  19443. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  19444. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  19445. /**
  19446. * Node material version of {@link MeshMatcapMaterial}.
  19447. *
  19448. * @augments NodeMaterial
  19449. */
  19450. class MeshMatcapNodeMaterial extends NodeMaterial {
  19451. static get type() {
  19452. return 'MeshMatcapNodeMaterial';
  19453. }
  19454. /**
  19455. * Constructs a new mesh normal node material.
  19456. *
  19457. * @param {Object} [parameters] - The configuration parameter.
  19458. */
  19459. constructor( parameters ) {
  19460. super();
  19461. /**
  19462. * This flag can be used for type testing.
  19463. *
  19464. * @type {boolean}
  19465. * @readonly
  19466. * @default true
  19467. */
  19468. this.isMeshMatcapNodeMaterial = true;
  19469. this.setDefaultValues( _defaultValues$3 );
  19470. this.setValues( parameters );
  19471. }
  19472. /**
  19473. * Setups the matcap specific node variables.
  19474. *
  19475. * @param {NodeBuilder} builder - The current node builder.
  19476. */
  19477. setupVariants( builder ) {
  19478. const uv = matcapUV;
  19479. let matcapColor;
  19480. if ( builder.material.matcap ) {
  19481. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  19482. } else {
  19483. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  19484. }
  19485. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  19486. }
  19487. }
  19488. /**
  19489. * Applies a rotation to the given position node.
  19490. *
  19491. * @augments TempNode
  19492. */
  19493. class RotateNode extends TempNode {
  19494. static get type() {
  19495. return 'RotateNode';
  19496. }
  19497. /**
  19498. * Constructs a new rotate node.
  19499. *
  19500. * @param {Node} positionNode - The position node.
  19501. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19502. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19503. */
  19504. constructor( positionNode, rotationNode ) {
  19505. super();
  19506. /**
  19507. * The position node.
  19508. *
  19509. * @type {Node}
  19510. */
  19511. this.positionNode = positionNode;
  19512. /**
  19513. * Represents the rotation that is applied to the position node.
  19514. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19515. *
  19516. * @type {Node}
  19517. */
  19518. this.rotationNode = rotationNode;
  19519. }
  19520. /**
  19521. * The type of the {@link RotateNode#positionNode} defines the node's type.
  19522. *
  19523. * @param {NodeBuilder} builder - The current node builder.
  19524. * @return {string} The node's type.
  19525. */
  19526. getNodeType( builder ) {
  19527. return this.positionNode.getNodeType( builder );
  19528. }
  19529. setup( builder ) {
  19530. const { rotationNode, positionNode } = this;
  19531. const nodeType = this.getNodeType( builder );
  19532. if ( nodeType === 'vec2' ) {
  19533. const cosAngle = rotationNode.cos();
  19534. const sinAngle = rotationNode.sin();
  19535. const rotationMatrix = mat2(
  19536. cosAngle, sinAngle,
  19537. sinAngle.negate(), cosAngle
  19538. );
  19539. return rotationMatrix.mul( positionNode );
  19540. } else {
  19541. const rotation = rotationNode;
  19542. 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 ) );
  19543. 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 ) );
  19544. 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 ) );
  19545. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  19546. }
  19547. }
  19548. }
  19549. /**
  19550. * TSL function for creating a rotate node.
  19551. *
  19552. * @tsl
  19553. * @function
  19554. * @param {Node} positionNode - The position node.
  19555. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19556. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19557. * @returns {RotateNode}
  19558. */
  19559. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  19560. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  19561. /**
  19562. * Node material version of {@link SpriteMaterial}.
  19563. *
  19564. * @augments NodeMaterial
  19565. */
  19566. class SpriteNodeMaterial extends NodeMaterial {
  19567. static get type() {
  19568. return 'SpriteNodeMaterial';
  19569. }
  19570. /**
  19571. * Constructs a new sprite node material.
  19572. *
  19573. * @param {Object} [parameters] - The configuration parameter.
  19574. */
  19575. constructor( parameters ) {
  19576. super();
  19577. /**
  19578. * This flag can be used for type testing.
  19579. *
  19580. * @type {boolean}
  19581. * @readonly
  19582. * @default true
  19583. */
  19584. this.isSpriteNodeMaterial = true;
  19585. this._useSizeAttenuation = true;
  19586. /**
  19587. * This property makes it possible to define the position of the sprite with a
  19588. * node. That can be useful when the material is used with instanced rendering
  19589. * and node data are defined with an instanced attribute node:
  19590. * ```js
  19591. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  19592. * material.positionNode = instancedBufferAttribute( positionAttribute );
  19593. * ```
  19594. * Another possibility is to compute the instanced data with a compute shader:
  19595. * ```js
  19596. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  19597. * particleMaterial.positionNode = positionBuffer.toAttribute();
  19598. * ```
  19599. *
  19600. * @type {?Node<vec2>}
  19601. * @default null
  19602. */
  19603. this.positionNode = null;
  19604. /**
  19605. * The rotation of sprite materials is by default inferred from the `rotation`,
  19606. * property. This node property allows to overwrite the default and define
  19607. * the rotation with a node instead.
  19608. *
  19609. * If you don't want to overwrite the rotation but modify the existing
  19610. * value instead, use {@link materialRotation}.
  19611. *
  19612. * @type {?Node<float>}
  19613. * @default null
  19614. */
  19615. this.rotationNode = null;
  19616. /**
  19617. * This node property provides an additional way to scale sprites next to
  19618. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  19619. * is multiplied with the scale value of this node in the vertex shader.
  19620. *
  19621. * @type {?Node<vec2>}
  19622. * @default null
  19623. */
  19624. this.scaleNode = null;
  19625. /**
  19626. * In Sprites, the transparent property is enabled by default.
  19627. *
  19628. * @type {boolean}
  19629. * @default true
  19630. */
  19631. this.transparent = true;
  19632. this.setDefaultValues( _defaultValues$2 );
  19633. this.setValues( parameters );
  19634. }
  19635. /**
  19636. * Setups the position node in view space. This method implements
  19637. * the sprite specific vertex shader.
  19638. *
  19639. * @param {NodeBuilder} builder - The current node builder.
  19640. * @return {Node<vec3>} The position in view space.
  19641. */
  19642. setupPositionView( builder ) {
  19643. const { object, camera } = builder;
  19644. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  19645. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  19646. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  19647. if ( scaleNode !== null ) {
  19648. scale = scale.mul( vec2( scaleNode ) );
  19649. }
  19650. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  19651. scale = scale.mul( mvPosition.z.negate() );
  19652. }
  19653. let alignedPosition = positionGeometry.xy;
  19654. if ( object.center && object.center.isVector2 === true ) {
  19655. const center = reference$1( 'center', 'vec2', object );
  19656. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  19657. }
  19658. alignedPosition = alignedPosition.mul( scale );
  19659. const rotation = float( rotationNode || materialRotation );
  19660. const rotatedPosition = rotate( alignedPosition, rotation );
  19661. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  19662. }
  19663. copy( source ) {
  19664. this.positionNode = source.positionNode;
  19665. this.rotationNode = source.rotationNode;
  19666. this.scaleNode = source.scaleNode;
  19667. return super.copy( source );
  19668. }
  19669. /**
  19670. * Whether to use size attenuation or not.
  19671. *
  19672. * @type {boolean}
  19673. * @default true
  19674. */
  19675. get sizeAttenuation() {
  19676. return this._useSizeAttenuation;
  19677. }
  19678. set sizeAttenuation( value ) {
  19679. if ( this._useSizeAttenuation !== value ) {
  19680. this._useSizeAttenuation = value;
  19681. this.needsUpdate = true;
  19682. }
  19683. }
  19684. }
  19685. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  19686. const _size$4 = /*@__PURE__*/ new Vector2();
  19687. /**
  19688. * Node material version of {@link PointsMaterial}.
  19689. *
  19690. * This material can be used in two ways:
  19691. *
  19692. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  19693. * with a pixel size of `1`, it's not possible to define a size.
  19694. *
  19695. * ```js
  19696. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  19697. * ```
  19698. *
  19699. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  19700. * see {@link PointsNodeMaterial#sizeNode}.
  19701. *
  19702. * ```js
  19703. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  19704. * ```
  19705. *
  19706. * @augments SpriteNodeMaterial
  19707. */
  19708. class PointsNodeMaterial extends SpriteNodeMaterial {
  19709. static get type() {
  19710. return 'PointsNodeMaterial';
  19711. }
  19712. /**
  19713. * Constructs a new points node material.
  19714. *
  19715. * @param {Object} [parameters] - The configuration parameter.
  19716. */
  19717. constructor( parameters ) {
  19718. super();
  19719. /**
  19720. * This node property provides an additional way to set the point size.
  19721. *
  19722. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  19723. * this node has no effect when the material is used with {@link Points} and a WebGPU
  19724. * backend. If an application wants to render points with a size larger than 1 pixel,
  19725. * the material should be used with {@link Sprite} and instancing.
  19726. *
  19727. * @type {?Node<vec2>}
  19728. * @default null
  19729. */
  19730. this.sizeNode = null;
  19731. /**
  19732. * This flag can be used for type testing.
  19733. *
  19734. * @type {boolean}
  19735. * @readonly
  19736. * @default true
  19737. */
  19738. this.isPointsNodeMaterial = true;
  19739. this.setDefaultValues( _defaultValues$1 );
  19740. this.setValues( parameters );
  19741. }
  19742. setupPositionView() {
  19743. const { positionNode } = this;
  19744. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  19745. }
  19746. setupVertexSprite( builder ) {
  19747. const { material, camera } = builder;
  19748. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  19749. let mvp = super.setupVertex( builder );
  19750. // skip further processing if the material is not a node material
  19751. if ( material.isNodeMaterial !== true ) {
  19752. return mvp;
  19753. }
  19754. // point size
  19755. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  19756. pointSize = pointSize.mul( screenDPR );
  19757. // size attenuation
  19758. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  19759. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  19760. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  19761. }
  19762. // scale
  19763. if ( scaleNode && scaleNode.isNode ) {
  19764. pointSize = pointSize.mul( vec2( scaleNode ) );
  19765. }
  19766. // compute offset
  19767. let offset = positionGeometry.xy;
  19768. // apply rotation
  19769. if ( rotationNode && rotationNode.isNode ) {
  19770. const rotation = float( rotationNode );
  19771. offset = rotate( offset, rotation );
  19772. }
  19773. // account for point size
  19774. offset = offset.mul( pointSize );
  19775. // scale by viewport size
  19776. offset = offset.div( viewportSize.div( 2 ) );
  19777. // compensate for the perspective divide
  19778. offset = offset.mul( mvp.w );
  19779. // add offset
  19780. mvp = mvp.add( vec4( offset, 0, 0 ) );
  19781. return mvp;
  19782. }
  19783. setupVertex( builder ) {
  19784. if ( builder.object.isPoints ) {
  19785. return super.setupVertex( builder );
  19786. } else {
  19787. return this.setupVertexSprite( builder );
  19788. }
  19789. }
  19790. /**
  19791. * Whether alpha to coverage should be used or not.
  19792. *
  19793. * @type {boolean}
  19794. * @default true
  19795. */
  19796. get alphaToCoverage() {
  19797. return this._useAlphaToCoverage;
  19798. }
  19799. set alphaToCoverage( value ) {
  19800. if ( this._useAlphaToCoverage !== value ) {
  19801. this._useAlphaToCoverage = value;
  19802. this.needsUpdate = true;
  19803. }
  19804. }
  19805. }
  19806. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  19807. const size = renderer.getSize( _size$4 ); // logical units
  19808. this.value = 0.5 * size.y;
  19809. } );
  19810. /**
  19811. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  19812. *
  19813. * @augments LightingModel
  19814. */
  19815. class ShadowMaskModel extends LightingModel {
  19816. /**
  19817. * Constructs a new shadow mask model.
  19818. */
  19819. constructor() {
  19820. super();
  19821. /**
  19822. * The shadow mask node.
  19823. *
  19824. * @type {Node}
  19825. */
  19826. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  19827. }
  19828. /**
  19829. * Only used to save the shadow mask.
  19830. *
  19831. * @param {Object} input - The input data.
  19832. */
  19833. direct( { lightNode } ) {
  19834. if ( lightNode.shadowNode !== null ) {
  19835. this.shadowNode.mulAssign( lightNode.shadowNode );
  19836. }
  19837. }
  19838. /**
  19839. * Uses the shadow mask to produce the final color.
  19840. *
  19841. * @param {NodeBuilder} builder - The current node builder.
  19842. */
  19843. finish( { context } ) {
  19844. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  19845. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  19846. }
  19847. }
  19848. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  19849. /**
  19850. * Node material version of {@link ShadowMaterial}.
  19851. *
  19852. * @augments NodeMaterial
  19853. */
  19854. class ShadowNodeMaterial extends NodeMaterial {
  19855. static get type() {
  19856. return 'ShadowNodeMaterial';
  19857. }
  19858. /**
  19859. * Constructs a new shadow node material.
  19860. *
  19861. * @param {Object} [parameters] - The configuration parameter.
  19862. */
  19863. constructor( parameters ) {
  19864. super();
  19865. /**
  19866. * This flag can be used for type testing.
  19867. *
  19868. * @type {boolean}
  19869. * @readonly
  19870. * @default true
  19871. */
  19872. this.isShadowNodeMaterial = true;
  19873. /**
  19874. * Set to `true` because so it's possible to implement
  19875. * the shadow mask effect.
  19876. *
  19877. * @type {boolean}
  19878. * @default true
  19879. */
  19880. this.lights = true;
  19881. /**
  19882. * Overwritten since shadow materials are transparent
  19883. * by default.
  19884. *
  19885. * @type {boolean}
  19886. * @default true
  19887. */
  19888. this.transparent = true;
  19889. this.setDefaultValues( _defaultValues );
  19890. this.setValues( parameters );
  19891. }
  19892. /**
  19893. * Setups the lighting model.
  19894. *
  19895. * @return {ShadowMaskModel} The lighting model.
  19896. */
  19897. setupLightingModel( /*builder*/ ) {
  19898. return new ShadowMaskModel();
  19899. }
  19900. }
  19901. const scatteringDensity = property( 'vec3' );
  19902. const linearDepthRay = property( 'vec3' );
  19903. const outgoingRayLight = property( 'vec3' );
  19904. /**
  19905. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  19906. * This model calculates the scattering and transmittance of light through a volumetric medium.
  19907. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  19908. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  19909. *
  19910. * @augments LightingModel
  19911. */
  19912. class VolumetricLightingModel extends LightingModel {
  19913. constructor() {
  19914. super();
  19915. }
  19916. start( builder ) {
  19917. const { material } = builder;
  19918. const startPos = property( 'vec3' );
  19919. const endPos = property( 'vec3' );
  19920. // This approach dynamically changes the direction of the ray,
  19921. // 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.
  19922. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  19923. startPos.assign( cameraPosition );
  19924. endPos.assign( positionWorld );
  19925. } ).Else( () => {
  19926. startPos.assign( positionWorld );
  19927. endPos.assign( cameraPosition );
  19928. } );
  19929. //
  19930. const viewVector = endPos.sub( startPos );
  19931. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  19932. const stepSize = viewVector.length().div( steps ).toVar();
  19933. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  19934. const distTravelled = float( 0.0 ).toVar();
  19935. const transmittance = vec3( 1 ).toVar();
  19936. if ( material.offsetNode ) {
  19937. // reduce banding
  19938. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  19939. }
  19940. Loop( steps, () => {
  19941. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  19942. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  19943. if ( material.depthNode !== null ) {
  19944. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  19945. builder.context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  19946. }
  19947. builder.context.positionWorld = positionRay;
  19948. builder.context.shadowPositionWorld = positionRay;
  19949. builder.context.positionView = positionViewRay;
  19950. scatteringDensity.assign( 0 );
  19951. let scatteringNode;
  19952. if ( material.scatteringNode ) {
  19953. scatteringNode = material.scatteringNode( {
  19954. positionRay
  19955. } );
  19956. }
  19957. super.start( builder );
  19958. if ( scatteringNode ) {
  19959. scatteringDensity.mulAssign( scatteringNode );
  19960. }
  19961. // beer's law
  19962. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  19963. transmittance.mulAssign( falloff );
  19964. // move along the ray
  19965. distTravelled.addAssign( stepSize );
  19966. } );
  19967. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  19968. }
  19969. scatteringLight( lightColor, builder ) {
  19970. const sceneDepthNode = builder.context.sceneDepthNode;
  19971. if ( sceneDepthNode ) {
  19972. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  19973. scatteringDensity.addAssign( lightColor );
  19974. } );
  19975. } else {
  19976. scatteringDensity.addAssign( lightColor );
  19977. }
  19978. }
  19979. direct( { lightNode, lightColor }, builder ) {
  19980. // Ignore lights with infinite distance
  19981. if ( lightNode.light.distance === undefined ) return;
  19982. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  19983. const directLight = lightColor.xyz.toVar();
  19984. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  19985. this.scatteringLight( directLight, builder );
  19986. }
  19987. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  19988. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  19989. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  19990. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  19991. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  19992. const P = builder.context.positionView;
  19993. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  19994. this.scatteringLight( directLight, builder );
  19995. }
  19996. finish( builder ) {
  19997. builder.context.outgoingLight.assign( outgoingRayLight );
  19998. }
  19999. }
  20000. /**
  20001. * Volume node material.
  20002. *
  20003. * @augments NodeMaterial
  20004. */
  20005. class VolumeNodeMaterial extends NodeMaterial {
  20006. static get type() {
  20007. return 'VolumeNodeMaterial';
  20008. }
  20009. /**
  20010. * Constructs a new volume node material.
  20011. *
  20012. * @param {Object} [parameters] - The configuration parameter.
  20013. */
  20014. constructor( parameters ) {
  20015. super();
  20016. /**
  20017. * This flag can be used for type testing.
  20018. *
  20019. * @type {boolean}
  20020. * @readonly
  20021. * @default true
  20022. */
  20023. this.isVolumeNodeMaterial = true;
  20024. /**
  20025. * Number of steps used for raymarching.
  20026. *
  20027. * @type {number}
  20028. * @default 25
  20029. */
  20030. this.steps = 25;
  20031. /**
  20032. * Offsets the distance a ray has been traveled through a volume.
  20033. * Can be used to implement dithering to reduce banding.
  20034. *
  20035. * @type {Node<float>}
  20036. * @default null
  20037. */
  20038. this.offsetNode = null;
  20039. /**
  20040. * Node used for scattering calculations.
  20041. *
  20042. * @type {Function|FunctionNode<vec4>}
  20043. * @default null
  20044. */
  20045. this.scatteringNode = null;
  20046. this.lights = true;
  20047. this.transparent = true;
  20048. this.side = BackSide;
  20049. this.depthTest = false;
  20050. this.depthWrite = false;
  20051. this.setValues( parameters );
  20052. }
  20053. setupLightingModel() {
  20054. return new VolumetricLightingModel();
  20055. }
  20056. }
  20057. /**
  20058. * This module manages the internal animation loop of the renderer.
  20059. *
  20060. * @private
  20061. */
  20062. class Animation {
  20063. /**
  20064. * Constructs a new animation loop management component.
  20065. *
  20066. * @param {Renderer} renderer - A reference to the main renderer.
  20067. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20068. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20069. */
  20070. constructor( renderer, nodes, info ) {
  20071. /**
  20072. * A reference to the main renderer.
  20073. *
  20074. * @type {Renderer}
  20075. */
  20076. this.renderer = renderer;
  20077. /**
  20078. * Renderer component for managing nodes related logic.
  20079. *
  20080. * @type {Nodes}
  20081. */
  20082. this.nodes = nodes;
  20083. /**
  20084. * Renderer component for managing metrics and monitoring data.
  20085. *
  20086. * @type {Info}
  20087. */
  20088. this.info = info;
  20089. /**
  20090. * A reference to the context from `requestAnimationFrame()` can
  20091. * be called (usually `window`).
  20092. *
  20093. * @type {?(Window|XRSession)}
  20094. */
  20095. this._context = typeof self !== 'undefined' ? self : null;
  20096. /**
  20097. * The user-defined animation loop.
  20098. *
  20099. * @type {?Function}
  20100. * @default null
  20101. */
  20102. this._animationLoop = null;
  20103. /**
  20104. * The requestId which is returned from the `requestAnimationFrame()` call.
  20105. * Can be used to cancel the stop the animation loop.
  20106. *
  20107. * @type {?number}
  20108. * @default null
  20109. */
  20110. this._requestId = null;
  20111. }
  20112. /**
  20113. * Starts the internal animation loop.
  20114. */
  20115. start() {
  20116. const update = ( time, xrFrame ) => {
  20117. this._requestId = this._context.requestAnimationFrame( update );
  20118. if ( this.info.autoReset === true ) this.info.reset();
  20119. this.nodes.nodeFrame.update();
  20120. this.info.frame = this.nodes.nodeFrame.frameId;
  20121. this.renderer._inspector.begin();
  20122. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  20123. this.renderer._inspector.finish();
  20124. };
  20125. update();
  20126. }
  20127. /**
  20128. * Stops the internal animation loop.
  20129. */
  20130. stop() {
  20131. this._context.cancelAnimationFrame( this._requestId );
  20132. this._requestId = null;
  20133. }
  20134. /**
  20135. * Returns the user-level animation loop.
  20136. *
  20137. * @return {?Function} The animation loop.
  20138. */
  20139. getAnimationLoop() {
  20140. return this._animationLoop;
  20141. }
  20142. /**
  20143. * Defines the user-level animation loop.
  20144. *
  20145. * @param {?Function} callback - The animation loop.
  20146. */
  20147. setAnimationLoop( callback ) {
  20148. this._animationLoop = callback;
  20149. }
  20150. /**
  20151. * Returns the animation context.
  20152. *
  20153. * @return {Window|XRSession} The animation context.
  20154. */
  20155. getContext() {
  20156. return this._context;
  20157. }
  20158. /**
  20159. * Defines the context in which `requestAnimationFrame()` is executed.
  20160. *
  20161. * @param {Window|XRSession} context - The context to set.
  20162. */
  20163. setContext( context ) {
  20164. this._context = context;
  20165. }
  20166. /**
  20167. * Frees all internal resources and stops the animation loop.
  20168. */
  20169. dispose() {
  20170. this.stop();
  20171. }
  20172. }
  20173. /**
  20174. * Data structure for the renderer. It allows defining values
  20175. * with chained, hierarchical keys. Keys are meant to be
  20176. * objects since the module internally works with Weak Maps
  20177. * for performance reasons.
  20178. *
  20179. * @private
  20180. */
  20181. class ChainMap {
  20182. /**
  20183. * Constructs a new Chain Map.
  20184. */
  20185. constructor() {
  20186. /**
  20187. * The root Weak Map.
  20188. *
  20189. * @type {WeakMap<Object, WeakMap>}
  20190. */
  20191. this.weakMap = new WeakMap();
  20192. }
  20193. /**
  20194. * Returns the value for the given array of keys.
  20195. *
  20196. * @param {Array<Object>} keys - List of keys.
  20197. * @return {any} The value. Returns `undefined` if no value was found.
  20198. */
  20199. get( keys ) {
  20200. let map = this.weakMap;
  20201. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20202. map = map.get( keys[ i ] );
  20203. if ( map === undefined ) return undefined;
  20204. }
  20205. return map.get( keys[ keys.length - 1 ] );
  20206. }
  20207. /**
  20208. * Sets the value for the given keys.
  20209. *
  20210. * @param {Array<Object>} keys - List of keys.
  20211. * @param {any} value - The value to set.
  20212. * @return {ChainMap} A reference to this Chain Map.
  20213. */
  20214. set( keys, value ) {
  20215. let map = this.weakMap;
  20216. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20217. const key = keys[ i ];
  20218. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  20219. map = map.get( key );
  20220. }
  20221. map.set( keys[ keys.length - 1 ], value );
  20222. return this;
  20223. }
  20224. /**
  20225. * Deletes a value for the given keys.
  20226. *
  20227. * @param {Array<Object>} keys - The keys.
  20228. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  20229. */
  20230. delete( keys ) {
  20231. let map = this.weakMap;
  20232. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20233. map = map.get( keys[ i ] );
  20234. if ( map === undefined ) return false;
  20235. }
  20236. return map.delete( keys[ keys.length - 1 ] );
  20237. }
  20238. }
  20239. let _id$a = 0;
  20240. function getKeys( obj ) {
  20241. const keys = Object.keys( obj );
  20242. let proto = Object.getPrototypeOf( obj );
  20243. while ( proto ) {
  20244. const descriptors = Object.getOwnPropertyDescriptors( proto );
  20245. for ( const key in descriptors ) {
  20246. if ( descriptors[ key ] !== undefined ) {
  20247. const descriptor = descriptors[ key ];
  20248. if ( descriptor && typeof descriptor.get === 'function' ) {
  20249. keys.push( key );
  20250. }
  20251. }
  20252. }
  20253. proto = Object.getPrototypeOf( proto );
  20254. }
  20255. return keys;
  20256. }
  20257. /**
  20258. * A render object is the renderer's representation of single entity that gets drawn
  20259. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  20260. * scene since render objects also depend from the used material, the current render context
  20261. * and the current scene's lighting.
  20262. *
  20263. * In general, the basic process of the renderer is:
  20264. *
  20265. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  20266. * - Process the render lists by calling one or more render commands for each render item.
  20267. * - For each render command, request a render object and perform the draw.
  20268. *
  20269. * The module provides an interface to get data required for the draw command like the actual
  20270. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  20271. * creating render objects should only be done when necessary.
  20272. *
  20273. * @private
  20274. */
  20275. class RenderObject {
  20276. /**
  20277. * Constructs a new render object.
  20278. *
  20279. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20280. * @param {Geometries} geometries - Renderer component for managing geometries.
  20281. * @param {Renderer} renderer - The renderer.
  20282. * @param {Object3D} object - The 3D object.
  20283. * @param {Material} material - The 3D object's material.
  20284. * @param {Scene} scene - The scene the 3D object belongs to.
  20285. * @param {Camera} camera - The camera the object should be rendered with.
  20286. * @param {LightsNode} lightsNode - The lights node.
  20287. * @param {RenderContext} renderContext - The render context.
  20288. * @param {ClippingContext} clippingContext - The clipping context.
  20289. */
  20290. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  20291. this.id = _id$a ++;
  20292. /**
  20293. * Renderer component for managing nodes related logic.
  20294. *
  20295. * @type {Nodes}
  20296. * @private
  20297. */
  20298. this._nodes = nodes;
  20299. /**
  20300. * Renderer component for managing geometries.
  20301. *
  20302. * @type {Geometries}
  20303. * @private
  20304. */
  20305. this._geometries = geometries;
  20306. /**
  20307. * The renderer.
  20308. *
  20309. * @type {Renderer}
  20310. */
  20311. this.renderer = renderer;
  20312. /**
  20313. * The 3D object.
  20314. *
  20315. * @type {Object3D}
  20316. */
  20317. this.object = object;
  20318. /**
  20319. * The 3D object's material.
  20320. *
  20321. * @type {Material}
  20322. */
  20323. this.material = material;
  20324. /**
  20325. * The scene the 3D object belongs to.
  20326. *
  20327. * @type {Scene}
  20328. */
  20329. this.scene = scene;
  20330. /**
  20331. * The camera the 3D object should be rendered with.
  20332. *
  20333. * @type {Camera}
  20334. */
  20335. this.camera = camera;
  20336. /**
  20337. * The lights node.
  20338. *
  20339. * @type {LightsNode}
  20340. */
  20341. this.lightsNode = lightsNode;
  20342. /**
  20343. * The render context.
  20344. *
  20345. * @type {RenderContext}
  20346. */
  20347. this.context = renderContext;
  20348. /**
  20349. * The 3D object's geometry.
  20350. *
  20351. * @type {BufferGeometry}
  20352. */
  20353. this.geometry = object.geometry;
  20354. /**
  20355. * The render object's version.
  20356. *
  20357. * @type {number}
  20358. */
  20359. this.version = material.version;
  20360. /**
  20361. * The draw range of the geometry.
  20362. *
  20363. * @type {?Object}
  20364. * @default null
  20365. */
  20366. this.drawRange = null;
  20367. /**
  20368. * An array holding the buffer attributes
  20369. * of the render object. This entails attribute
  20370. * definitions on geometry and node level.
  20371. *
  20372. * @type {?Array<BufferAttribute>}
  20373. * @default null
  20374. */
  20375. this.attributes = null;
  20376. /**
  20377. * An object holding the version of the
  20378. * attributes. The keys are the attribute names
  20379. * and the values are the attribute versions.
  20380. *
  20381. * @type {?Object<string, number>}
  20382. * @default null
  20383. */
  20384. this.attributesId = null;
  20385. /**
  20386. * A reference to a render pipeline the render
  20387. * object is processed with.
  20388. *
  20389. * @type {RenderPipeline}
  20390. * @default null
  20391. */
  20392. this.pipeline = null;
  20393. /**
  20394. * Only relevant for objects using
  20395. * multiple materials. This represents a group entry
  20396. * from the respective `BufferGeometry`.
  20397. *
  20398. * @type {?{start: number, count: number}}
  20399. * @default null
  20400. */
  20401. this.group = null;
  20402. /**
  20403. * An array holding the vertex buffers which can
  20404. * be buffer attributes but also interleaved buffers.
  20405. *
  20406. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  20407. * @default null
  20408. */
  20409. this.vertexBuffers = null;
  20410. /**
  20411. * The parameters for the draw command.
  20412. *
  20413. * @type {?Object}
  20414. * @default null
  20415. */
  20416. this.drawParams = null;
  20417. /**
  20418. * If this render object is used inside a render bundle,
  20419. * this property points to the respective bundle group.
  20420. *
  20421. * @type {?BundleGroup}
  20422. * @default null
  20423. */
  20424. this.bundle = null;
  20425. /**
  20426. * The clipping context.
  20427. *
  20428. * @type {ClippingContext}
  20429. */
  20430. this.clippingContext = clippingContext;
  20431. /**
  20432. * The clipping context's cache key.
  20433. *
  20434. * @type {string}
  20435. */
  20436. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  20437. /**
  20438. * The initial node cache key.
  20439. *
  20440. * @type {number}
  20441. */
  20442. this.initialNodesCacheKey = this.getDynamicCacheKey();
  20443. /**
  20444. * The initial cache key.
  20445. *
  20446. * @type {number}
  20447. */
  20448. this.initialCacheKey = this.getCacheKey();
  20449. /**
  20450. * The node builder state.
  20451. *
  20452. * @type {?NodeBuilderState}
  20453. * @private
  20454. * @default null
  20455. */
  20456. this._nodeBuilderState = null;
  20457. /**
  20458. * An array of bindings.
  20459. *
  20460. * @type {?Array<BindGroup>}
  20461. * @private
  20462. * @default null
  20463. */
  20464. this._bindings = null;
  20465. /**
  20466. * Reference to the node material observer.
  20467. *
  20468. * @type {?NodeMaterialObserver}
  20469. * @private
  20470. * @default null
  20471. */
  20472. this._monitor = null;
  20473. /**
  20474. * An event listener which is defined by `RenderObjects`. It performs
  20475. * clean up tasks when `dispose()` on this render object.
  20476. *
  20477. * @method
  20478. */
  20479. this.onDispose = null;
  20480. /**
  20481. * This flag can be used for type testing.
  20482. *
  20483. * @type {boolean}
  20484. * @readonly
  20485. * @default true
  20486. */
  20487. this.isRenderObject = true;
  20488. /**
  20489. * An event listener which is executed when `dispose()` is called on
  20490. * the material of this render object.
  20491. *
  20492. * @method
  20493. */
  20494. this.onMaterialDispose = () => {
  20495. this.dispose();
  20496. };
  20497. /**
  20498. * An event listener which is executed when `dispose()` is called on
  20499. * the geometry of this render object.
  20500. *
  20501. * @method
  20502. */
  20503. this.onGeometryDispose = () => {
  20504. // clear geometry cache attributes
  20505. this.attributes = null;
  20506. this.attributesId = null;
  20507. };
  20508. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  20509. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  20510. }
  20511. /**
  20512. * Updates the clipping context.
  20513. *
  20514. * @param {ClippingContext} context - The clipping context to set.
  20515. */
  20516. updateClipping( context ) {
  20517. this.clippingContext = context;
  20518. }
  20519. /**
  20520. * Whether the clipping requires an update or not.
  20521. *
  20522. * @type {boolean}
  20523. * @readonly
  20524. */
  20525. get clippingNeedsUpdate() {
  20526. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  20527. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  20528. return true;
  20529. }
  20530. /**
  20531. * The number of clipping planes defined in context of hardware clipping.
  20532. *
  20533. * @type {number}
  20534. * @readonly
  20535. */
  20536. get hardwareClippingPlanes() {
  20537. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  20538. }
  20539. /**
  20540. * Returns the node builder state of this render object.
  20541. *
  20542. * @return {NodeBuilderState} The node builder state.
  20543. */
  20544. getNodeBuilderState() {
  20545. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  20546. }
  20547. /**
  20548. * Returns the node material observer of this render object.
  20549. *
  20550. * @return {NodeMaterialObserver} The node material observer.
  20551. */
  20552. getMonitor() {
  20553. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  20554. }
  20555. /**
  20556. * Returns an array of bind groups of this render object.
  20557. *
  20558. * @return {Array<BindGroup>} The bindings.
  20559. */
  20560. getBindings() {
  20561. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  20562. }
  20563. /**
  20564. * Returns a binding group by group name of this render object.
  20565. *
  20566. * @param {string} name - The name of the binding group.
  20567. * @return {?BindGroup} The bindings.
  20568. */
  20569. getBindingGroup( name ) {
  20570. for ( const bindingGroup of this.getBindings() ) {
  20571. if ( bindingGroup.name === name ) {
  20572. return bindingGroup;
  20573. }
  20574. }
  20575. }
  20576. /**
  20577. * Returns the index of the render object's geometry.
  20578. *
  20579. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20580. */
  20581. getIndex() {
  20582. return this._geometries.getIndex( this );
  20583. }
  20584. /**
  20585. * Returns the indirect buffer attribute.
  20586. *
  20587. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20588. */
  20589. getIndirect() {
  20590. return this._geometries.getIndirect( this );
  20591. }
  20592. /**
  20593. * Returns an array that acts as a key for identifying the render object in a chain map.
  20594. *
  20595. * @return {Array<Object>} An array with object references.
  20596. */
  20597. getChainArray() {
  20598. return [ this.object, this.material, this.context, this.lightsNode ];
  20599. }
  20600. /**
  20601. * This method is used when the geometry of a 3D object has been exchanged and the
  20602. * respective render object now requires an update.
  20603. *
  20604. * @param {BufferGeometry} geometry - The geometry to set.
  20605. */
  20606. setGeometry( geometry ) {
  20607. this.geometry = geometry;
  20608. this.attributes = null;
  20609. this.attributesId = null;
  20610. }
  20611. /**
  20612. * Returns the buffer attributes of the render object. The returned array holds
  20613. * attribute definitions on geometry and node level.
  20614. *
  20615. * @return {Array<BufferAttribute>} An array with buffer attributes.
  20616. */
  20617. getAttributes() {
  20618. if ( this.attributes !== null ) return this.attributes;
  20619. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  20620. const geometry = this.geometry;
  20621. const attributes = [];
  20622. const vertexBuffers = new Set();
  20623. const attributesId = {};
  20624. for ( const nodeAttribute of nodeAttributes ) {
  20625. let attribute;
  20626. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  20627. // node attribute
  20628. attribute = nodeAttribute.node.attribute;
  20629. } else {
  20630. // geometry attribute
  20631. attribute = geometry.getAttribute( nodeAttribute.name );
  20632. attributesId[ nodeAttribute.name ] = attribute.version;
  20633. }
  20634. if ( attribute === undefined ) continue;
  20635. attributes.push( attribute );
  20636. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20637. vertexBuffers.add( bufferAttribute );
  20638. }
  20639. this.attributes = attributes;
  20640. this.attributesId = attributesId;
  20641. this.vertexBuffers = Array.from( vertexBuffers.values() );
  20642. return attributes;
  20643. }
  20644. /**
  20645. * Returns the vertex buffers of the render object.
  20646. *
  20647. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  20648. */
  20649. getVertexBuffers() {
  20650. if ( this.vertexBuffers === null ) this.getAttributes();
  20651. return this.vertexBuffers;
  20652. }
  20653. /**
  20654. * Returns the draw parameters for the render object.
  20655. *
  20656. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  20657. */
  20658. getDrawParameters() {
  20659. const { object, material, geometry, group, drawRange } = this;
  20660. const drawParams = this.drawParams || ( this.drawParams = {
  20661. vertexCount: 0,
  20662. firstVertex: 0,
  20663. instanceCount: 0,
  20664. firstInstance: 0
  20665. } );
  20666. const index = this.getIndex();
  20667. const hasIndex = ( index !== null );
  20668. let instanceCount = 1;
  20669. if ( geometry.isInstancedBufferGeometry === true ) {
  20670. instanceCount = geometry.instanceCount;
  20671. } else if ( object.count !== undefined ) {
  20672. instanceCount = Math.max( 0, object.count );
  20673. }
  20674. if ( instanceCount === 0 ) return null;
  20675. drawParams.instanceCount = instanceCount;
  20676. if ( object.isBatchedMesh === true ) return drawParams;
  20677. let rangeFactor = 1;
  20678. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  20679. rangeFactor = 2;
  20680. }
  20681. let firstVertex = drawRange.start * rangeFactor;
  20682. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  20683. if ( group !== null ) {
  20684. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  20685. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  20686. }
  20687. const position = geometry.attributes.position;
  20688. let itemCount = Infinity;
  20689. if ( hasIndex ) {
  20690. itemCount = index.count;
  20691. } else if ( position !== undefined && position !== null ) {
  20692. itemCount = position.count;
  20693. }
  20694. firstVertex = Math.max( firstVertex, 0 );
  20695. lastVertex = Math.min( lastVertex, itemCount );
  20696. const count = lastVertex - firstVertex;
  20697. if ( count < 0 || count === Infinity ) return null;
  20698. drawParams.vertexCount = count;
  20699. drawParams.firstVertex = firstVertex;
  20700. return drawParams;
  20701. }
  20702. /**
  20703. * Returns the render object's geometry cache key.
  20704. *
  20705. * The geometry cache key is part of the material cache key.
  20706. *
  20707. * @return {string} The geometry cache key.
  20708. */
  20709. getGeometryCacheKey() {
  20710. const { geometry } = this;
  20711. let cacheKey = '';
  20712. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  20713. const attribute = geometry.attributes[ name ];
  20714. cacheKey += name + ',';
  20715. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  20716. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  20717. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  20718. if ( attribute.normalized ) cacheKey += 'n,';
  20719. }
  20720. // structural equality isn't sufficient for morph targets since the
  20721. // data are maintained in textures. only if the targets are all equal
  20722. // the texture and thus the instance of `MorphNode` can be shared.
  20723. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  20724. const targets = geometry.morphAttributes[ name ];
  20725. cacheKey += 'morph-' + name + ',';
  20726. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  20727. const attribute = targets[ i ];
  20728. cacheKey += attribute.id + ',';
  20729. }
  20730. }
  20731. if ( geometry.index ) {
  20732. cacheKey += 'index,';
  20733. }
  20734. return cacheKey;
  20735. }
  20736. /**
  20737. * Returns the render object's material cache key.
  20738. *
  20739. * The material cache key is part of the render object cache key.
  20740. *
  20741. * @return {number} The material cache key.
  20742. */
  20743. getMaterialCacheKey() {
  20744. const { object, material, renderer } = this;
  20745. let cacheKey = material.customProgramCacheKey();
  20746. for ( const property of getKeys( material ) ) {
  20747. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  20748. const value = material[ property ];
  20749. let valueKey;
  20750. if ( value !== null ) {
  20751. // some material values require a formatting
  20752. const type = typeof value;
  20753. if ( type === 'number' ) {
  20754. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  20755. } else if ( type === 'object' ) {
  20756. valueKey = '{';
  20757. if ( value.isTexture ) {
  20758. valueKey += value.mapping;
  20759. // WebGPU must honor the sampler data because they are part of the bindings
  20760. if ( renderer.backend.isWebGPUBackend === true ) {
  20761. valueKey += value.magFilter;
  20762. valueKey += value.minFilter;
  20763. valueKey += value.wrapS;
  20764. valueKey += value.wrapT;
  20765. valueKey += value.wrapR;
  20766. }
  20767. }
  20768. valueKey += '}';
  20769. } else {
  20770. valueKey = String( value );
  20771. }
  20772. } else {
  20773. valueKey = String( value );
  20774. }
  20775. cacheKey += /*property + ':' +*/ valueKey + ',';
  20776. }
  20777. cacheKey += this.clippingContextCacheKey + ',';
  20778. if ( object.geometry ) {
  20779. cacheKey += this.getGeometryCacheKey();
  20780. }
  20781. if ( object.skeleton ) {
  20782. cacheKey += object.skeleton.bones.length + ',';
  20783. }
  20784. if ( object.isBatchedMesh ) {
  20785. cacheKey += object._matricesTexture.uuid + ',';
  20786. if ( object._colorsTexture !== null ) {
  20787. cacheKey += object._colorsTexture.uuid + ',';
  20788. }
  20789. }
  20790. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  20791. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  20792. cacheKey += object.uuid + ',';
  20793. }
  20794. cacheKey += this.context.id + ',';
  20795. cacheKey += object.receiveShadow + ',';
  20796. return hashString( cacheKey );
  20797. }
  20798. /**
  20799. * Whether the geometry requires an update or not.
  20800. *
  20801. * @type {boolean}
  20802. * @readonly
  20803. */
  20804. get needsGeometryUpdate() {
  20805. if ( this.geometry.id !== this.object.geometry.id ) return true;
  20806. if ( this.attributes !== null ) {
  20807. const attributesId = this.attributesId;
  20808. for ( const name in attributesId ) {
  20809. const attribute = this.geometry.getAttribute( name );
  20810. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  20811. return true;
  20812. }
  20813. }
  20814. }
  20815. return false;
  20816. }
  20817. /**
  20818. * Whether the render object requires an update or not.
  20819. *
  20820. * Note: There are two distinct places where render objects are checked for an update.
  20821. *
  20822. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  20823. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  20824. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  20825. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  20826. * a need for a refresh due to material, geometry or object related value changes.
  20827. *
  20828. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  20829. * that performs the 'needsUpdate' check.
  20830. *
  20831. * @type {boolean}
  20832. * @readonly
  20833. */
  20834. get needsUpdate() {
  20835. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  20836. }
  20837. /**
  20838. * Returns the dynamic cache key which represents a key that is computed per draw command.
  20839. *
  20840. * @return {number} The cache key.
  20841. */
  20842. getDynamicCacheKey() {
  20843. let cacheKey = 0;
  20844. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  20845. // the renderer is inside a shadow pass.
  20846. if ( this.material.isShadowPassMaterial !== true ) {
  20847. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  20848. }
  20849. if ( this.camera.isArrayCamera ) {
  20850. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  20851. }
  20852. if ( this.object.receiveShadow ) {
  20853. cacheKey = hash$1( cacheKey, 1 );
  20854. }
  20855. cacheKey = hash$1( cacheKey, this.camera.id, this.renderer.contextNode.id, this.renderer.contextNode.version );
  20856. return cacheKey;
  20857. }
  20858. /**
  20859. * Returns the render object's cache key.
  20860. *
  20861. * @return {number} The cache key.
  20862. */
  20863. getCacheKey() {
  20864. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  20865. }
  20866. /**
  20867. * Frees internal resources.
  20868. */
  20869. dispose() {
  20870. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  20871. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  20872. this.onDispose();
  20873. }
  20874. }
  20875. const _chainKeys$5 = [];
  20876. /**
  20877. * This module manages the render objects of the renderer.
  20878. *
  20879. * @private
  20880. */
  20881. class RenderObjects {
  20882. /**
  20883. * Constructs a new render object management component.
  20884. *
  20885. * @param {Renderer} renderer - The renderer.
  20886. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20887. * @param {Geometries} geometries - Renderer component for managing geometries.
  20888. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20889. * @param {Bindings} bindings - Renderer component for managing bindings.
  20890. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20891. */
  20892. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  20893. /**
  20894. * The renderer.
  20895. *
  20896. * @type {Renderer}
  20897. */
  20898. this.renderer = renderer;
  20899. /**
  20900. * Renderer component for managing nodes related logic.
  20901. *
  20902. * @type {Nodes}
  20903. */
  20904. this.nodes = nodes;
  20905. /**
  20906. * Renderer component for managing geometries.
  20907. *
  20908. * @type {Geometries}
  20909. */
  20910. this.geometries = geometries;
  20911. /**
  20912. * Renderer component for managing pipelines.
  20913. *
  20914. * @type {Pipelines}
  20915. */
  20916. this.pipelines = pipelines;
  20917. /**
  20918. * Renderer component for managing bindings.
  20919. *
  20920. * @type {Bindings}
  20921. */
  20922. this.bindings = bindings;
  20923. /**
  20924. * Renderer component for managing metrics and monitoring data.
  20925. *
  20926. * @type {Info}
  20927. */
  20928. this.info = info;
  20929. /**
  20930. * A dictionary that manages render contexts in chain maps
  20931. * for each pass ID.
  20932. *
  20933. * @type {Object<string,ChainMap>}
  20934. */
  20935. this.chainMaps = {};
  20936. }
  20937. /**
  20938. * Returns a render object for the given object and state data.
  20939. *
  20940. * @param {Object3D} object - The 3D object.
  20941. * @param {Material} material - The 3D object's material.
  20942. * @param {Scene} scene - The scene the 3D object belongs to.
  20943. * @param {Camera} camera - The camera the 3D object should be rendered with.
  20944. * @param {LightsNode} lightsNode - The lights node.
  20945. * @param {RenderContext} renderContext - The render context.
  20946. * @param {ClippingContext} clippingContext - The clipping context.
  20947. * @param {string} [passId] - An optional ID for identifying the pass.
  20948. * @return {RenderObject} The render object.
  20949. */
  20950. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20951. const chainMap = this.getChainMap( passId );
  20952. // reuse chainArray
  20953. _chainKeys$5[ 0 ] = object;
  20954. _chainKeys$5[ 1 ] = material;
  20955. _chainKeys$5[ 2 ] = renderContext;
  20956. _chainKeys$5[ 3 ] = lightsNode;
  20957. let renderObject = chainMap.get( _chainKeys$5 );
  20958. if ( renderObject === undefined ) {
  20959. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20960. chainMap.set( _chainKeys$5, renderObject );
  20961. } else {
  20962. renderObject.updateClipping( clippingContext );
  20963. if ( renderObject.needsGeometryUpdate ) {
  20964. renderObject.setGeometry( object.geometry );
  20965. }
  20966. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  20967. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  20968. renderObject.dispose();
  20969. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20970. } else {
  20971. renderObject.version = material.version;
  20972. }
  20973. }
  20974. }
  20975. _chainKeys$5.length = 0;
  20976. return renderObject;
  20977. }
  20978. /**
  20979. * Returns a chain map for the given pass ID.
  20980. *
  20981. * @param {string} [passId='default'] - The pass ID.
  20982. * @return {ChainMap} The chain map.
  20983. */
  20984. getChainMap( passId = 'default' ) {
  20985. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  20986. }
  20987. /**
  20988. * Frees internal resources.
  20989. */
  20990. dispose() {
  20991. this.chainMaps = {};
  20992. }
  20993. /**
  20994. * Factory method for creating render objects with the given list of parameters.
  20995. *
  20996. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20997. * @param {Geometries} geometries - Renderer component for managing geometries.
  20998. * @param {Renderer} renderer - The renderer.
  20999. * @param {Object3D} object - The 3D object.
  21000. * @param {Material} material - The object's material.
  21001. * @param {Scene} scene - The scene the 3D object belongs to.
  21002. * @param {Camera} camera - The camera the object should be rendered with.
  21003. * @param {LightsNode} lightsNode - The lights node.
  21004. * @param {RenderContext} renderContext - The render context.
  21005. * @param {ClippingContext} clippingContext - The clipping context.
  21006. * @param {string} [passId] - An optional ID for identifying the pass.
  21007. * @return {RenderObject} The render object.
  21008. */
  21009. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21010. const chainMap = this.getChainMap( passId );
  21011. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  21012. renderObject.onDispose = () => {
  21013. this.pipelines.delete( renderObject );
  21014. this.bindings.deleteForRender( renderObject );
  21015. this.nodes.delete( renderObject );
  21016. chainMap.delete( renderObject.getChainArray() );
  21017. };
  21018. return renderObject;
  21019. }
  21020. }
  21021. /**
  21022. * Data structure for the renderer. It is intended to manage
  21023. * data of objects in dictionaries.
  21024. *
  21025. * @private
  21026. */
  21027. class DataMap {
  21028. /**
  21029. * Constructs a new data map.
  21030. */
  21031. constructor() {
  21032. /**
  21033. * `DataMap` internally uses a weak map
  21034. * to manage its data.
  21035. *
  21036. * @type {WeakMap<Object, Object>}
  21037. */
  21038. this.data = new WeakMap();
  21039. }
  21040. /**
  21041. * Returns the dictionary for the given object.
  21042. *
  21043. * @param {Object} object - The object.
  21044. * @return {Object} The dictionary.
  21045. */
  21046. get( object ) {
  21047. let map = this.data.get( object );
  21048. if ( map === undefined ) {
  21049. map = {};
  21050. this.data.set( object, map );
  21051. }
  21052. return map;
  21053. }
  21054. /**
  21055. * Deletes the dictionary for the given object.
  21056. *
  21057. * @param {Object} object - The object.
  21058. * @return {?Object} The deleted dictionary.
  21059. */
  21060. delete( object ) {
  21061. let map = null;
  21062. if ( this.data.has( object ) ) {
  21063. map = this.data.get( object );
  21064. this.data.delete( object );
  21065. }
  21066. return map;
  21067. }
  21068. /**
  21069. * Returns `true` if the given object has a dictionary defined.
  21070. *
  21071. * @param {Object} object - The object to test.
  21072. * @return {boolean} Whether a dictionary is defined or not.
  21073. */
  21074. has( object ) {
  21075. return this.data.has( object );
  21076. }
  21077. /**
  21078. * Frees internal resources.
  21079. */
  21080. dispose() {
  21081. this.data = new WeakMap();
  21082. }
  21083. }
  21084. const AttributeType = {
  21085. VERTEX: 1,
  21086. INDEX: 2,
  21087. STORAGE: 3,
  21088. INDIRECT: 4
  21089. };
  21090. // size of a chunk in bytes (STD140 layout)
  21091. const GPU_CHUNK_BYTES = 16;
  21092. // @TODO: Move to src/constants.js
  21093. const BlendColorFactor = 211;
  21094. const OneMinusBlendColorFactor = 212;
  21095. /**
  21096. * This renderer module manages geometry attributes.
  21097. *
  21098. * @private
  21099. * @augments DataMap
  21100. */
  21101. class Attributes extends DataMap {
  21102. /**
  21103. * Constructs a new attribute management component.
  21104. *
  21105. * @param {Backend} backend - The renderer's backend.
  21106. */
  21107. constructor( backend ) {
  21108. super();
  21109. /**
  21110. * The renderer's backend.
  21111. *
  21112. * @type {Backend}
  21113. */
  21114. this.backend = backend;
  21115. }
  21116. /**
  21117. * Deletes the data for the given attribute.
  21118. *
  21119. * @param {BufferAttribute} attribute - The attribute.
  21120. * @return {?Object} The deleted attribute data.
  21121. */
  21122. delete( attribute ) {
  21123. const attributeData = super.delete( attribute );
  21124. if ( attributeData !== null ) {
  21125. this.backend.destroyAttribute( attribute );
  21126. }
  21127. return attributeData;
  21128. }
  21129. /**
  21130. * Updates the given attribute. This method creates attribute buffers
  21131. * for new attributes and updates data for existing ones.
  21132. *
  21133. * @param {BufferAttribute} attribute - The attribute to update.
  21134. * @param {number} type - The attribute type.
  21135. */
  21136. update( attribute, type ) {
  21137. const data = this.get( attribute );
  21138. if ( data.version === undefined ) {
  21139. if ( type === AttributeType.VERTEX ) {
  21140. this.backend.createAttribute( attribute );
  21141. } else if ( type === AttributeType.INDEX ) {
  21142. this.backend.createIndexAttribute( attribute );
  21143. } else if ( type === AttributeType.STORAGE ) {
  21144. this.backend.createStorageAttribute( attribute );
  21145. } else if ( type === AttributeType.INDIRECT ) {
  21146. this.backend.createIndirectStorageAttribute( attribute );
  21147. }
  21148. data.version = this._getBufferAttribute( attribute ).version;
  21149. } else {
  21150. const bufferAttribute = this._getBufferAttribute( attribute );
  21151. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21152. this.backend.updateAttribute( attribute );
  21153. data.version = bufferAttribute.version;
  21154. }
  21155. }
  21156. }
  21157. /**
  21158. * Utility method for handling interleaved buffer attributes correctly.
  21159. * To process them, their `InterleavedBuffer` is returned.
  21160. *
  21161. * @param {BufferAttribute} attribute - The attribute.
  21162. * @return {BufferAttribute|InterleavedBuffer}
  21163. */
  21164. _getBufferAttribute( attribute ) {
  21165. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21166. return attribute;
  21167. }
  21168. }
  21169. /**
  21170. * Returns the wireframe version for the given geometry.
  21171. *
  21172. * @private
  21173. * @function
  21174. * @param {BufferGeometry} geometry - The geometry.
  21175. * @return {number} The version.
  21176. */
  21177. function getWireframeVersion( geometry ) {
  21178. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21179. }
  21180. /**
  21181. * Returns a wireframe index attribute for the given geometry.
  21182. *
  21183. * @private
  21184. * @function
  21185. * @param {BufferGeometry} geometry - The geometry.
  21186. * @return {BufferAttribute} The wireframe index attribute.
  21187. */
  21188. function getWireframeIndex( geometry ) {
  21189. const indices = [];
  21190. const geometryIndex = geometry.index;
  21191. const geometryPosition = geometry.attributes.position;
  21192. if ( geometryIndex !== null ) {
  21193. const array = geometryIndex.array;
  21194. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21195. const a = array[ i + 0 ];
  21196. const b = array[ i + 1 ];
  21197. const c = array[ i + 2 ];
  21198. indices.push( a, b, b, c, c, a );
  21199. }
  21200. } else {
  21201. const array = geometryPosition.array;
  21202. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21203. const a = i + 0;
  21204. const b = i + 1;
  21205. const c = i + 2;
  21206. indices.push( a, b, b, c, c, a );
  21207. }
  21208. }
  21209. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21210. attribute.version = getWireframeVersion( geometry );
  21211. return attribute;
  21212. }
  21213. /**
  21214. * This renderer module manages geometries.
  21215. *
  21216. * @private
  21217. * @augments DataMap
  21218. */
  21219. class Geometries extends DataMap {
  21220. /**
  21221. * Constructs a new geometry management component.
  21222. *
  21223. * @param {Attributes} attributes - Renderer component for managing attributes.
  21224. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21225. */
  21226. constructor( attributes, info ) {
  21227. super();
  21228. /**
  21229. * Renderer component for managing attributes.
  21230. *
  21231. * @type {Attributes}
  21232. */
  21233. this.attributes = attributes;
  21234. /**
  21235. * Renderer component for managing metrics and monitoring data.
  21236. *
  21237. * @type {Info}
  21238. */
  21239. this.info = info;
  21240. /**
  21241. * Weak Map for managing attributes for wireframe rendering.
  21242. *
  21243. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  21244. */
  21245. this.wireframes = new WeakMap();
  21246. /**
  21247. * This Weak Map is used to make sure buffer attributes are
  21248. * updated only once per render call.
  21249. *
  21250. * @type {WeakMap<BufferAttribute,number>}
  21251. */
  21252. this.attributeCall = new WeakMap();
  21253. /**
  21254. * Stores the event listeners attached to geometries.
  21255. *
  21256. * @private
  21257. * @type {Map<BufferGeometry,Function>}
  21258. */
  21259. this._geometryDisposeListeners = new Map();
  21260. }
  21261. /**
  21262. * Returns `true` if the given render object has an initialized geometry.
  21263. *
  21264. * @param {RenderObject} renderObject - The render object.
  21265. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  21266. */
  21267. has( renderObject ) {
  21268. const geometry = renderObject.geometry;
  21269. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21270. }
  21271. /**
  21272. * Prepares the geometry of the given render object for rendering.
  21273. *
  21274. * @param {RenderObject} renderObject - The render object.
  21275. */
  21276. updateForRender( renderObject ) {
  21277. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21278. this.updateAttributes( renderObject );
  21279. }
  21280. /**
  21281. * Initializes the geometry of the given render object.
  21282. *
  21283. * @param {RenderObject} renderObject - The render object.
  21284. */
  21285. initGeometry( renderObject ) {
  21286. const geometry = renderObject.geometry;
  21287. const geometryData = this.get( geometry );
  21288. geometryData.initialized = true;
  21289. this.info.memory.geometries ++;
  21290. const onDispose = () => {
  21291. this.info.memory.geometries --;
  21292. const index = geometry.index;
  21293. const geometryAttributes = renderObject.getAttributes();
  21294. if ( index !== null ) {
  21295. this.attributes.delete( index );
  21296. }
  21297. for ( const geometryAttribute of geometryAttributes ) {
  21298. this.attributes.delete( geometryAttribute );
  21299. }
  21300. const wireframeAttribute = this.wireframes.get( geometry );
  21301. if ( wireframeAttribute !== undefined ) {
  21302. this.attributes.delete( wireframeAttribute );
  21303. }
  21304. geometry.removeEventListener( 'dispose', onDispose );
  21305. this._geometryDisposeListeners.delete( geometry );
  21306. };
  21307. geometry.addEventListener( 'dispose', onDispose );
  21308. // see #31798 why tracking separate remove listeners is required right now
  21309. // TODO: Re-evaluate how onDispose() is managed in this component
  21310. this._geometryDisposeListeners.set( geometry, onDispose );
  21311. }
  21312. /**
  21313. * Updates the geometry attributes of the given render object.
  21314. *
  21315. * @param {RenderObject} renderObject - The render object.
  21316. */
  21317. updateAttributes( renderObject ) {
  21318. // attributes
  21319. const attributes = renderObject.getAttributes();
  21320. for ( const attribute of attributes ) {
  21321. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21322. this.updateAttribute( attribute, AttributeType.STORAGE );
  21323. } else {
  21324. this.updateAttribute( attribute, AttributeType.VERTEX );
  21325. }
  21326. }
  21327. // indexes
  21328. const index = this.getIndex( renderObject );
  21329. if ( index !== null ) {
  21330. this.updateAttribute( index, AttributeType.INDEX );
  21331. }
  21332. // indirect
  21333. const indirect = renderObject.geometry.indirect;
  21334. if ( indirect !== null ) {
  21335. this.updateAttribute( indirect, AttributeType.INDIRECT );
  21336. }
  21337. }
  21338. /**
  21339. * Updates the given attribute.
  21340. *
  21341. * @param {BufferAttribute} attribute - The attribute to update.
  21342. * @param {number} type - The attribute type.
  21343. */
  21344. updateAttribute( attribute, type ) {
  21345. const callId = this.info.render.calls;
  21346. if ( ! attribute.isInterleavedBufferAttribute ) {
  21347. if ( this.attributeCall.get( attribute ) !== callId ) {
  21348. this.attributes.update( attribute, type );
  21349. this.attributeCall.set( attribute, callId );
  21350. }
  21351. } else {
  21352. if ( this.attributeCall.get( attribute ) === undefined ) {
  21353. this.attributes.update( attribute, type );
  21354. this.attributeCall.set( attribute, callId );
  21355. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21356. this.attributes.update( attribute, type );
  21357. this.attributeCall.set( attribute.data, callId );
  21358. this.attributeCall.set( attribute, callId );
  21359. }
  21360. }
  21361. }
  21362. /**
  21363. * Returns the indirect buffer attribute of the given render object.
  21364. *
  21365. * @param {RenderObject} renderObject - The render object.
  21366. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  21367. */
  21368. getIndirect( renderObject ) {
  21369. return renderObject.geometry.indirect;
  21370. }
  21371. /**
  21372. * Returns the index of the given render object's geometry. This is implemented
  21373. * in a method to return a wireframe index if necessary.
  21374. *
  21375. * @param {RenderObject} renderObject - The render object.
  21376. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  21377. */
  21378. getIndex( renderObject ) {
  21379. const { geometry, material } = renderObject;
  21380. let index = geometry.index;
  21381. if ( material.wireframe === true ) {
  21382. const wireframes = this.wireframes;
  21383. let wireframeAttribute = wireframes.get( geometry );
  21384. if ( wireframeAttribute === undefined ) {
  21385. wireframeAttribute = getWireframeIndex( geometry );
  21386. wireframes.set( geometry, wireframeAttribute );
  21387. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  21388. this.attributes.delete( wireframeAttribute );
  21389. wireframeAttribute = getWireframeIndex( geometry );
  21390. wireframes.set( geometry, wireframeAttribute );
  21391. }
  21392. index = wireframeAttribute;
  21393. }
  21394. return index;
  21395. }
  21396. dispose() {
  21397. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  21398. geometry.removeEventListener( 'dispose', onDispose );
  21399. }
  21400. this._geometryDisposeListeners.clear();
  21401. }
  21402. }
  21403. /**
  21404. * This renderer module provides a series of statistical information
  21405. * about the GPU memory and the rendering process. Useful for debugging
  21406. * and monitoring.
  21407. */
  21408. class Info {
  21409. /**
  21410. * Constructs a new info component.
  21411. */
  21412. constructor() {
  21413. /**
  21414. * Whether frame related metrics should automatically
  21415. * be resetted or not. This property should be set to `false`
  21416. * by apps which manage their own animation loop. They must
  21417. * then call `renderer.info.reset()` once per frame manually.
  21418. *
  21419. * @type {boolean}
  21420. * @default true
  21421. */
  21422. this.autoReset = true;
  21423. /**
  21424. * The current frame ID. This ID is managed
  21425. * by `NodeFrame`.
  21426. *
  21427. * @type {number}
  21428. * @readonly
  21429. * @default 0
  21430. */
  21431. this.frame = 0;
  21432. /**
  21433. * The number of render calls since the
  21434. * app has been started.
  21435. *
  21436. * @type {number}
  21437. * @readonly
  21438. * @default 0
  21439. */
  21440. this.calls = 0;
  21441. /**
  21442. * Render related metrics.
  21443. *
  21444. * @type {Object}
  21445. * @readonly
  21446. * @property {number} calls - The number of render calls since the app has been started.
  21447. * @property {number} frameCalls - The number of render calls of the current frame.
  21448. * @property {number} drawCalls - The number of draw calls of the current frame.
  21449. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  21450. * @property {number} points - The number of rendered point primitives of the current frame.
  21451. * @property {number} lines - The number of rendered line primitives of the current frame.
  21452. * @property {number} timestamp - The timestamp of the frame.
  21453. */
  21454. this.render = {
  21455. calls: 0,
  21456. frameCalls: 0,
  21457. drawCalls: 0,
  21458. triangles: 0,
  21459. points: 0,
  21460. lines: 0,
  21461. timestamp: 0,
  21462. };
  21463. /**
  21464. * Compute related metrics.
  21465. *
  21466. * @type {Object}
  21467. * @readonly
  21468. * @property {number} calls - The number of compute calls since the app has been started.
  21469. * @property {number} frameCalls - The number of compute calls of the current frame.
  21470. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  21471. */
  21472. this.compute = {
  21473. calls: 0,
  21474. frameCalls: 0,
  21475. timestamp: 0
  21476. };
  21477. /**
  21478. * Memory related metrics.
  21479. *
  21480. * @type {Object}
  21481. * @readonly
  21482. * @property {number} geometries - The number of active geometries.
  21483. * @property {number} frameCalls - The number of active textures.
  21484. */
  21485. this.memory = {
  21486. geometries: 0,
  21487. textures: 0
  21488. };
  21489. }
  21490. /**
  21491. * This method should be executed per draw call and updates the corresponding metrics.
  21492. *
  21493. * @param {Object3D} object - The 3D object that is going to be rendered.
  21494. * @param {number} count - The vertex or index count.
  21495. * @param {number} instanceCount - The instance count.
  21496. */
  21497. update( object, count, instanceCount ) {
  21498. this.render.drawCalls ++;
  21499. if ( object.isMesh || object.isSprite ) {
  21500. this.render.triangles += instanceCount * ( count / 3 );
  21501. } else if ( object.isPoints ) {
  21502. this.render.points += instanceCount * count;
  21503. } else if ( object.isLineSegments ) {
  21504. this.render.lines += instanceCount * ( count / 2 );
  21505. } else if ( object.isLine ) {
  21506. this.render.lines += instanceCount * ( count - 1 );
  21507. } else {
  21508. error( 'WebGPUInfo: Unknown object type.' );
  21509. }
  21510. }
  21511. /**
  21512. * Resets frame related metrics.
  21513. */
  21514. reset() {
  21515. this.render.drawCalls = 0;
  21516. this.render.frameCalls = 0;
  21517. this.compute.frameCalls = 0;
  21518. this.render.triangles = 0;
  21519. this.render.points = 0;
  21520. this.render.lines = 0;
  21521. }
  21522. /**
  21523. * Performs a complete reset of the object.
  21524. */
  21525. dispose() {
  21526. this.reset();
  21527. this.calls = 0;
  21528. this.render.calls = 0;
  21529. this.compute.calls = 0;
  21530. this.render.timestamp = 0;
  21531. this.compute.timestamp = 0;
  21532. this.memory.geometries = 0;
  21533. this.memory.textures = 0;
  21534. }
  21535. }
  21536. /**
  21537. * Abstract class for representing pipelines.
  21538. *
  21539. * @private
  21540. * @abstract
  21541. */
  21542. class Pipeline {
  21543. /**
  21544. * Constructs a new pipeline.
  21545. *
  21546. * @param {string} cacheKey - The pipeline's cache key.
  21547. */
  21548. constructor( cacheKey ) {
  21549. /**
  21550. * The pipeline's cache key.
  21551. *
  21552. * @type {string}
  21553. */
  21554. this.cacheKey = cacheKey;
  21555. /**
  21556. * How often the pipeline is currently in use.
  21557. *
  21558. * @type {number}
  21559. * @default 0
  21560. */
  21561. this.usedTimes = 0;
  21562. }
  21563. }
  21564. /**
  21565. * Class for representing render pipelines.
  21566. *
  21567. * @private
  21568. * @augments Pipeline
  21569. */
  21570. class RenderPipeline extends Pipeline {
  21571. /**
  21572. * Constructs a new render pipeline.
  21573. *
  21574. * @param {string} cacheKey - The pipeline's cache key.
  21575. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  21576. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  21577. */
  21578. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21579. super( cacheKey );
  21580. /**
  21581. * The pipeline's vertex shader.
  21582. *
  21583. * @type {ProgrammableStage}
  21584. */
  21585. this.vertexProgram = vertexProgram;
  21586. /**
  21587. * The pipeline's fragment shader.
  21588. *
  21589. * @type {ProgrammableStage}
  21590. */
  21591. this.fragmentProgram = fragmentProgram;
  21592. }
  21593. }
  21594. /**
  21595. * Class for representing compute pipelines.
  21596. *
  21597. * @private
  21598. * @augments Pipeline
  21599. */
  21600. class ComputePipeline extends Pipeline {
  21601. /**
  21602. * Constructs a new render pipeline.
  21603. *
  21604. * @param {string} cacheKey - The pipeline's cache key.
  21605. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  21606. */
  21607. constructor( cacheKey, computeProgram ) {
  21608. super( cacheKey );
  21609. /**
  21610. * The pipeline's compute shader.
  21611. *
  21612. * @type {ProgrammableStage}
  21613. */
  21614. this.computeProgram = computeProgram;
  21615. /**
  21616. * This flag can be used for type testing.
  21617. *
  21618. * @type {boolean}
  21619. * @readonly
  21620. * @default true
  21621. */
  21622. this.isComputePipeline = true;
  21623. }
  21624. }
  21625. let _id$9 = 0;
  21626. /**
  21627. * Class for representing programmable stages which are vertex,
  21628. * fragment or compute shaders. Unlike fixed-function states (like blending),
  21629. * they represent the programmable part of a pipeline.
  21630. *
  21631. * @private
  21632. */
  21633. class ProgrammableStage {
  21634. /**
  21635. * Constructs a new programmable stage.
  21636. *
  21637. * @param {string} code - The shader code.
  21638. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  21639. * @param {string} name - The name of the shader.
  21640. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21641. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21642. */
  21643. constructor( code, stage, name, transforms = null, attributes = null ) {
  21644. /**
  21645. * The id of the programmable stage.
  21646. *
  21647. * @type {number}
  21648. */
  21649. this.id = _id$9 ++;
  21650. /**
  21651. * The shader code.
  21652. *
  21653. * @type {string}
  21654. */
  21655. this.code = code;
  21656. /**
  21657. * The type of stage.
  21658. *
  21659. * @type {string}
  21660. */
  21661. this.stage = stage;
  21662. /**
  21663. * The name of the stage.
  21664. * This is used for debugging purposes.
  21665. *
  21666. * @type {string}
  21667. */
  21668. this.name = name;
  21669. /**
  21670. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21671. *
  21672. * @type {?Array<Object>}
  21673. */
  21674. this.transforms = transforms;
  21675. /**
  21676. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21677. *
  21678. * @type {?Array<Object>}
  21679. */
  21680. this.attributes = attributes;
  21681. /**
  21682. * How often the programmable stage is currently in use.
  21683. *
  21684. * @type {number}
  21685. * @default 0
  21686. */
  21687. this.usedTimes = 0;
  21688. }
  21689. }
  21690. /**
  21691. * This renderer module manages the pipelines of the renderer.
  21692. *
  21693. * @private
  21694. * @augments DataMap
  21695. */
  21696. class Pipelines extends DataMap {
  21697. /**
  21698. * Constructs a new pipeline management component.
  21699. *
  21700. * @param {Backend} backend - The renderer's backend.
  21701. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21702. */
  21703. constructor( backend, nodes ) {
  21704. super();
  21705. /**
  21706. * The renderer's backend.
  21707. *
  21708. * @type {Backend}
  21709. */
  21710. this.backend = backend;
  21711. /**
  21712. * Renderer component for managing nodes related logic.
  21713. *
  21714. * @type {Nodes}
  21715. */
  21716. this.nodes = nodes;
  21717. /**
  21718. * A references to the bindings management component.
  21719. * This reference will be set inside the `Bindings`
  21720. * constructor.
  21721. *
  21722. * @type {?Bindings}
  21723. * @default null
  21724. */
  21725. this.bindings = null;
  21726. /**
  21727. * Internal cache for maintaining pipelines.
  21728. * The key of the map is a cache key, the value the pipeline.
  21729. *
  21730. * @type {Map<string,Pipeline>}
  21731. */
  21732. this.caches = new Map();
  21733. /**
  21734. * This dictionary maintains for each shader stage type (vertex,
  21735. * fragment and compute) the programmable stage objects which
  21736. * represent the actual shader code.
  21737. *
  21738. * @type {Object<string,Map<string, ProgrammableStage>>}
  21739. */
  21740. this.programs = {
  21741. vertex: new Map(),
  21742. fragment: new Map(),
  21743. compute: new Map()
  21744. };
  21745. }
  21746. /**
  21747. * Returns a compute pipeline for the given compute node.
  21748. *
  21749. * @param {Node} computeNode - The compute node.
  21750. * @param {Array<BindGroup>} bindings - The bindings.
  21751. * @return {ComputePipeline} The compute pipeline.
  21752. */
  21753. getForCompute( computeNode, bindings ) {
  21754. const { backend } = this;
  21755. const data = this.get( computeNode );
  21756. if ( this._needsComputeUpdate( computeNode ) ) {
  21757. const previousPipeline = data.pipeline;
  21758. if ( previousPipeline ) {
  21759. previousPipeline.usedTimes --;
  21760. previousPipeline.computeProgram.usedTimes --;
  21761. }
  21762. // get shader
  21763. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21764. // programmable stage
  21765. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21766. if ( stageCompute === undefined ) {
  21767. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21768. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21769. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21770. backend.createProgram( stageCompute );
  21771. }
  21772. // determine compute pipeline
  21773. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21774. let pipeline = this.caches.get( cacheKey );
  21775. if ( pipeline === undefined ) {
  21776. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21777. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  21778. }
  21779. // keep track of all used times
  21780. pipeline.usedTimes ++;
  21781. stageCompute.usedTimes ++;
  21782. //
  21783. data.version = computeNode.version;
  21784. data.pipeline = pipeline;
  21785. }
  21786. return data.pipeline;
  21787. }
  21788. /**
  21789. * Returns a render pipeline for the given render object.
  21790. *
  21791. * @param {RenderObject} renderObject - The render object.
  21792. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21793. * @return {RenderPipeline} The render pipeline.
  21794. */
  21795. getForRender( renderObject, promises = null ) {
  21796. const { backend } = this;
  21797. const data = this.get( renderObject );
  21798. if ( this._needsRenderUpdate( renderObject ) ) {
  21799. const previousPipeline = data.pipeline;
  21800. if ( previousPipeline ) {
  21801. previousPipeline.usedTimes --;
  21802. previousPipeline.vertexProgram.usedTimes --;
  21803. previousPipeline.fragmentProgram.usedTimes --;
  21804. }
  21805. // get shader
  21806. const nodeBuilderState = renderObject.getNodeBuilderState();
  21807. const name = renderObject.material ? renderObject.material.name : '';
  21808. // programmable stages
  21809. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  21810. if ( stageVertex === undefined ) {
  21811. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  21812. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  21813. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  21814. backend.createProgram( stageVertex );
  21815. }
  21816. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  21817. if ( stageFragment === undefined ) {
  21818. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  21819. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  21820. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  21821. backend.createProgram( stageFragment );
  21822. }
  21823. // determine render pipeline
  21824. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21825. let pipeline = this.caches.get( cacheKey );
  21826. if ( pipeline === undefined ) {
  21827. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21828. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  21829. } else {
  21830. renderObject.pipeline = pipeline;
  21831. }
  21832. // keep track of all used times
  21833. pipeline.usedTimes ++;
  21834. stageVertex.usedTimes ++;
  21835. stageFragment.usedTimes ++;
  21836. //
  21837. data.pipeline = pipeline;
  21838. }
  21839. return data.pipeline;
  21840. }
  21841. /**
  21842. * Deletes the pipeline for the given render object.
  21843. *
  21844. * @param {RenderObject} object - The render object.
  21845. * @return {?Object} The deleted dictionary.
  21846. */
  21847. delete( object ) {
  21848. const pipeline = this.get( object ).pipeline;
  21849. if ( pipeline ) {
  21850. // pipeline
  21851. pipeline.usedTimes --;
  21852. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  21853. // programs
  21854. if ( pipeline.isComputePipeline ) {
  21855. pipeline.computeProgram.usedTimes --;
  21856. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  21857. } else {
  21858. pipeline.fragmentProgram.usedTimes --;
  21859. pipeline.vertexProgram.usedTimes --;
  21860. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  21861. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  21862. }
  21863. }
  21864. return super.delete( object );
  21865. }
  21866. /**
  21867. * Frees internal resources.
  21868. */
  21869. dispose() {
  21870. super.dispose();
  21871. this.caches = new Map();
  21872. this.programs = {
  21873. vertex: new Map(),
  21874. fragment: new Map(),
  21875. compute: new Map()
  21876. };
  21877. }
  21878. /**
  21879. * Updates the pipeline for the given render object.
  21880. *
  21881. * @param {RenderObject} renderObject - The render object.
  21882. */
  21883. updateForRender( renderObject ) {
  21884. this.getForRender( renderObject );
  21885. }
  21886. /**
  21887. * Returns a compute pipeline for the given parameters.
  21888. *
  21889. * @private
  21890. * @param {Node} computeNode - The compute node.
  21891. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21892. * @param {string} cacheKey - The cache key.
  21893. * @param {Array<BindGroup>} bindings - The bindings.
  21894. * @return {ComputePipeline} The compute pipeline.
  21895. */
  21896. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  21897. // check for existing pipeline
  21898. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  21899. let pipeline = this.caches.get( cacheKey );
  21900. if ( pipeline === undefined ) {
  21901. pipeline = new ComputePipeline( cacheKey, stageCompute );
  21902. this.caches.set( cacheKey, pipeline );
  21903. this.backend.createComputePipeline( pipeline, bindings );
  21904. }
  21905. return pipeline;
  21906. }
  21907. /**
  21908. * Returns a render pipeline for the given parameters.
  21909. *
  21910. * @private
  21911. * @param {RenderObject} renderObject - The render object.
  21912. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21913. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21914. * @param {string} cacheKey - The cache key.
  21915. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21916. * @return {ComputePipeline} The compute pipeline.
  21917. */
  21918. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  21919. // check for existing pipeline
  21920. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21921. let pipeline = this.caches.get( cacheKey );
  21922. if ( pipeline === undefined ) {
  21923. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  21924. this.caches.set( cacheKey, pipeline );
  21925. renderObject.pipeline = pipeline;
  21926. // The `promises` array is `null` by default and only set to an empty array when
  21927. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  21928. // pending promises that resolve when the render pipelines are ready for rendering.
  21929. this.backend.createRenderPipeline( renderObject, promises );
  21930. }
  21931. return pipeline;
  21932. }
  21933. /**
  21934. * Computes a cache key representing a compute pipeline.
  21935. *
  21936. * @private
  21937. * @param {Node} computeNode - The compute node.
  21938. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21939. * @return {string} The cache key.
  21940. */
  21941. _getComputeCacheKey( computeNode, stageCompute ) {
  21942. return computeNode.id + ',' + stageCompute.id;
  21943. }
  21944. /**
  21945. * Computes a cache key representing a render pipeline.
  21946. *
  21947. * @private
  21948. * @param {RenderObject} renderObject - The render object.
  21949. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21950. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21951. * @return {string} The cache key.
  21952. */
  21953. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  21954. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  21955. }
  21956. /**
  21957. * Releases the given pipeline.
  21958. *
  21959. * @private
  21960. * @param {Pipeline} pipeline - The pipeline to release.
  21961. */
  21962. _releasePipeline( pipeline ) {
  21963. this.caches.delete( pipeline.cacheKey );
  21964. }
  21965. /**
  21966. * Releases the shader program.
  21967. *
  21968. * @private
  21969. * @param {Object} program - The shader program to release.
  21970. */
  21971. _releaseProgram( program ) {
  21972. const code = program.code;
  21973. const stage = program.stage;
  21974. this.programs[ stage ].delete( code );
  21975. }
  21976. /**
  21977. * Returns `true` if the compute pipeline for the given compute node requires an update.
  21978. *
  21979. * @private
  21980. * @param {Node} computeNode - The compute node.
  21981. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  21982. */
  21983. _needsComputeUpdate( computeNode ) {
  21984. const data = this.get( computeNode );
  21985. return data.pipeline === undefined || data.version !== computeNode.version;
  21986. }
  21987. /**
  21988. * Returns `true` if the render pipeline for the given render object requires an update.
  21989. *
  21990. * @private
  21991. * @param {RenderObject} renderObject - The render object.
  21992. * @return {boolean} Whether the render object for the given render object requires an update or not.
  21993. */
  21994. _needsRenderUpdate( renderObject ) {
  21995. const data = this.get( renderObject );
  21996. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  21997. }
  21998. }
  21999. /**
  22000. * This renderer module manages the bindings of the renderer.
  22001. *
  22002. * @private
  22003. * @augments DataMap
  22004. */
  22005. class Bindings extends DataMap {
  22006. /**
  22007. * Constructs a new bindings management component.
  22008. *
  22009. * @param {Backend} backend - The renderer's backend.
  22010. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  22011. * @param {Textures} textures - Renderer component for managing textures.
  22012. * @param {Attributes} attributes - Renderer component for managing attributes.
  22013. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  22014. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22015. */
  22016. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22017. super();
  22018. /**
  22019. * The renderer's backend.
  22020. *
  22021. * @type {Backend}
  22022. */
  22023. this.backend = backend;
  22024. /**
  22025. * Renderer component for managing textures.
  22026. *
  22027. * @type {Textures}
  22028. */
  22029. this.textures = textures;
  22030. /**
  22031. * Renderer component for managing pipelines.
  22032. *
  22033. * @type {Pipelines}
  22034. */
  22035. this.pipelines = pipelines;
  22036. /**
  22037. * Renderer component for managing attributes.
  22038. *
  22039. * @type {Attributes}
  22040. */
  22041. this.attributes = attributes;
  22042. /**
  22043. * Renderer component for managing nodes related logic.
  22044. *
  22045. * @type {Nodes}
  22046. */
  22047. this.nodes = nodes;
  22048. /**
  22049. * Renderer component for managing metrics and monitoring data.
  22050. *
  22051. * @type {Info}
  22052. */
  22053. this.info = info;
  22054. this.pipelines.bindings = this; // assign bindings to pipelines
  22055. }
  22056. /**
  22057. * Returns the bind groups for the given render object.
  22058. *
  22059. * @param {RenderObject} renderObject - The render object.
  22060. * @return {Array<BindGroup>} The bind groups.
  22061. */
  22062. getForRender( renderObject ) {
  22063. const bindings = renderObject.getBindings();
  22064. for ( const bindGroup of bindings ) {
  22065. const groupData = this.get( bindGroup );
  22066. if ( groupData.bindGroup === undefined ) {
  22067. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22068. this._init( bindGroup );
  22069. this.backend.createBindings( bindGroup, bindings, 0 );
  22070. groupData.bindGroup = bindGroup;
  22071. }
  22072. }
  22073. return bindings;
  22074. }
  22075. /**
  22076. * Returns the bind groups for the given compute node.
  22077. *
  22078. * @param {Node} computeNode - The compute node.
  22079. * @return {Array<BindGroup>} The bind groups.
  22080. */
  22081. getForCompute( computeNode ) {
  22082. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22083. for ( const bindGroup of bindings ) {
  22084. const groupData = this.get( bindGroup );
  22085. if ( groupData.bindGroup === undefined ) {
  22086. this._init( bindGroup );
  22087. this.backend.createBindings( bindGroup, bindings, 0 );
  22088. groupData.bindGroup = bindGroup;
  22089. }
  22090. }
  22091. return bindings;
  22092. }
  22093. /**
  22094. * Updates the bindings for the given compute node.
  22095. *
  22096. * @param {Node} computeNode - The compute node.
  22097. */
  22098. updateForCompute( computeNode ) {
  22099. this._updateBindings( this.getForCompute( computeNode ) );
  22100. }
  22101. /**
  22102. * Updates the bindings for the given render object.
  22103. *
  22104. * @param {RenderObject} renderObject - The render object.
  22105. */
  22106. updateForRender( renderObject ) {
  22107. this._updateBindings( this.getForRender( renderObject ) );
  22108. }
  22109. /**
  22110. * Deletes the bindings for the given compute node.
  22111. *
  22112. * @param {Node} computeNode - The compute node.
  22113. */
  22114. deleteForCompute( computeNode ) {
  22115. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22116. for ( const bindGroup of bindings ) {
  22117. this.delete( bindGroup );
  22118. }
  22119. }
  22120. /**
  22121. * Deletes the bindings for the given renderObject node.
  22122. *
  22123. * @param {RenderObject} renderObject - The renderObject.
  22124. */
  22125. deleteForRender( renderObject ) {
  22126. const bindings = renderObject.getBindings();
  22127. for ( const bindGroup of bindings ) {
  22128. this.delete( bindGroup );
  22129. }
  22130. }
  22131. /**
  22132. * Updates the given array of bindings.
  22133. *
  22134. * @param {Array<BindGroup>} bindings - The bind groups.
  22135. */
  22136. _updateBindings( bindings ) {
  22137. for ( const bindGroup of bindings ) {
  22138. this._update( bindGroup, bindings );
  22139. }
  22140. }
  22141. /**
  22142. * Initializes the given bind group.
  22143. *
  22144. * @param {BindGroup} bindGroup - The bind group to initialize.
  22145. */
  22146. _init( bindGroup ) {
  22147. for ( const binding of bindGroup.bindings ) {
  22148. if ( binding.isSampledTexture ) {
  22149. this.textures.updateTexture( binding.texture );
  22150. } else if ( binding.isSampler ) {
  22151. this.textures.updateSampler( binding.texture );
  22152. } else if ( binding.isStorageBuffer ) {
  22153. const attribute = binding.attribute;
  22154. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22155. this.attributes.update( attribute, attributeType );
  22156. }
  22157. }
  22158. }
  22159. /**
  22160. * Updates the given bind group.
  22161. *
  22162. * @param {BindGroup} bindGroup - The bind group to update.
  22163. * @param {Array<BindGroup>} bindings - The bind groups.
  22164. */
  22165. _update( bindGroup, bindings ) {
  22166. const { backend } = this;
  22167. let needsBindingsUpdate = false;
  22168. let cacheBindings = true;
  22169. let cacheIndex = 0;
  22170. let version = 0;
  22171. // iterate over all bindings and check if buffer updates or a new binding group is required
  22172. for ( const binding of bindGroup.bindings ) {
  22173. const updatedGroup = this.nodes.updateGroup( binding );
  22174. // every uniforms group is a uniform buffer. So if no update is required,
  22175. // we move one with the next binding. Otherwise the next if block will update the group.
  22176. if ( updatedGroup === false ) continue;
  22177. //
  22178. if ( binding.isStorageBuffer ) {
  22179. const attribute = binding.attribute;
  22180. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22181. this.attributes.update( attribute, attributeType );
  22182. }
  22183. if ( binding.isUniformBuffer ) {
  22184. const updated = binding.update();
  22185. if ( updated ) {
  22186. backend.updateBinding( binding );
  22187. }
  22188. } else if ( binding.isSampledTexture ) {
  22189. const updated = binding.update();
  22190. // get the texture data after the update, to sync the texture reference from node
  22191. const texture = binding.texture;
  22192. const texturesTextureData = this.textures.get( texture );
  22193. if ( updated ) {
  22194. // version: update the texture data or create a new one
  22195. this.textures.updateTexture( texture );
  22196. // generation: update the bindings if a new texture has been created
  22197. if ( binding.generation !== texturesTextureData.generation ) {
  22198. binding.generation = texturesTextureData.generation;
  22199. needsBindingsUpdate = true;
  22200. cacheBindings = false;
  22201. }
  22202. }
  22203. const textureData = backend.get( texture );
  22204. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  22205. cacheBindings = false;
  22206. } else {
  22207. cacheIndex = cacheIndex * 10 + texture.id;
  22208. version += texture.version;
  22209. }
  22210. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  22211. const textureData = this.get( texture );
  22212. if ( binding.store === true ) {
  22213. textureData.needsMipmap = true;
  22214. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22215. this.backend.generateMipmaps( texture );
  22216. textureData.needsMipmap = false;
  22217. }
  22218. }
  22219. } else if ( binding.isSampler ) {
  22220. const updated = binding.update();
  22221. if ( updated ) {
  22222. const samplerKey = this.textures.updateSampler( binding.texture );
  22223. if ( binding.samplerKey !== samplerKey ) {
  22224. binding.samplerKey = samplerKey;
  22225. needsBindingsUpdate = true;
  22226. cacheBindings = false;
  22227. }
  22228. }
  22229. }
  22230. }
  22231. if ( needsBindingsUpdate === true ) {
  22232. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  22233. }
  22234. }
  22235. }
  22236. /**
  22237. * Default sorting function for opaque render items.
  22238. *
  22239. * @private
  22240. * @function
  22241. * @param {Object} a - The first render item.
  22242. * @param {Object} b - The second render item.
  22243. * @return {number} A numeric value which defines the sort order.
  22244. */
  22245. function painterSortStable( a, b ) {
  22246. if ( a.groupOrder !== b.groupOrder ) {
  22247. return a.groupOrder - b.groupOrder;
  22248. } else if ( a.renderOrder !== b.renderOrder ) {
  22249. return a.renderOrder - b.renderOrder;
  22250. } else if ( a.z !== b.z ) {
  22251. return a.z - b.z;
  22252. } else {
  22253. return a.id - b.id;
  22254. }
  22255. }
  22256. /**
  22257. * Default sorting function for transparent render items.
  22258. *
  22259. * @private
  22260. * @function
  22261. * @param {Object} a - The first render item.
  22262. * @param {Object} b - The second render item.
  22263. * @return {number} A numeric value which defines the sort order.
  22264. */
  22265. function reversePainterSortStable( a, b ) {
  22266. if ( a.groupOrder !== b.groupOrder ) {
  22267. return a.groupOrder - b.groupOrder;
  22268. } else if ( a.renderOrder !== b.renderOrder ) {
  22269. return a.renderOrder - b.renderOrder;
  22270. } else if ( a.z !== b.z ) {
  22271. return b.z - a.z;
  22272. } else {
  22273. return a.id - b.id;
  22274. }
  22275. }
  22276. /**
  22277. * Returns `true` if the given transparent material requires a double pass.
  22278. *
  22279. * @private
  22280. * @function
  22281. * @param {Material} material - The transparent material.
  22282. * @return {boolean} Whether the given material requires a double pass or not.
  22283. */
  22284. function needsDoublePass( material ) {
  22285. const hasTransmission = material.transmission > 0 || ( material.transmissionNode && material.transmissionNode.isNode );
  22286. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  22287. }
  22288. /**
  22289. * When the renderer analyzes the scene at the beginning of a render call,
  22290. * it stores 3D object for further processing in render lists. Depending on the
  22291. * properties of a 3D objects (like their transformation or material state), the
  22292. * objects are maintained in ordered lists for the actual rendering.
  22293. *
  22294. * Render lists are unique per scene and camera combination.
  22295. *
  22296. * @private
  22297. * @augments Pipeline
  22298. */
  22299. class RenderList {
  22300. /**
  22301. * Constructs a render list.
  22302. *
  22303. * @param {Lighting} lighting - The lighting management component.
  22304. * @param {Scene} scene - The scene.
  22305. * @param {Camera} camera - The camera the scene is rendered with.
  22306. */
  22307. constructor( lighting, scene, camera ) {
  22308. /**
  22309. * 3D objects are transformed into render items and stored in this array.
  22310. *
  22311. * @type {Array<Object>}
  22312. */
  22313. this.renderItems = [];
  22314. /**
  22315. * The current render items index.
  22316. *
  22317. * @type {number}
  22318. * @default 0
  22319. */
  22320. this.renderItemsIndex = 0;
  22321. /**
  22322. * A list with opaque render items.
  22323. *
  22324. * @type {Array<Object>}
  22325. */
  22326. this.opaque = [];
  22327. /**
  22328. * A list with transparent render items which require
  22329. * double pass rendering (e.g. transmissive objects).
  22330. *
  22331. * @type {Array<Object>}
  22332. */
  22333. this.transparentDoublePass = [];
  22334. /**
  22335. * A list with transparent render items.
  22336. *
  22337. * @type {Array<Object>}
  22338. */
  22339. this.transparent = [];
  22340. /**
  22341. * A list with transparent render bundle data.
  22342. *
  22343. * @type {Array<Object>}
  22344. */
  22345. this.bundles = [];
  22346. /**
  22347. * The render list's lights node. This node is later
  22348. * relevant for the actual analytical light nodes which
  22349. * compute the scene's lighting in the shader.
  22350. *
  22351. * @type {LightsNode}
  22352. */
  22353. this.lightsNode = lighting.getNode( scene, camera );
  22354. /**
  22355. * The scene's lights stored in an array. This array
  22356. * is used to setup the lights node.
  22357. *
  22358. * @type {Array<Light>}
  22359. */
  22360. this.lightsArray = [];
  22361. /**
  22362. * The scene.
  22363. *
  22364. * @type {Scene}
  22365. */
  22366. this.scene = scene;
  22367. /**
  22368. * The camera the scene is rendered with.
  22369. *
  22370. * @type {Camera}
  22371. */
  22372. this.camera = camera;
  22373. /**
  22374. * How many objects perform occlusion query tests.
  22375. *
  22376. * @type {number}
  22377. * @default 0
  22378. */
  22379. this.occlusionQueryCount = 0;
  22380. }
  22381. /**
  22382. * This method is called right at the beginning of a render call
  22383. * before the scene is analyzed. It prepares the internal data
  22384. * structures for the upcoming render lists generation.
  22385. *
  22386. * @return {RenderList} A reference to this render list.
  22387. */
  22388. begin() {
  22389. this.renderItemsIndex = 0;
  22390. this.opaque.length = 0;
  22391. this.transparentDoublePass.length = 0;
  22392. this.transparent.length = 0;
  22393. this.bundles.length = 0;
  22394. this.lightsArray.length = 0;
  22395. this.occlusionQueryCount = 0;
  22396. return this;
  22397. }
  22398. /**
  22399. * Returns a render item for the giving render item state. The state is defined
  22400. * by a series of object-related parameters.
  22401. *
  22402. * The method avoids object creation by holding render items and reusing them in
  22403. * subsequent render calls (just with different property values).
  22404. *
  22405. * @param {Object3D} object - The 3D object.
  22406. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22407. * @param {Material} material - The 3D object's material.
  22408. * @param {number} groupOrder - The current group order.
  22409. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22410. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22411. * @param {ClippingContext} clippingContext - The current clipping context.
  22412. * @return {Object} The render item.
  22413. */
  22414. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22415. let renderItem = this.renderItems[ this.renderItemsIndex ];
  22416. if ( renderItem === undefined ) {
  22417. renderItem = {
  22418. id: object.id,
  22419. object: object,
  22420. geometry: geometry,
  22421. material: material,
  22422. groupOrder: groupOrder,
  22423. renderOrder: object.renderOrder,
  22424. z: z,
  22425. group: group,
  22426. clippingContext: clippingContext
  22427. };
  22428. this.renderItems[ this.renderItemsIndex ] = renderItem;
  22429. } else {
  22430. renderItem.id = object.id;
  22431. renderItem.object = object;
  22432. renderItem.geometry = geometry;
  22433. renderItem.material = material;
  22434. renderItem.groupOrder = groupOrder;
  22435. renderItem.renderOrder = object.renderOrder;
  22436. renderItem.z = z;
  22437. renderItem.group = group;
  22438. renderItem.clippingContext = clippingContext;
  22439. }
  22440. this.renderItemsIndex ++;
  22441. return renderItem;
  22442. }
  22443. /**
  22444. * Pushes the given object as a render item to the internal render lists.
  22445. * The selected lists depend on the object properties.
  22446. *
  22447. * @param {Object3D} object - The 3D object.
  22448. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22449. * @param {Material} material - The 3D object's material.
  22450. * @param {number} groupOrder - The current group order.
  22451. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22452. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22453. * @param {ClippingContext} clippingContext - The current clipping context.
  22454. */
  22455. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22456. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22457. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  22458. if ( material.transparent === true || material.transmission > 0 ||
  22459. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22460. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22461. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  22462. this.transparent.push( renderItem );
  22463. } else {
  22464. this.opaque.push( renderItem );
  22465. }
  22466. }
  22467. /**
  22468. * Inserts the given object as a render item at the start of the internal render lists.
  22469. * The selected lists depend on the object properties.
  22470. *
  22471. * @param {Object3D} object - The 3D object.
  22472. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22473. * @param {Material} material - The 3D object's material.
  22474. * @param {number} groupOrder - The current group order.
  22475. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22476. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22477. * @param {ClippingContext} clippingContext - The current clipping context.
  22478. */
  22479. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22480. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22481. if ( material.transparent === true || material.transmission > 0 ||
  22482. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22483. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22484. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  22485. this.transparent.unshift( renderItem );
  22486. } else {
  22487. this.opaque.unshift( renderItem );
  22488. }
  22489. }
  22490. /**
  22491. * Pushes render bundle group data into the render list.
  22492. *
  22493. * @param {Object} group - Bundle group data.
  22494. */
  22495. pushBundle( group ) {
  22496. this.bundles.push( group );
  22497. }
  22498. /**
  22499. * Pushes a light into the render list.
  22500. *
  22501. * @param {Light} light - The light.
  22502. */
  22503. pushLight( light ) {
  22504. this.lightsArray.push( light );
  22505. }
  22506. /**
  22507. * Sorts the internal render lists.
  22508. *
  22509. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  22510. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  22511. */
  22512. sort( customOpaqueSort, customTransparentSort ) {
  22513. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  22514. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  22515. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  22516. }
  22517. /**
  22518. * This method performs finalizing tasks right after the render lists
  22519. * have been generated.
  22520. */
  22521. finish() {
  22522. // update lights
  22523. this.lightsNode.setLights( this.lightsArray );
  22524. // Clear references from inactive renderItems in the list
  22525. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  22526. const renderItem = this.renderItems[ i ];
  22527. if ( renderItem.id === null ) break;
  22528. renderItem.id = null;
  22529. renderItem.object = null;
  22530. renderItem.geometry = null;
  22531. renderItem.material = null;
  22532. renderItem.groupOrder = null;
  22533. renderItem.renderOrder = null;
  22534. renderItem.z = null;
  22535. renderItem.group = null;
  22536. renderItem.clippingContext = null;
  22537. }
  22538. }
  22539. }
  22540. const _chainKeys$4 = [];
  22541. /**
  22542. * This renderer module manages the render lists which are unique
  22543. * per scene and camera combination.
  22544. *
  22545. * @private
  22546. */
  22547. class RenderLists {
  22548. /**
  22549. * Constructs a render lists management component.
  22550. *
  22551. * @param {Lighting} lighting - The lighting management component.
  22552. */
  22553. constructor( lighting ) {
  22554. /**
  22555. * The lighting management component.
  22556. *
  22557. * @type {Lighting}
  22558. */
  22559. this.lighting = lighting;
  22560. /**
  22561. * The internal chain map which holds the render lists.
  22562. *
  22563. * @type {ChainMap}
  22564. */
  22565. this.lists = new ChainMap();
  22566. }
  22567. /**
  22568. * Returns a render list for the given scene and camera.
  22569. *
  22570. * @param {Scene} scene - The scene.
  22571. * @param {Camera} camera - The camera.
  22572. * @return {RenderList} The render list.
  22573. */
  22574. get( scene, camera ) {
  22575. const lists = this.lists;
  22576. _chainKeys$4[ 0 ] = scene;
  22577. _chainKeys$4[ 1 ] = camera;
  22578. let list = lists.get( _chainKeys$4 );
  22579. if ( list === undefined ) {
  22580. list = new RenderList( this.lighting, scene, camera );
  22581. lists.set( _chainKeys$4, list );
  22582. }
  22583. _chainKeys$4.length = 0;
  22584. return list;
  22585. }
  22586. /**
  22587. * Frees all internal resources.
  22588. */
  22589. dispose() {
  22590. this.lists = new ChainMap();
  22591. }
  22592. }
  22593. let _id$8 = 0;
  22594. /**
  22595. * Any render or compute command is executed in a specific context that defines
  22596. * the state of the renderer and its backend. Typical examples for such context
  22597. * data are the current clear values or data from the active framebuffer. This
  22598. * module is used to represent these contexts as objects.
  22599. *
  22600. * @private
  22601. */
  22602. class RenderContext {
  22603. /**
  22604. * Constructs a new render context.
  22605. */
  22606. constructor() {
  22607. /**
  22608. * The context's ID.
  22609. *
  22610. * @type {number}
  22611. */
  22612. this.id = _id$8 ++;
  22613. /**
  22614. * Whether the current active framebuffer has a color attachment.
  22615. *
  22616. * @type {boolean}
  22617. * @default true
  22618. */
  22619. this.color = true;
  22620. /**
  22621. * Whether the color attachment should be cleared or not.
  22622. *
  22623. * @type {boolean}
  22624. * @default true
  22625. */
  22626. this.clearColor = true;
  22627. /**
  22628. * The clear color value.
  22629. *
  22630. * @type {Object}
  22631. * @default true
  22632. */
  22633. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  22634. /**
  22635. * Whether the current active framebuffer has a depth attachment.
  22636. *
  22637. * @type {boolean}
  22638. * @default true
  22639. */
  22640. this.depth = true;
  22641. /**
  22642. * Whether the depth attachment should be cleared or not.
  22643. *
  22644. * @type {boolean}
  22645. * @default true
  22646. */
  22647. this.clearDepth = true;
  22648. /**
  22649. * The clear depth value.
  22650. *
  22651. * @type {number}
  22652. * @default 1
  22653. */
  22654. this.clearDepthValue = 1;
  22655. /**
  22656. * Whether the current active framebuffer has a stencil attachment.
  22657. *
  22658. * @type {boolean}
  22659. * @default false
  22660. */
  22661. this.stencil = false;
  22662. /**
  22663. * Whether the stencil attachment should be cleared or not.
  22664. *
  22665. * @type {boolean}
  22666. * @default true
  22667. */
  22668. this.clearStencil = true;
  22669. /**
  22670. * The clear stencil value.
  22671. *
  22672. * @type {number}
  22673. * @default 1
  22674. */
  22675. this.clearStencilValue = 1;
  22676. /**
  22677. * By default the viewport encloses the entire framebuffer If a smaller
  22678. * viewport is manually defined, this property is to `true` by the renderer.
  22679. *
  22680. * @type {boolean}
  22681. * @default false
  22682. */
  22683. this.viewport = false;
  22684. /**
  22685. * The viewport value. This value is in physical pixels meaning it incorporates
  22686. * the renderer's pixel ratio. The viewport property of render targets or
  22687. * the renderer is in logical pixels.
  22688. *
  22689. * @type {Vector4}
  22690. */
  22691. this.viewportValue = new Vector4();
  22692. /**
  22693. * When the scissor test is active and scissor rectangle smaller than the
  22694. * framebuffers dimensions, this property is to `true` by the renderer.
  22695. *
  22696. * @type {boolean}
  22697. * @default false
  22698. */
  22699. this.scissor = false;
  22700. /**
  22701. * The scissor rectangle.
  22702. *
  22703. * @type {Vector4}
  22704. */
  22705. this.scissorValue = new Vector4();
  22706. /**
  22707. * The active render target.
  22708. *
  22709. * @type {?RenderTarget}
  22710. * @default null
  22711. */
  22712. this.renderTarget = null;
  22713. /**
  22714. * The textures of the active render target.
  22715. * `null` when no render target is set.
  22716. *
  22717. * @type {?Array<Texture>}
  22718. * @default null
  22719. */
  22720. this.textures = null;
  22721. /**
  22722. * The depth texture of the active render target.
  22723. * `null` when no render target is set.
  22724. *
  22725. * @type {?DepthTexture}
  22726. * @default null
  22727. */
  22728. this.depthTexture = null;
  22729. /**
  22730. * The active cube face.
  22731. *
  22732. * @type {number}
  22733. * @default 0
  22734. */
  22735. this.activeCubeFace = 0;
  22736. /**
  22737. * The active mipmap level.
  22738. *
  22739. * @type {number}
  22740. * @default 0
  22741. */
  22742. this.activeMipmapLevel = 0;
  22743. /**
  22744. * The number of MSAA samples. This value is always `1` when
  22745. * MSAA isn't used.
  22746. *
  22747. * @type {number}
  22748. * @default 1
  22749. */
  22750. this.sampleCount = 1;
  22751. /**
  22752. * The active render target's width in physical pixels.
  22753. *
  22754. * @type {number}
  22755. * @default 0
  22756. */
  22757. this.width = 0;
  22758. /**
  22759. * The active render target's height in physical pixels.
  22760. *
  22761. * @type {number}
  22762. * @default 0
  22763. */
  22764. this.height = 0;
  22765. /**
  22766. * The occlusion query count.
  22767. *
  22768. * @type {number}
  22769. * @default 0
  22770. */
  22771. this.occlusionQueryCount = 0;
  22772. /**
  22773. * The current clipping context.
  22774. *
  22775. * @type {?ClippingContext}
  22776. * @default null
  22777. */
  22778. this.clippingContext = null;
  22779. /**
  22780. * This flag can be used for type testing.
  22781. *
  22782. * @type {boolean}
  22783. * @readonly
  22784. * @default true
  22785. */
  22786. this.isRenderContext = true;
  22787. }
  22788. /**
  22789. * Returns the cache key of this render context.
  22790. *
  22791. * @return {number} The cache key.
  22792. */
  22793. getCacheKey() {
  22794. return getCacheKey( this );
  22795. }
  22796. }
  22797. /**
  22798. * Computes a cache key for the given render context. This key
  22799. * should identify the render target state so it is possible to
  22800. * configure the correct attachments in the respective backend.
  22801. *
  22802. * @param {RenderContext} renderContext - The render context.
  22803. * @return {number} The cache key.
  22804. */
  22805. function getCacheKey( renderContext ) {
  22806. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  22807. const values = [ activeCubeFace, activeMipmapLevel ];
  22808. for ( const texture of textures ) {
  22809. values.push( texture.id );
  22810. }
  22811. return hashArray( values );
  22812. }
  22813. const _chainKeys$3 = [];
  22814. const _defaultScene = /*@__PURE__*/ new Scene();
  22815. const _defaultCamera = /*@__PURE__*/ new Camera();
  22816. /**
  22817. * This module manages the render contexts of the renderer.
  22818. *
  22819. * @private
  22820. */
  22821. class RenderContexts {
  22822. /**
  22823. * Constructs a new render context management component.
  22824. */
  22825. constructor() {
  22826. /**
  22827. * A dictionary that manages render contexts in chain maps
  22828. * for each attachment state.
  22829. *
  22830. * @type {Object<string,ChainMap>}
  22831. */
  22832. this.chainMaps = {};
  22833. }
  22834. /**
  22835. * Returns a render context for the given scene, camera and render target.
  22836. *
  22837. * @param {Scene} scene - The scene.
  22838. * @param {Camera} camera - The camera that is used to render the scene.
  22839. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22840. * @param {?MRT} [mrt=null] - The active multiple render target.
  22841. * @return {RenderContext} The render context.
  22842. */
  22843. get( scene, camera, renderTarget = null, mrt = null ) {
  22844. let index = 0;
  22845. if ( mrt !== null ) {
  22846. // TODO: Improve ChainMap so that it only matches submaps corresponding to the key lengths.
  22847. // For we use: if ( mrt !== null ) _chainKeys[ 2 ] = mrt;
  22848. _chainKeys$3[ index ++ ] = mrt;
  22849. }
  22850. _chainKeys$3[ index ++ ] = scene;
  22851. _chainKeys$3[ index ++ ] = camera;
  22852. let attachmentState;
  22853. if ( renderTarget === null ) {
  22854. attachmentState = 'default';
  22855. } else {
  22856. const format = renderTarget.texture.format;
  22857. const count = renderTarget.textures.length;
  22858. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  22859. }
  22860. const chainMap = this._getChainMap( attachmentState );
  22861. let renderState = chainMap.get( _chainKeys$3 );
  22862. if ( renderState === undefined ) {
  22863. renderState = new RenderContext();
  22864. chainMap.set( _chainKeys$3, renderState );
  22865. }
  22866. _chainKeys$3.length = 0;
  22867. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22868. return renderState;
  22869. }
  22870. /**
  22871. * Returns a render context intended for clear operations.
  22872. *
  22873. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22874. * @return {RenderContext} The render context.
  22875. */
  22876. getForClear( renderTarget = null ) {
  22877. return this.get( _defaultScene, _defaultCamera, renderTarget );
  22878. }
  22879. /**
  22880. * Returns a chain map for the given attachment state.
  22881. *
  22882. * @private
  22883. * @param {string} attachmentState - The attachment state.
  22884. * @return {ChainMap} The chain map.
  22885. */
  22886. _getChainMap( attachmentState ) {
  22887. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  22888. }
  22889. /**
  22890. * Frees internal resources.
  22891. */
  22892. dispose() {
  22893. this.chainMaps = {};
  22894. }
  22895. }
  22896. const _size$3 = /*@__PURE__*/ new Vector3();
  22897. /**
  22898. * This module manages the textures of the renderer.
  22899. *
  22900. * @private
  22901. * @augments DataMap
  22902. */
  22903. class Textures extends DataMap {
  22904. /**
  22905. * Constructs a new texture management component.
  22906. *
  22907. * @param {Renderer} renderer - The renderer.
  22908. * @param {Backend} backend - The renderer's backend.
  22909. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22910. */
  22911. constructor( renderer, backend, info ) {
  22912. super();
  22913. /**
  22914. * The renderer.
  22915. *
  22916. * @type {Renderer}
  22917. */
  22918. this.renderer = renderer;
  22919. /**
  22920. * The backend.
  22921. *
  22922. * @type {Backend}
  22923. */
  22924. this.backend = backend;
  22925. /**
  22926. * Renderer component for managing metrics and monitoring data.
  22927. *
  22928. * @type {Info}
  22929. */
  22930. this.info = info;
  22931. }
  22932. /**
  22933. * Updates the given render target. Based on the given render target configuration,
  22934. * it updates the texture states representing the attachments of the framebuffer.
  22935. *
  22936. * @param {RenderTarget} renderTarget - The render target to update.
  22937. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  22938. */
  22939. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  22940. const renderTargetData = this.get( renderTarget );
  22941. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22942. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  22943. const textures = renderTarget.textures;
  22944. const size = this.getSize( textures[ 0 ] );
  22945. const mipWidth = size.width >> activeMipmapLevel;
  22946. const mipHeight = size.height >> activeMipmapLevel;
  22947. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  22948. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  22949. let textureNeedsUpdate = false;
  22950. if ( depthTexture === undefined && useDepthTexture ) {
  22951. depthTexture = new DepthTexture();
  22952. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  22953. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  22954. depthTexture.image.width = mipWidth;
  22955. depthTexture.image.height = mipHeight;
  22956. depthTexture.image.depth = size.depth;
  22957. depthTexture.renderTarget = renderTarget;
  22958. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  22959. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  22960. }
  22961. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  22962. textureNeedsUpdate = true;
  22963. if ( depthTexture ) {
  22964. depthTexture.needsUpdate = true;
  22965. depthTexture.image.width = mipWidth;
  22966. depthTexture.image.height = mipHeight;
  22967. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  22968. }
  22969. }
  22970. renderTargetData.width = size.width;
  22971. renderTargetData.height = size.height;
  22972. renderTargetData.textures = textures;
  22973. renderTargetData.depthTexture = depthTexture || null;
  22974. renderTargetData.depth = renderTarget.depthBuffer;
  22975. renderTargetData.stencil = renderTarget.stencilBuffer;
  22976. renderTargetData.renderTarget = renderTarget;
  22977. if ( renderTargetData.sampleCount !== sampleCount ) {
  22978. textureNeedsUpdate = true;
  22979. if ( depthTexture ) {
  22980. depthTexture.needsUpdate = true;
  22981. }
  22982. renderTargetData.sampleCount = sampleCount;
  22983. }
  22984. //
  22985. const options = { sampleCount };
  22986. // XR render targets require no texture updates
  22987. if ( renderTarget.isXRRenderTarget !== true ) {
  22988. for ( let i = 0; i < textures.length; i ++ ) {
  22989. const texture = textures[ i ];
  22990. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  22991. this.updateTexture( texture, options );
  22992. }
  22993. if ( depthTexture ) {
  22994. this.updateTexture( depthTexture, options );
  22995. }
  22996. }
  22997. // dispose handler
  22998. if ( renderTargetData.initialized !== true ) {
  22999. renderTargetData.initialized = true;
  23000. // dispose
  23001. renderTargetData.onDispose = () => {
  23002. this._destroyRenderTarget( renderTarget );
  23003. };
  23004. renderTarget.addEventListener( 'dispose', renderTargetData.onDispose );
  23005. }
  23006. }
  23007. /**
  23008. * Updates the given texture. Depending on the texture state, this method
  23009. * triggers the upload of texture data to the GPU memory. If the texture data are
  23010. * not yet ready for the upload, it uses default texture data for as a placeholder.
  23011. *
  23012. * @param {Texture} texture - The texture to update.
  23013. * @param {Object} [options={}] - The options.
  23014. */
  23015. updateTexture( texture, options = {} ) {
  23016. const textureData = this.get( texture );
  23017. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  23018. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  23019. const backend = this.backend;
  23020. if ( isRenderTarget && textureData.initialized === true ) {
  23021. // it's an update
  23022. backend.destroyTexture( texture );
  23023. }
  23024. //
  23025. if ( texture.isFramebufferTexture ) {
  23026. const renderTarget = this.renderer.getRenderTarget();
  23027. if ( renderTarget ) {
  23028. texture.type = renderTarget.texture.type;
  23029. } else {
  23030. texture.type = UnsignedByteType;
  23031. }
  23032. }
  23033. //
  23034. const { width, height, depth } = this.getSize( texture );
  23035. options.width = width;
  23036. options.height = height;
  23037. options.depth = depth;
  23038. options.needsMipmaps = this.needsMipmaps( texture );
  23039. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  23040. // TODO: Uniformly handle mipmap definitions
  23041. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  23042. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  23043. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  23044. //
  23045. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  23046. backend.createTexture( texture, options );
  23047. textureData.generation = texture.version;
  23048. } else {
  23049. if ( texture.version > 0 ) {
  23050. const image = texture.image;
  23051. if ( image === undefined ) {
  23052. warn( 'Renderer: Texture marked for update but image is undefined.' );
  23053. } else if ( image.complete === false ) {
  23054. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  23055. } else {
  23056. if ( texture.images ) {
  23057. const images = [];
  23058. for ( const image of texture.images ) {
  23059. images.push( image );
  23060. }
  23061. options.images = images;
  23062. } else {
  23063. options.image = image;
  23064. }
  23065. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  23066. backend.createTexture( texture, options );
  23067. textureData.isDefaultTexture = false;
  23068. textureData.generation = texture.version;
  23069. }
  23070. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  23071. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  23072. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  23073. backend.generateMipmaps( texture );
  23074. }
  23075. if ( texture.onUpdate ) texture.onUpdate( texture );
  23076. }
  23077. } else {
  23078. // async update
  23079. backend.createDefaultTexture( texture );
  23080. textureData.isDefaultTexture = true;
  23081. textureData.generation = texture.version;
  23082. }
  23083. }
  23084. // dispose handler
  23085. if ( textureData.initialized !== true ) {
  23086. textureData.initialized = true;
  23087. textureData.generation = texture.version;
  23088. //
  23089. this.info.memory.textures ++;
  23090. //
  23091. if ( texture.isVideoTexture && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  23092. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  23093. }
  23094. // dispose
  23095. textureData.onDispose = () => {
  23096. this._destroyTexture( texture );
  23097. };
  23098. texture.addEventListener( 'dispose', textureData.onDispose );
  23099. }
  23100. //
  23101. textureData.version = texture.version;
  23102. }
  23103. /**
  23104. * Updates the sampler for the given texture. This method has no effect
  23105. * for the WebGL backend since it has no concept of samplers. Texture
  23106. * parameters are configured with the `texParameter()` command for each
  23107. * texture.
  23108. *
  23109. * In WebGPU, samplers are objects like textures and it's possible to share
  23110. * them when the texture parameters match.
  23111. *
  23112. * @param {Texture} texture - The texture to update the sampler for.
  23113. * @return {string} The current sampler key.
  23114. */
  23115. updateSampler( texture ) {
  23116. return this.backend.updateSampler( texture );
  23117. }
  23118. /**
  23119. * Computes the size of the given texture and writes the result
  23120. * into the target vector. This vector is also returned by the
  23121. * method.
  23122. *
  23123. * If no texture data are available for the compute yet, the method
  23124. * returns default size values.
  23125. *
  23126. * @param {Texture} texture - The texture to compute the size for.
  23127. * @param {Vector3} target - The target vector.
  23128. * @return {Vector3} The target vector.
  23129. */
  23130. getSize( texture, target = _size$3 ) {
  23131. let image = texture.images ? texture.images[ 0 ] : texture.image;
  23132. if ( image ) {
  23133. if ( image.image !== undefined ) image = image.image;
  23134. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  23135. target.width = image.videoWidth || 1;
  23136. target.height = image.videoHeight || 1;
  23137. target.depth = 1;
  23138. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  23139. target.width = image.displayWidth || 1;
  23140. target.height = image.displayHeight || 1;
  23141. target.depth = 1;
  23142. } else {
  23143. target.width = image.width || 1;
  23144. target.height = image.height || 1;
  23145. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  23146. }
  23147. } else {
  23148. target.width = target.height = target.depth = 1;
  23149. }
  23150. return target;
  23151. }
  23152. /**
  23153. * Computes the number of mipmap levels for the given texture.
  23154. *
  23155. * @param {Texture} texture - The texture.
  23156. * @param {number} width - The texture's width.
  23157. * @param {number} height - The texture's height.
  23158. * @return {number} The number of mipmap levels.
  23159. */
  23160. getMipLevels( texture, width, height ) {
  23161. let mipLevelCount;
  23162. if ( texture.mipmaps.length > 0 ) {
  23163. mipLevelCount = texture.mipmaps.length;
  23164. } else {
  23165. if ( texture.isCompressedTexture === true ) {
  23166. // it is not possible to compute mipmaps for compressed textures. So
  23167. // when no mipmaps are defined in "texture.mipmaps", force a texture
  23168. // level of 1
  23169. mipLevelCount = 1;
  23170. } else {
  23171. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  23172. }
  23173. }
  23174. return mipLevelCount;
  23175. }
  23176. /**
  23177. * Returns `true` if the given texture makes use of mipmapping.
  23178. *
  23179. * @param {Texture} texture - The texture.
  23180. * @return {boolean} Whether mipmaps are required or not.
  23181. */
  23182. needsMipmaps( texture ) {
  23183. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  23184. }
  23185. /**
  23186. * Frees internal resources when the given render target isn't
  23187. * required anymore.
  23188. *
  23189. * @param {RenderTarget} renderTarget - The render target to destroy.
  23190. */
  23191. _destroyRenderTarget( renderTarget ) {
  23192. if ( this.has( renderTarget ) === true ) {
  23193. const renderTargetData = this.get( renderTarget );
  23194. const textures = renderTargetData.textures;
  23195. const depthTexture = renderTargetData.depthTexture;
  23196. //
  23197. renderTarget.removeEventListener( 'dispose', renderTargetData.onDispose );
  23198. //
  23199. for ( let i = 0; i < textures.length; i ++ ) {
  23200. this._destroyTexture( textures[ i ] );
  23201. }
  23202. if ( depthTexture ) {
  23203. this._destroyTexture( depthTexture );
  23204. }
  23205. this.delete( renderTarget );
  23206. this.backend.delete( renderTarget );
  23207. }
  23208. }
  23209. /**
  23210. * Frees internal resource when the given texture isn't
  23211. * required anymore.
  23212. *
  23213. * @param {Texture} texture - The texture to destroy.
  23214. */
  23215. _destroyTexture( texture ) {
  23216. if ( this.has( texture ) === true ) {
  23217. const textureData = this.get( texture );
  23218. //
  23219. texture.removeEventListener( 'dispose', textureData.onDispose );
  23220. // if a texture is not ready for use, it falls back to a default texture so it's possible
  23221. // to use it for rendering. If a texture in this state is disposed, it's important to
  23222. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  23223. // other textures.
  23224. const isDefaultTexture = textureData.isDefaultTexture;
  23225. this.backend.destroyTexture( texture, isDefaultTexture );
  23226. this.delete( texture );
  23227. this.info.memory.textures --;
  23228. }
  23229. }
  23230. }
  23231. /**
  23232. * A four-component version of {@link Color} which is internally
  23233. * used by the renderer to represents clear color with alpha as
  23234. * one object.
  23235. *
  23236. * @private
  23237. * @augments Color
  23238. */
  23239. class Color4 extends Color {
  23240. /**
  23241. * Constructs a new four-component color.
  23242. * You can also pass a single THREE.Color, hex or
  23243. * string argument to this constructor.
  23244. *
  23245. * @param {number|string} [r=1] - The red value.
  23246. * @param {number} [g=1] - The green value.
  23247. * @param {number} [b=1] - The blue value.
  23248. * @param {number} [a=1] - The alpha value.
  23249. */
  23250. constructor( r, g, b, a = 1 ) {
  23251. super( r, g, b );
  23252. this.a = a;
  23253. }
  23254. /**
  23255. * Overwrites the default to honor alpha.
  23256. * You can also pass a single THREE.Color, hex or
  23257. * string argument to this method.
  23258. *
  23259. * @param {number|string|Color} r - The red value.
  23260. * @param {number} [g] - The green value.
  23261. * @param {number} [b] - The blue value.
  23262. * @param {number} [a=1] - The alpha value.
  23263. * @return {Color4} A reference to this object.
  23264. */
  23265. set( r, g, b, a = 1 ) {
  23266. this.a = a;
  23267. return super.set( r, g, b );
  23268. }
  23269. /**
  23270. * Overwrites the default to honor alpha.
  23271. *
  23272. * @param {Color4} color - The color to copy.
  23273. * @return {Color4} A reference to this object.
  23274. */
  23275. copy( color ) {
  23276. if ( color.a !== undefined ) this.a = color.a;
  23277. return super.copy( color );
  23278. }
  23279. /**
  23280. * Overwrites the default to honor alpha.
  23281. *
  23282. * @return {Color4} The cloned color.
  23283. */
  23284. clone() {
  23285. return new this.constructor( this.r, this.g, this.b, this.a );
  23286. }
  23287. }
  23288. /**
  23289. * Special version of {@link PropertyNode} which is used for parameters.
  23290. *
  23291. * @augments PropertyNode
  23292. */
  23293. class ParameterNode extends PropertyNode {
  23294. static get type() {
  23295. return 'ParameterNode';
  23296. }
  23297. /**
  23298. * Constructs a new parameter node.
  23299. *
  23300. * @param {string} nodeType - The type of the node.
  23301. * @param {?string} [name=null] - The name of the parameter in the shader.
  23302. */
  23303. constructor( nodeType, name = null ) {
  23304. super( nodeType, name );
  23305. /**
  23306. * This flag can be used for type testing.
  23307. *
  23308. * @type {boolean}
  23309. * @readonly
  23310. * @default true
  23311. */
  23312. this.isParameterNode = true;
  23313. }
  23314. /**
  23315. * Gets the type of a member variable in the parameter node.
  23316. *
  23317. * @param {NodeBuilder} builder - The node builder.
  23318. * @param {string} name - The name of the member variable.
  23319. * @returns {string}
  23320. */
  23321. getMemberType( builder, name ) {
  23322. const type = this.getNodeType( builder );
  23323. const struct = builder.getStructTypeNode( type );
  23324. let memberType;
  23325. if ( struct !== null ) {
  23326. memberType = struct.getMemberType( builder, name );
  23327. } else {
  23328. error( `TSL: Member "${ name }" not found in struct "${ type }".` );
  23329. memberType = 'float';
  23330. }
  23331. return memberType;
  23332. }
  23333. getHash() {
  23334. return this.uuid;
  23335. }
  23336. generate() {
  23337. return this.name;
  23338. }
  23339. }
  23340. /**
  23341. * TSL function for creating a parameter node.
  23342. *
  23343. * @tsl
  23344. * @function
  23345. * @param {string} type - The type of the node.
  23346. * @param {?string} name - The name of the parameter in the shader.
  23347. * @returns {ParameterNode}
  23348. */
  23349. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  23350. /**
  23351. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  23352. * They are usually needed in cases like `If`, `Else`.
  23353. *
  23354. * @augments Node
  23355. */
  23356. class StackNode extends Node {
  23357. static get type() {
  23358. return 'StackNode';
  23359. }
  23360. /**
  23361. * Constructs a new stack node.
  23362. *
  23363. * @param {?StackNode} [parent=null] - The parent stack node.
  23364. */
  23365. constructor( parent = null ) {
  23366. super();
  23367. /**
  23368. * List of nodes.
  23369. *
  23370. * @type {Array<Node>}
  23371. */
  23372. this.nodes = [];
  23373. /**
  23374. * The output node.
  23375. *
  23376. * @type {?Node}
  23377. * @default null
  23378. */
  23379. this.outputNode = null;
  23380. /**
  23381. * The parent stack node.
  23382. *
  23383. * @type {?StackNode}
  23384. * @default null
  23385. */
  23386. this.parent = parent;
  23387. /**
  23388. * The current conditional node.
  23389. *
  23390. * @private
  23391. * @type {ConditionalNode}
  23392. * @default null
  23393. */
  23394. this._currentCond = null;
  23395. /**
  23396. * The expression node. Only
  23397. * relevant for Switch/Case.
  23398. *
  23399. * @private
  23400. * @type {Node}
  23401. * @default null
  23402. */
  23403. this._expressionNode = null;
  23404. /**
  23405. * This flag can be used for type testing.
  23406. *
  23407. * @type {boolean}
  23408. * @readonly
  23409. * @default true
  23410. */
  23411. this.isStackNode = true;
  23412. }
  23413. getElementType( builder ) {
  23414. return this.hasOutput ? this.outputNode.getElementType( builder ) : 'void';
  23415. }
  23416. getNodeType( builder ) {
  23417. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  23418. }
  23419. getMemberType( builder, name ) {
  23420. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  23421. }
  23422. /**
  23423. * Adds a node to this stack.
  23424. *
  23425. * @param {Node} node - The node to add.
  23426. * @return {StackNode} A reference to this stack node.
  23427. */
  23428. addToStack( node ) {
  23429. if ( node.isNode !== true ) {
  23430. error( 'TSL: Invalid node added to stack.' );
  23431. return this;
  23432. }
  23433. this.nodes.push( node );
  23434. return this;
  23435. }
  23436. /**
  23437. * Represent an `if` statement in TSL.
  23438. *
  23439. * @param {Node} boolNode - Represents the condition.
  23440. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23441. * @return {StackNode} A reference to this stack node.
  23442. */
  23443. If( boolNode, method ) {
  23444. const methodNode = new ShaderNode( method );
  23445. this._currentCond = select( boolNode, methodNode );
  23446. return this.addToStack( this._currentCond );
  23447. }
  23448. /**
  23449. * Represent an `elseif` statement in TSL.
  23450. *
  23451. * @param {Node} boolNode - Represents the condition.
  23452. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23453. * @return {StackNode} A reference to this stack node.
  23454. */
  23455. ElseIf( boolNode, method ) {
  23456. const methodNode = new ShaderNode( method );
  23457. const ifNode = select( boolNode, methodNode );
  23458. this._currentCond.elseNode = ifNode;
  23459. this._currentCond = ifNode;
  23460. return this;
  23461. }
  23462. /**
  23463. * Represent an `else` statement in TSL.
  23464. *
  23465. * @param {Function} method - TSL code which is executed in the `else` case.
  23466. * @return {StackNode} A reference to this stack node.
  23467. */
  23468. Else( method ) {
  23469. this._currentCond.elseNode = new ShaderNode( method );
  23470. return this;
  23471. }
  23472. /**
  23473. * Represents a `switch` statement in TSL.
  23474. *
  23475. * @param {any} expression - Represents the expression.
  23476. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23477. * @return {StackNode} A reference to this stack node.
  23478. */
  23479. Switch( expression ) {
  23480. this._expressionNode = nodeObject( expression );
  23481. return this;
  23482. }
  23483. /**
  23484. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  23485. * The last parameter must be the callback method that should be executed in the `true` case.
  23486. *
  23487. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  23488. * @return {StackNode} A reference to this stack node.
  23489. */
  23490. Case( ...params ) {
  23491. const caseNodes = [];
  23492. // extract case nodes from the parameter list
  23493. if ( params.length >= 2 ) {
  23494. for ( let i = 0; i < params.length - 1; i ++ ) {
  23495. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  23496. }
  23497. } else {
  23498. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  23499. }
  23500. // extract method
  23501. const method = params[ params.length - 1 ];
  23502. const methodNode = new ShaderNode( method );
  23503. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  23504. let caseNode = caseNodes[ 0 ];
  23505. for ( let i = 1; i < caseNodes.length; i ++ ) {
  23506. caseNode = caseNode.or( caseNodes[ i ] );
  23507. }
  23508. // build condition
  23509. const condNode = select( caseNode, methodNode );
  23510. if ( this._currentCond === null ) {
  23511. this._currentCond = condNode;
  23512. return this.addToStack( this._currentCond );
  23513. } else {
  23514. this._currentCond.elseNode = condNode;
  23515. this._currentCond = condNode;
  23516. return this;
  23517. }
  23518. }
  23519. /**
  23520. * Represents the default code block of a Switch/Case statement.
  23521. *
  23522. * @param {Function} method - TSL code which is executed in the `else` case.
  23523. * @return {StackNode} A reference to this stack node.
  23524. */
  23525. Default( method ) {
  23526. this.Else( method );
  23527. return this;
  23528. }
  23529. setup( builder ) {
  23530. const nodeProperties = builder.getNodeProperties( this );
  23531. let index = 0;
  23532. for ( const childNode of this.getChildren() ) {
  23533. if ( childNode.isVarNode && childNode.intent === true ) {
  23534. if ( childNode.isAssign( builder ) !== true ) {
  23535. continue;
  23536. }
  23537. }
  23538. nodeProperties[ 'node' + index ++ ] = childNode;
  23539. }
  23540. // return a outputNode if exists or null
  23541. return nodeProperties.outputNode || null;
  23542. }
  23543. get hasOutput() {
  23544. return this.outputNode && this.outputNode.isNode;
  23545. }
  23546. build( builder, ...params ) {
  23547. const previousStack = getCurrentStack();
  23548. setCurrentStack( this );
  23549. builder.setActiveStack( this );
  23550. const buildStage = builder.buildStage;
  23551. for ( const node of this.nodes ) {
  23552. if ( node.isVarNode && node.intent === true ) {
  23553. if ( node.isAssign( builder ) !== true ) {
  23554. continue;
  23555. }
  23556. }
  23557. if ( buildStage === 'setup' ) {
  23558. node.build( builder );
  23559. } else if ( buildStage === 'analyze' ) {
  23560. node.build( builder, this );
  23561. } else if ( buildStage === 'generate' ) {
  23562. const stages = builder.getDataFromNode( node, 'any' ).stages;
  23563. const parents = stages && stages[ builder.shaderStage ];
  23564. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  23565. continue; // skip var nodes that are only used in .toVarying()
  23566. }
  23567. node.build( builder, 'void' );
  23568. }
  23569. }
  23570. //
  23571. let result;
  23572. if ( this.hasOutput ) {
  23573. result = this.outputNode.build( builder, ...params );
  23574. } else {
  23575. result = super.build( builder, ...params );
  23576. }
  23577. setCurrentStack( previousStack );
  23578. builder.removeActiveStack( this );
  23579. return result;
  23580. }
  23581. }
  23582. /**
  23583. * TSL function for creating a stack node.
  23584. *
  23585. * @tsl
  23586. * @function
  23587. * @param {?StackNode} [parent=null] - The parent stack node.
  23588. * @returns {StackNode}
  23589. */
  23590. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  23591. /**
  23592. * Generates a layout for struct members.
  23593. * This function takes an object representing struct members and returns an array of member layouts.
  23594. * Each member layout includes the member's name, type, and whether it is atomic.
  23595. *
  23596. * @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.
  23597. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  23598. */
  23599. function getMembersLayout( members ) {
  23600. return Object.entries( members ).map( ( [ name, value ] ) => {
  23601. if ( typeof value === 'string' ) {
  23602. return { name, type: value, atomic: false };
  23603. }
  23604. return { name, type: value.type, atomic: value.atomic || false };
  23605. } );
  23606. }
  23607. /**
  23608. * Represents a struct type node in the node-based system.
  23609. * This class is used to define and manage the layout and types of struct members.
  23610. * It extends the base Node class and provides methods to get the length of the struct,
  23611. * retrieve member types, and generate the struct type for a builder.
  23612. *
  23613. * @augments Node
  23614. */
  23615. class StructTypeNode extends Node {
  23616. static get type() {
  23617. return 'StructTypeNode';
  23618. }
  23619. /**
  23620. * Creates an instance of StructTypeNode.
  23621. *
  23622. * @param {Object} membersLayout - The layout of the members for the struct.
  23623. * @param {?string} [name=null] - The optional name of the struct.
  23624. */
  23625. constructor( membersLayout, name = null ) {
  23626. super( 'struct' );
  23627. /**
  23628. * The layout of the members for the struct
  23629. *
  23630. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  23631. */
  23632. this.membersLayout = getMembersLayout( membersLayout );
  23633. /**
  23634. * The name of the struct.
  23635. *
  23636. * @type {?string}
  23637. * @default null
  23638. */
  23639. this.name = name;
  23640. /**
  23641. * This flag can be used for type testing.
  23642. *
  23643. * @type {boolean}
  23644. * @readonly
  23645. * @default true
  23646. */
  23647. this.isStructLayoutNode = true;
  23648. }
  23649. /**
  23650. * Returns the length of the struct.
  23651. * The length is calculated by summing the lengths of the struct's members.
  23652. *
  23653. * @returns {number} The length of the struct.
  23654. */
  23655. getLength() {
  23656. const GPU_CHUNK_BYTES = 8;
  23657. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  23658. let offset = 0; // global buffer offset in bytes
  23659. for ( const member of this.membersLayout ) {
  23660. const type = member.type;
  23661. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  23662. const boundary = getByteBoundaryFromType( type );
  23663. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  23664. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  23665. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  23666. offset += chunkPadding;
  23667. // Check for chunk overflow
  23668. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  23669. // Add padding to the end of the chunk
  23670. offset += ( GPU_CHUNK_BYTES - chunkStart );
  23671. }
  23672. offset += itemSize;
  23673. }
  23674. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  23675. }
  23676. getMemberType( builder, name ) {
  23677. const member = this.membersLayout.find( m => m.name === name );
  23678. return member ? member.type : 'void';
  23679. }
  23680. getNodeType( builder ) {
  23681. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23682. return structType.name;
  23683. }
  23684. setup( builder ) {
  23685. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23686. builder.addInclude( this );
  23687. }
  23688. generate( builder ) {
  23689. return this.getNodeType( builder );
  23690. }
  23691. }
  23692. /**
  23693. * StructNode allows to create custom structures with multiple members.
  23694. * This can also be used to define structures in attribute and uniform data.
  23695. *
  23696. * ```js
  23697. * // Define a custom struct
  23698. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  23699. *
  23700. * // Create a new instance of the struct
  23701. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  23702. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  23703. *
  23704. * // Access the struct members
  23705. * const min = bb.get( 'min' );
  23706. *
  23707. * // Assign a new value to a member
  23708. * min.assign( vec3() );
  23709. * ```
  23710. * @augments Node
  23711. */
  23712. class StructNode extends Node {
  23713. static get type() {
  23714. return 'StructNode';
  23715. }
  23716. constructor( structTypeNode, values ) {
  23717. super( 'vec3' );
  23718. this.structTypeNode = structTypeNode;
  23719. this.values = values;
  23720. this.isStructNode = true;
  23721. }
  23722. getNodeType( builder ) {
  23723. return this.structTypeNode.getNodeType( builder );
  23724. }
  23725. getMemberType( builder, name ) {
  23726. return this.structTypeNode.getMemberType( builder, name );
  23727. }
  23728. generate( builder ) {
  23729. const nodeVar = builder.getVarFromNode( this );
  23730. const structType = nodeVar.type;
  23731. const propertyName = builder.getPropertyName( nodeVar );
  23732. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  23733. return nodeVar.name;
  23734. }
  23735. }
  23736. /**
  23737. * TSL function for creating a struct node.
  23738. *
  23739. * @tsl
  23740. * @function
  23741. * @param {Object} membersLayout - The layout of the struct members.
  23742. * @param {?string} [name=null] - The name of the struct.
  23743. * @returns {Function} The struct function.
  23744. */
  23745. const struct = ( membersLayout, name = null ) => {
  23746. const structLayout = new StructTypeNode( membersLayout, name );
  23747. const struct = ( ...params ) => {
  23748. let values = null;
  23749. if ( params.length > 0 ) {
  23750. if ( params[ 0 ].isNode ) {
  23751. values = {};
  23752. const names = Object.keys( membersLayout );
  23753. for ( let i = 0; i < params.length; i ++ ) {
  23754. values[ names[ i ] ] = params[ i ];
  23755. }
  23756. } else {
  23757. values = params[ 0 ];
  23758. }
  23759. }
  23760. return nodeObject( new StructNode( structLayout, values ) );
  23761. };
  23762. struct.layout = structLayout;
  23763. struct.isStruct = true;
  23764. return struct;
  23765. };
  23766. /**
  23767. * This node can be used to define multiple outputs in a shader programs.
  23768. *
  23769. * @augments Node
  23770. */
  23771. class OutputStructNode extends Node {
  23772. static get type() {
  23773. return 'OutputStructNode';
  23774. }
  23775. /**
  23776. * Constructs a new output struct node. The constructor can be invoked with an
  23777. * arbitrary number of nodes representing the members.
  23778. *
  23779. * @param {...Node} members - A parameter list of nodes.
  23780. */
  23781. constructor( ...members ) {
  23782. super();
  23783. /**
  23784. * An array of nodes which defines the output.
  23785. *
  23786. * @type {Array<Node>}
  23787. */
  23788. this.members = members;
  23789. /**
  23790. * This flag can be used for type testing.
  23791. *
  23792. * @type {boolean}
  23793. * @readonly
  23794. * @default true
  23795. */
  23796. this.isOutputStructNode = true;
  23797. }
  23798. getNodeType( builder ) {
  23799. const properties = builder.getNodeProperties( this );
  23800. if ( properties.membersLayout === undefined ) {
  23801. const members = this.members;
  23802. const membersLayout = [];
  23803. for ( let i = 0; i < members.length; i ++ ) {
  23804. const name = 'm' + i;
  23805. const type = members[ i ].getNodeType( builder );
  23806. membersLayout.push( { name, type, index: i } );
  23807. }
  23808. properties.membersLayout = membersLayout;
  23809. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  23810. }
  23811. return properties.structType.name;
  23812. }
  23813. generate( builder ) {
  23814. const propertyName = builder.getOutputStructName();
  23815. const members = this.members;
  23816. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  23817. for ( let i = 0; i < members.length; i ++ ) {
  23818. const snippet = members[ i ].build( builder );
  23819. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  23820. }
  23821. return propertyName;
  23822. }
  23823. }
  23824. /**
  23825. * TSL function for creating an output struct node.
  23826. *
  23827. * @tsl
  23828. * @function
  23829. * @param {...Node} members - A parameter list of nodes.
  23830. * @returns {OutputStructNode}
  23831. */
  23832. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  23833. /**
  23834. * Returns the MRT texture index for the given name.
  23835. *
  23836. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  23837. * @param {string} name - The name of the MRT texture which index is requested.
  23838. * @return {number} The texture index.
  23839. */
  23840. function getTextureIndex( textures, name ) {
  23841. for ( let i = 0; i < textures.length; i ++ ) {
  23842. if ( textures[ i ].name === name ) {
  23843. return i;
  23844. }
  23845. }
  23846. return -1;
  23847. }
  23848. /**
  23849. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  23850. * post-processing is shown below:
  23851. * ```js
  23852. * const mrtNode = mrt( {
  23853. * output: output,
  23854. * normal: normalView
  23855. * } ) );
  23856. * ```
  23857. * The MRT output is defined as a dictionary.
  23858. *
  23859. * @augments OutputStructNode
  23860. */
  23861. class MRTNode extends OutputStructNode {
  23862. static get type() {
  23863. return 'MRTNode';
  23864. }
  23865. /**
  23866. * Constructs a new output struct node.
  23867. *
  23868. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23869. */
  23870. constructor( outputNodes ) {
  23871. super();
  23872. /**
  23873. * A dictionary representing the MRT outputs. The key
  23874. * is the name of the output, the value the node which produces
  23875. * the output result.
  23876. *
  23877. * @type {Object<string, Node>}
  23878. */
  23879. this.outputNodes = outputNodes;
  23880. /**
  23881. * This flag can be used for type testing.
  23882. *
  23883. * @type {boolean}
  23884. * @readonly
  23885. * @default true
  23886. */
  23887. this.isMRTNode = true;
  23888. }
  23889. /**
  23890. * Returns `true` if the MRT node has an output with the given name.
  23891. *
  23892. * @param {string} name - The name of the output.
  23893. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  23894. */
  23895. has( name ) {
  23896. return this.outputNodes[ name ] !== undefined;
  23897. }
  23898. /**
  23899. * Returns the output node for the given name.
  23900. *
  23901. * @param {string} name - The name of the output.
  23902. * @return {Node} The output node.
  23903. */
  23904. get( name ) {
  23905. return this.outputNodes[ name ];
  23906. }
  23907. /**
  23908. * Merges the outputs of the given MRT node with the outputs of this node.
  23909. *
  23910. * @param {MRTNode} mrtNode - The MRT to merge.
  23911. * @return {MRTNode} A new MRT node with merged outputs..
  23912. */
  23913. merge( mrtNode ) {
  23914. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  23915. return mrt( outputs );
  23916. }
  23917. setup( builder ) {
  23918. const outputNodes = this.outputNodes;
  23919. const mrt = builder.renderer.getRenderTarget();
  23920. const members = [];
  23921. const textures = mrt.textures;
  23922. for ( const name in outputNodes ) {
  23923. const index = getTextureIndex( textures, name );
  23924. members[ index ] = vec4( outputNodes[ name ] );
  23925. }
  23926. this.members = members;
  23927. return super.setup( builder );
  23928. }
  23929. }
  23930. /**
  23931. * TSL function for creating a MRT node.
  23932. *
  23933. * @tsl
  23934. * @function
  23935. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23936. * @returns {MRTNode}
  23937. */
  23938. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  23939. /**
  23940. * This node represents an operation that reinterprets the bit representation of a value
  23941. * in one type as a value in another type.
  23942. *
  23943. * @augments TempNode
  23944. */
  23945. class BitcastNode extends TempNode {
  23946. static get type() {
  23947. return 'BitcastNode';
  23948. }
  23949. /**
  23950. * Constructs a new bitcast node.
  23951. *
  23952. * @param {Node} valueNode - The value to convert.
  23953. * @param {string} conversionType - The type to convert to.
  23954. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  23955. */
  23956. constructor( valueNode, conversionType, inputType = null ) {
  23957. super();
  23958. /**
  23959. * The data to bitcast to a new type.
  23960. *
  23961. * @type {Node}
  23962. */
  23963. this.valueNode = valueNode;
  23964. /**
  23965. * The type the value will be converted to.
  23966. *
  23967. * @type {string}
  23968. */
  23969. this.conversionType = conversionType;
  23970. /**
  23971. * The expected input data type of the bitcast operation.
  23972. *
  23973. *
  23974. * @type {string}
  23975. * @default null
  23976. */
  23977. this.inputType = inputType;
  23978. /**
  23979. * This flag can be used for type testing.
  23980. *
  23981. * @type {boolean}
  23982. * @readonly
  23983. * @default true
  23984. */
  23985. this.isBitcastNode = true;
  23986. }
  23987. getNodeType( builder ) {
  23988. // GLSL aliasing
  23989. if ( this.inputType !== null ) {
  23990. const valueType = this.valueNode.getNodeType( builder );
  23991. const valueLength = builder.getTypeLength( valueType );
  23992. return builder.getTypeFromLength( valueLength, this.conversionType );
  23993. }
  23994. return this.conversionType;
  23995. }
  23996. generate( builder ) {
  23997. const type = this.getNodeType( builder );
  23998. let inputType = '';
  23999. if ( this.inputType !== null ) {
  24000. const valueType = this.valueNode.getNodeType( builder );
  24001. const valueTypeLength = builder.getTypeLength( valueType );
  24002. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  24003. } else {
  24004. inputType = this.valueNode.getNodeType( builder );
  24005. }
  24006. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  24007. }
  24008. }
  24009. /**
  24010. * Reinterpret the bit representation of a value in one type as a value in another type.
  24011. *
  24012. * @tsl
  24013. * @function
  24014. * @param {Node | number} x - The parameter.
  24015. * @param {string} y - The new type.
  24016. * @returns {Node}
  24017. */
  24018. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  24019. /**
  24020. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  24021. *
  24022. * @tsl
  24023. * @function
  24024. * @param {Node<float>} value - The float or vector of floats to bitcast.
  24025. * @returns {BitcastNode}
  24026. */
  24027. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  24028. /**
  24029. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  24030. *
  24031. * @tsl
  24032. * @function
  24033. * @param {Node<float>} value - The float or vector of floats to bitcast.
  24034. * @returns {BitcastNode}
  24035. */
  24036. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  24037. /**
  24038. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  24039. *
  24040. * @tsl
  24041. * @function
  24042. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  24043. * @returns {BitcastNode}
  24044. */
  24045. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  24046. /**
  24047. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  24048. *
  24049. * @tsl
  24050. * @function
  24051. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  24052. * @returns {BitcastNode}
  24053. */
  24054. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  24055. const registeredBitcountFunctions = {};
  24056. /**
  24057. * This node represents an operation that counts the bits of a piece of shader data.
  24058. *
  24059. * @augments MathNode
  24060. */
  24061. class BitcountNode extends MathNode {
  24062. static get type() {
  24063. return 'BitcountNode';
  24064. }
  24065. /**
  24066. * Constructs a new math node.
  24067. *
  24068. * @param {'countTrailingZeros'|'countLeadingZeros'|'countOneBits'} method - The method name.
  24069. * @param {Node} aNode - The first input.
  24070. */
  24071. constructor( method, aNode ) {
  24072. super( method, aNode );
  24073. /**
  24074. * This flag can be used for type testing.
  24075. *
  24076. * @type {boolean}
  24077. * @readonly
  24078. * @default true
  24079. */
  24080. this.isBitcountNode = true;
  24081. }
  24082. /**
  24083. * Casts the input value of the function to an integer if necessary.
  24084. *
  24085. * @private
  24086. * @param {Node<uint>|Node<int>} inputNode - The input value.
  24087. * @param {Node<uint>} outputNode - The output value.
  24088. * @param {string} elementType - The type of the input value.
  24089. */
  24090. _resolveElementType( inputNode, outputNode, elementType ) {
  24091. if ( elementType === 'int' ) {
  24092. outputNode.assign( bitcast( inputNode, 'uint' ) );
  24093. } else {
  24094. outputNode.assign( inputNode );
  24095. }
  24096. }
  24097. _returnDataNode( inputType ) {
  24098. switch ( inputType ) {
  24099. case 'uint': {
  24100. return uint;
  24101. }
  24102. case 'int': {
  24103. return int;
  24104. }
  24105. case 'uvec2': {
  24106. return uvec2;
  24107. }
  24108. case 'uvec3': {
  24109. return uvec3;
  24110. }
  24111. case 'uvec4': {
  24112. return uvec4;
  24113. }
  24114. case 'ivec2': {
  24115. return ivec2;
  24116. }
  24117. case 'ivec3': {
  24118. return ivec3;
  24119. }
  24120. case 'ivec4': {
  24121. return ivec4;
  24122. }
  24123. }
  24124. }
  24125. /**
  24126. * Creates and registers a reusable GLSL function that emulates the behavior of countTrailingZeros.
  24127. *
  24128. * @private
  24129. * @param {string} method - The name of the function to create.
  24130. * @param {string} elementType - The type of the input value.
  24131. * @returns {Function} - The generated function
  24132. */
  24133. _createTrailingZerosBaseLayout( method, elementType ) {
  24134. const outputConvertNode = this._returnDataNode( elementType );
  24135. const fnDef = Fn( ( [ value ] ) => {
  24136. const v = uint( 0.0 );
  24137. this._resolveElementType( value, v, elementType );
  24138. const f = float( v.bitAnd( negate( v ) ) );
  24139. const uintBits = floatBitsToUint( f );
  24140. const numTrailingZeros = ( uintBits.shiftRight( 23 ) ).sub( 127 );
  24141. return outputConvertNode( numTrailingZeros );
  24142. } ).setLayout( {
  24143. name: method,
  24144. type: elementType,
  24145. inputs: [
  24146. { name: 'value', type: elementType }
  24147. ]
  24148. } );
  24149. return fnDef;
  24150. }
  24151. /**
  24152. * Creates and registers a reusable GLSL function that emulates the behavior of countLeadingZeros.
  24153. *
  24154. * @private
  24155. * @param {string} method - The name of the function to create.
  24156. * @param {string} elementType - The type of the input value.
  24157. * @returns {Function} - The generated function
  24158. */
  24159. _createLeadingZerosBaseLayout( method, elementType ) {
  24160. const outputConvertNode = this._returnDataNode( elementType );
  24161. const fnDef = Fn( ( [ value ] ) => {
  24162. If( value.equal( uint( 0 ) ), () => {
  24163. return uint( 32 );
  24164. } );
  24165. const v = uint( 0 );
  24166. const n = uint( 0 );
  24167. this._resolveElementType( value, v, elementType );
  24168. If( v.shiftRight( 16 ).equal( 0 ), () => {
  24169. n.addAssign( 16 );
  24170. v.shiftLeftAssign( 16 );
  24171. } );
  24172. If( v.shiftRight( 24 ).equal( 0 ), () => {
  24173. n.addAssign( 8 );
  24174. v.shiftLeftAssign( 8 );
  24175. } );
  24176. If( v.shiftRight( 28 ).equal( 0 ), () => {
  24177. n.addAssign( 4 );
  24178. v.shiftLeftAssign( 4 );
  24179. } );
  24180. If( v.shiftRight( 30 ).equal( 0 ), () => {
  24181. n.addAssign( 2 );
  24182. v.shiftLeftAssign( 2 );
  24183. } );
  24184. If( v.shiftRight( 31 ).equal( 0 ), () => {
  24185. n.addAssign( 1 );
  24186. } );
  24187. return outputConvertNode( n );
  24188. } ).setLayout( {
  24189. name: method,
  24190. type: elementType,
  24191. inputs: [
  24192. { name: 'value', type: elementType }
  24193. ]
  24194. } );
  24195. return fnDef;
  24196. }
  24197. /**
  24198. * Creates and registers a reusable GLSL function that emulates the behavior of countOneBits.
  24199. *
  24200. * @private
  24201. * @param {string} method - The name of the function to create.
  24202. * @param {string} elementType - The type of the input value.
  24203. * @returns {Function} - The generated function
  24204. */
  24205. _createOneBitsBaseLayout( method, elementType ) {
  24206. const outputConvertNode = this._returnDataNode( elementType );
  24207. const fnDef = Fn( ( [ value ] ) => {
  24208. const v = uint( 0.0 );
  24209. this._resolveElementType( value, v, elementType );
  24210. v.assign( v.sub( v.shiftRight( uint( 1 ) ).bitAnd( uint( 0x55555555 ) ) ) );
  24211. v.assign( v.bitAnd( uint( 0x33333333 ) ).add( v.shiftRight( uint( 2 ) ).bitAnd( uint( 0x33333333 ) ) ) );
  24212. const numBits = v.add( v.shiftRight( uint( 4 ) ) ).bitAnd( uint( 0xF0F0F0F ) ).mul( uint( 0x1010101 ) ).shiftRight( uint( 24 ) );
  24213. return outputConvertNode( numBits );
  24214. } ).setLayout( {
  24215. name: method,
  24216. type: elementType,
  24217. inputs: [
  24218. { name: 'value', type: elementType }
  24219. ]
  24220. } );
  24221. return fnDef;
  24222. }
  24223. /**
  24224. * Creates and registers a reusable GLSL function that emulates the behavior of the specified bitcount function.
  24225. * including considerations for component-wise bitcounts on vector type inputs.
  24226. *
  24227. * @private
  24228. * @param {string} method - The name of the function to create.
  24229. * @param {string} inputType - The type of the input value.
  24230. * @param {number} typeLength - The vec length of the input value.
  24231. * @param {Function} baseFn - The base function that operates on an individual component of the vector.
  24232. * @returns {Function} - The alias function for the specified bitcount method.
  24233. */
  24234. _createMainLayout( method, inputType, typeLength, baseFn ) {
  24235. const outputConvertNode = this._returnDataNode( inputType );
  24236. const fnDef = Fn( ( [ value ] ) => {
  24237. if ( typeLength === 1 ) {
  24238. return outputConvertNode( baseFn( value ) );
  24239. } else {
  24240. const vec = outputConvertNode( 0 );
  24241. const components = [ 'x', 'y', 'z', 'w' ];
  24242. for ( let i = 0; i < typeLength; i ++ ) {
  24243. const component = components[ i ];
  24244. vec[ component ].assign( baseFn( value[ component ] ) );
  24245. }
  24246. return vec;
  24247. }
  24248. } ).setLayout( {
  24249. name: method,
  24250. type: inputType,
  24251. inputs: [
  24252. { name: 'value', type: inputType }
  24253. ]
  24254. } );
  24255. return fnDef;
  24256. }
  24257. setup( builder ) {
  24258. const { method, aNode } = this;
  24259. const { renderer } = builder;
  24260. if ( renderer.backend.isWebGPUBackend ) {
  24261. // use built-in WGSL functions for WebGPU
  24262. return super.setup( builder );
  24263. }
  24264. const inputType = this.getInputType( builder );
  24265. const elementType = builder.getElementType( inputType );
  24266. const typeLength = builder.getTypeLength( inputType );
  24267. const baseMethod = `${method}_base_${elementType}`;
  24268. const newMethod = `${method}_${inputType}`;
  24269. let baseFn = registeredBitcountFunctions[ baseMethod ];
  24270. if ( baseFn === undefined ) {
  24271. switch ( method ) {
  24272. case BitcountNode.COUNT_LEADING_ZEROS: {
  24273. baseFn = this._createLeadingZerosBaseLayout( baseMethod, elementType );
  24274. break;
  24275. }
  24276. case BitcountNode.COUNT_TRAILING_ZEROS: {
  24277. baseFn = this._createTrailingZerosBaseLayout( baseMethod, elementType );
  24278. break;
  24279. }
  24280. case BitcountNode.COUNT_ONE_BITS: {
  24281. baseFn = this._createOneBitsBaseLayout( baseMethod, elementType );
  24282. break;
  24283. }
  24284. }
  24285. registeredBitcountFunctions[ baseMethod ] = baseFn;
  24286. }
  24287. let fn = registeredBitcountFunctions[ newMethod ];
  24288. if ( fn === undefined ) {
  24289. fn = this._createMainLayout( newMethod, inputType, typeLength, baseFn );
  24290. registeredBitcountFunctions[ newMethod ] = fn;
  24291. }
  24292. const output = Fn( () => {
  24293. return fn(
  24294. aNode,
  24295. );
  24296. } );
  24297. return output();
  24298. }
  24299. }
  24300. BitcountNode.COUNT_TRAILING_ZEROS = 'countTrailingZeros';
  24301. BitcountNode.COUNT_LEADING_ZEROS = 'countLeadingZeros';
  24302. BitcountNode.COUNT_ONE_BITS = 'countOneBits';
  24303. /**
  24304. * Finds the number of consecutive 0 bits from the least significant bit of the input value,
  24305. * which is also the index of the least significant bit of the input value.
  24306. *
  24307. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24308. *
  24309. * @tsl
  24310. * @function
  24311. * @param {Node | number} x - The input value.
  24312. * @returns {Node}
  24313. */
  24314. const countTrailingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_TRAILING_ZEROS ).setParameterLength( 1 );
  24315. /**
  24316. * Finds the number of consecutive 0 bits starting from the most significant bit of the input value.
  24317. *
  24318. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24319. *
  24320. * @tsl
  24321. * @function
  24322. * @param {Node | number} x - The input value.
  24323. * @returns {Node}
  24324. */
  24325. const countLeadingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_LEADING_ZEROS ).setParameterLength( 1 );
  24326. /**
  24327. * Finds the number of '1' bits set in the input value
  24328. *
  24329. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24330. *
  24331. * @tsl
  24332. * @function
  24333. * @returns {Node}
  24334. */
  24335. const countOneBits = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_ONE_BITS ).setParameterLength( 1 );
  24336. /**
  24337. * Generates a hash value in the range `[0, 1]` from the given seed.
  24338. *
  24339. * @tsl
  24340. * @function
  24341. * @param {Node<float>} seed - The seed.
  24342. * @return {Node<float>} The hash value.
  24343. */
  24344. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  24345. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  24346. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  24347. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  24348. const result = word.shiftRight( 22 ).bitXor( word );
  24349. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  24350. } );
  24351. /**
  24352. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24353. * The corners are mapped to `0` and the center to `1`.
  24354. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24355. *
  24356. * @tsl
  24357. * @function
  24358. * @param {Node<float>} x - The value to remap.
  24359. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  24360. * @return {Node<float>} The remapped value.
  24361. */
  24362. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  24363. /**
  24364. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24365. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  24366. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24367. *
  24368. * @tsl
  24369. * @function
  24370. * @param {Node<float>} x - The value to remap.
  24371. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  24372. * @return {Node<float>} The remapped value.
  24373. */
  24374. 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 ) );
  24375. /**
  24376. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24377. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  24378. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24379. *
  24380. * @tsl
  24381. * @function
  24382. * @param {Node<float>} x - The value to remap.
  24383. * @param {Node<float>} a - First control parameter.
  24384. * @param {Node<float>} b - Second control parameter.
  24385. * @return {Node<float>} The remapped value.
  24386. */
  24387. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  24388. /**
  24389. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  24390. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24391. *
  24392. * @tsl
  24393. * @function
  24394. * @param {Node<float>} x - The value to compute the sin for.
  24395. * @param {Node<float>} k - Controls the amount of bounces.
  24396. * @return {Node<float>} The result value.
  24397. */
  24398. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  24399. /**
  24400. * This node represents an operation that packs floating-point values of a vector into an unsigned 32-bit integer
  24401. *
  24402. * @augments TempNode
  24403. */
  24404. class PackFloatNode extends TempNode {
  24405. static get type() {
  24406. return 'PackFloatNode';
  24407. }
  24408. /**
  24409. *
  24410. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  24411. * @param {Node} vectorNode - The vector node to be packed
  24412. */
  24413. constructor( encoding, vectorNode ) {
  24414. super();
  24415. /**
  24416. * The vector to be packed.
  24417. *
  24418. * @type {Node}
  24419. */
  24420. this.vectorNode = vectorNode;
  24421. /**
  24422. * The numeric encoding.
  24423. *
  24424. * @type {string}
  24425. */
  24426. this.encoding = encoding;
  24427. /**
  24428. * This flag can be used for type testing.
  24429. *
  24430. * @type {boolean}
  24431. * @readonly
  24432. * @default true
  24433. */
  24434. this.isPackFloatNode = true;
  24435. }
  24436. getNodeType() {
  24437. return 'uint';
  24438. }
  24439. generate( builder ) {
  24440. const inputType = this.vectorNode.getNodeType( builder );
  24441. return `${ builder.getFloatPackingMethod( this.encoding ) }(${ this.vectorNode.build( builder, inputType )})`;
  24442. }
  24443. }
  24444. /**
  24445. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  24446. * round(clamp(c, -1, +1) * 32767.0)
  24447. *
  24448. * @tsl
  24449. * @function
  24450. * @param {Node<vec2>} value - The 2-component vector to be packed
  24451. * @returns {Node}
  24452. */
  24453. const packSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'snorm' ).setParameterLength( 1 );
  24454. /**
  24455. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  24456. * round(clamp(c, 0, +1) * 65535.0)
  24457. *
  24458. * @tsl
  24459. * @function
  24460. * @param {Node<vec2>} value - The 2-component vector to be packed
  24461. * @returns {Node}
  24462. */
  24463. const packUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'unorm' ).setParameterLength( 1 );
  24464. /**
  24465. * Converts each component of the vec2 to 16-bit floating-point values. The results are packed into a single unsigned integer.
  24466. *
  24467. * @tsl
  24468. * @function
  24469. * @param {Node<vec2>} value - The 2-component vector to be packed
  24470. * @returns {Node}
  24471. */
  24472. const packHalf2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'float16' ).setParameterLength( 1 );
  24473. /**
  24474. * This node represents an operation that unpacks values from a 32-bit unsigned integer, reinterpreting the results as a floating-point vector
  24475. *
  24476. * @augments TempNode
  24477. */
  24478. class UnpackFloatNode extends TempNode {
  24479. static get type() {
  24480. return 'UnpackFloatNode';
  24481. }
  24482. /**
  24483. *
  24484. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the integer values are mapped to the float range
  24485. * @param {Node} uintNode - The uint node to be unpacked
  24486. */
  24487. constructor( encoding, uintNode ) {
  24488. super();
  24489. /**
  24490. * The unsigned integer to be unpacked.
  24491. *
  24492. * @type {Node}
  24493. */
  24494. this.uintNode = uintNode;
  24495. /**
  24496. * The numeric encoding.
  24497. *
  24498. * @type {string}
  24499. */
  24500. this.encoding = encoding;
  24501. /**
  24502. * This flag can be used for type testing.
  24503. *
  24504. * @type {boolean}
  24505. * @readonly
  24506. * @default true
  24507. */
  24508. this.isUnpackFloatNode = true;
  24509. }
  24510. getNodeType() {
  24511. return 'vec2';
  24512. }
  24513. generate( builder ) {
  24514. const inputType = this.uintNode.getNodeType( builder );
  24515. return `${ builder.getFloatUnpackingMethod( this.encoding ) }(${ this.uintNode.build( builder, inputType )})`;
  24516. }
  24517. }
  24518. /**
  24519. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized signed integers. Returns a vec2 with both values.
  24520. *
  24521. * @tsl
  24522. * @function
  24523. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24524. * @returns {Node}
  24525. */
  24526. const unpackSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'snorm' ).setParameterLength( 1 );
  24527. /**
  24528. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized unsigned integers. Returns a vec2 with both values.
  24529. *
  24530. * @tsl
  24531. * @function
  24532. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24533. * @returns {Node}
  24534. */
  24535. const unpackUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'unorm' ).setParameterLength( 1 );
  24536. /**
  24537. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as 16-bit floating-point numbers. Returns a vec2 with both values.
  24538. *
  24539. * @tsl
  24540. * @function
  24541. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24542. * @returns {Node}
  24543. */
  24544. const unpackHalf2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'float16' ).setParameterLength( 1 );
  24545. // https://github.com/cabbibo/glsl-tri-noise-3d
  24546. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  24547. return x.fract().sub( .5 ).abs();
  24548. } ).setLayout( {
  24549. name: 'tri',
  24550. type: 'float',
  24551. inputs: [
  24552. { name: 'x', type: 'float' }
  24553. ]
  24554. } );
  24555. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  24556. 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. ) ) ) ) );
  24557. } ).setLayout( {
  24558. name: 'tri3',
  24559. type: 'vec3',
  24560. inputs: [
  24561. { name: 'p', type: 'vec3' }
  24562. ]
  24563. } );
  24564. /**
  24565. * Generates a noise value from the given position, speed and time parameters.
  24566. *
  24567. * @tsl
  24568. * @function
  24569. * @param {Node<vec3>} position - The position.
  24570. * @param {Node<float>} speed - The speed.
  24571. * @param {Node<float>} time - The time.
  24572. * @return {Node<float>} The generated noise.
  24573. */
  24574. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  24575. const p = vec3( position ).toVar();
  24576. const z = float( 1.4 ).toVar();
  24577. const rz = float( 0.0 ).toVar();
  24578. const bp = vec3( p ).toVar();
  24579. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  24580. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  24581. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  24582. bp.mulAssign( 1.8 );
  24583. z.mulAssign( 1.5 );
  24584. p.mulAssign( 1.2 );
  24585. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  24586. rz.addAssign( t.div( z ) );
  24587. bp.addAssign( 0.14 );
  24588. } );
  24589. return rz;
  24590. } ).setLayout( {
  24591. name: 'triNoise3D',
  24592. type: 'float',
  24593. inputs: [
  24594. { name: 'position', type: 'vec3' },
  24595. { name: 'speed', type: 'float' },
  24596. { name: 'time', type: 'float' }
  24597. ]
  24598. } );
  24599. /**
  24600. * This class allows to define multiple overloaded versions
  24601. * of the same function. Depending on the parameters of the function
  24602. * call, the node picks the best-fit overloaded version.
  24603. *
  24604. * @augments Node
  24605. */
  24606. class FunctionOverloadingNode extends Node {
  24607. static get type() {
  24608. return 'FunctionOverloadingNode';
  24609. }
  24610. /**
  24611. * Constructs a new function overloading node.
  24612. *
  24613. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  24614. * @param {...Node} parametersNodes - A list of parameter nodes.
  24615. */
  24616. constructor( functionNodes = [], ...parametersNodes ) {
  24617. super();
  24618. /**
  24619. * Array of `Fn` function definitions.
  24620. *
  24621. * @type {Array<Function>}
  24622. */
  24623. this.functionNodes = functionNodes;
  24624. /**
  24625. * A list of parameter nodes.
  24626. *
  24627. * @type {Array<Node>}
  24628. */
  24629. this.parametersNodes = parametersNodes;
  24630. /**
  24631. * The selected overloaded function call.
  24632. *
  24633. * @private
  24634. * @type {ShaderCallNodeInternal}
  24635. */
  24636. this._candidateFn = null;
  24637. /**
  24638. * This node is marked as global.
  24639. *
  24640. * @type {boolean}
  24641. * @default true
  24642. */
  24643. this.global = true;
  24644. }
  24645. /**
  24646. * This method is overwritten since the node type is inferred from
  24647. * the function's return type.
  24648. *
  24649. * @param {NodeBuilder} builder - The current node builder.
  24650. * @return {string} The node type.
  24651. */
  24652. getNodeType( builder ) {
  24653. const candidateFn = this.getCandidateFn( builder );
  24654. return candidateFn.shaderNode.layout.type;
  24655. }
  24656. /**
  24657. * Returns the candidate function for the current parameters.
  24658. *
  24659. * @param {NodeBuilder} builder - The current node builder.
  24660. * @return {FunctionNode} The candidate function.
  24661. */
  24662. getCandidateFn( builder ) {
  24663. const params = this.parametersNodes;
  24664. let candidateFn = this._candidateFn;
  24665. if ( candidateFn === null ) {
  24666. let bestCandidateFn = null;
  24667. let bestScore = -1;
  24668. for ( const functionNode of this.functionNodes ) {
  24669. const shaderNode = functionNode.shaderNode;
  24670. const layout = shaderNode.layout;
  24671. if ( layout === null ) {
  24672. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  24673. }
  24674. const inputs = layout.inputs;
  24675. if ( params.length === inputs.length ) {
  24676. let currentScore = 0;
  24677. for ( let i = 0; i < params.length; i ++ ) {
  24678. const param = params[ i ];
  24679. const input = inputs[ i ];
  24680. if ( param.getNodeType( builder ) === input.type ) {
  24681. currentScore ++;
  24682. }
  24683. }
  24684. if ( currentScore > bestScore ) {
  24685. bestCandidateFn = functionNode;
  24686. bestScore = currentScore;
  24687. }
  24688. }
  24689. }
  24690. this._candidateFn = candidateFn = bestCandidateFn;
  24691. }
  24692. return candidateFn;
  24693. }
  24694. /**
  24695. * Sets up the node for the current parameters.
  24696. *
  24697. * @param {NodeBuilder} builder - The current node builder.
  24698. * @return {Node} The setup node.
  24699. */
  24700. setup( builder ) {
  24701. const candidateFn = this.getCandidateFn( builder );
  24702. return candidateFn( ...this.parametersNodes );
  24703. }
  24704. }
  24705. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  24706. /**
  24707. * TSL function for creating a function overloading node.
  24708. *
  24709. * @tsl
  24710. * @function
  24711. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  24712. * @returns {FunctionOverloadingNode}
  24713. */
  24714. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  24715. /**
  24716. * Represents the elapsed time in seconds.
  24717. *
  24718. * @tsl
  24719. * @type {UniformNode<float>}
  24720. */
  24721. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  24722. /**
  24723. * Represents the delta time in seconds.
  24724. *
  24725. * @tsl
  24726. * @type {UniformNode<float>}
  24727. */
  24728. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  24729. /**
  24730. * Represents the current frame ID.
  24731. *
  24732. * @tsl
  24733. * @type {UniformNode<uint>}
  24734. */
  24735. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  24736. /**
  24737. * Generates a sine wave oscillation based on a timer.
  24738. *
  24739. * @tsl
  24740. * @function
  24741. * @param {Node<float>} t - The timer to generate the oscillation with.
  24742. * @return {Node<float>} The oscillation node.
  24743. */
  24744. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  24745. /**
  24746. * Generates a square wave oscillation based on a timer.
  24747. *
  24748. * @tsl
  24749. * @function
  24750. * @param {Node<float>} t - The timer to generate the oscillation with.
  24751. * @return {Node<float>} The oscillation node.
  24752. */
  24753. const oscSquare = ( t = time ) => t.fract().round();
  24754. /**
  24755. * Generates a triangle wave oscillation based on a timer.
  24756. *
  24757. * @tsl
  24758. * @function
  24759. * @param {Node<float>} t - The timer to generate the oscillation with.
  24760. * @return {Node<float>} The oscillation node.
  24761. */
  24762. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  24763. /**
  24764. * Generates a sawtooth wave oscillation based on a timer.
  24765. *
  24766. * @tsl
  24767. * @function
  24768. * @param {Node<float>} t - The timer to generate the oscillation with.
  24769. * @return {Node<float>} The oscillation node.
  24770. */
  24771. const oscSawtooth = ( t = time ) => t.fract();
  24772. /**
  24773. * Replaces the default UV coordinates used in texture lookups.
  24774. *
  24775. * ```js
  24776. *material.contextNode = replaceDefaultUV( ( textureNode ) => {
  24777. *
  24778. * // ...
  24779. * return customUVCoordinates;
  24780. *
  24781. *} );
  24782. *```
  24783. *
  24784. * @tsl
  24785. * @function
  24786. * @param {function(Node):Node<vec2>} callback - A callback that receives the texture node
  24787. * and must return the new uv coordinates.
  24788. * @param {Node} [node=null] - An optional node to which the context will be applied.
  24789. * @return {ContextNode} A context node that replaces the default UV coordinates.
  24790. */
  24791. function replaceDefaultUV( callback, node = null ) {
  24792. return context( node, { getUV: callback } );
  24793. }
  24794. /**
  24795. * Rotates the given uv coordinates around a center point
  24796. *
  24797. * @tsl
  24798. * @function
  24799. * @param {Node<vec2>} uv - The uv coordinates.
  24800. * @param {Node<float>} rotation - The rotation defined in radians.
  24801. * @param {Node<vec2>} center - The center of rotation
  24802. * @return {Node<vec2>} The rotated uv coordinates.
  24803. */
  24804. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  24805. return rotate( uv.sub( center ), rotation ).add( center );
  24806. } );
  24807. /**
  24808. * Applies a spherical warping effect to the given uv coordinates.
  24809. *
  24810. * @tsl
  24811. * @function
  24812. * @param {Node<vec2>} uv - The uv coordinates.
  24813. * @param {Node<float>} strength - The strength of the effect.
  24814. * @param {Node<vec2>} center - The center point
  24815. * @return {Node<vec2>} The updated uv coordinates.
  24816. */
  24817. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  24818. const delta = uv.sub( center );
  24819. const delta2 = delta.dot( delta );
  24820. const delta4 = delta2.mul( delta2 );
  24821. const deltaOffset = delta4.mul( strength );
  24822. return uv.add( delta.mul( deltaOffset ) );
  24823. } );
  24824. /**
  24825. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  24826. * oriented always towards the camera.
  24827. *
  24828. * ```js
  24829. * material.vertexNode = billboarding();
  24830. * ```
  24831. *
  24832. * @tsl
  24833. * @function
  24834. * @param {Object} config - The configuration object.
  24835. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  24836. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  24837. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  24838. * @return {Node<vec3>} The updated vertex position in clip space.
  24839. */
  24840. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  24841. let worldMatrix;
  24842. if ( position !== null ) {
  24843. worldMatrix = modelWorldMatrix.toVar();
  24844. worldMatrix[ 3 ][ 0 ] = position.x;
  24845. worldMatrix[ 3 ][ 1 ] = position.y;
  24846. worldMatrix[ 3 ][ 2 ] = position.z;
  24847. } else {
  24848. worldMatrix = modelWorldMatrix;
  24849. }
  24850. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  24851. if ( defined( horizontal ) ) {
  24852. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  24853. modelViewMatrix[ 0 ][ 1 ] = 0;
  24854. modelViewMatrix[ 0 ][ 2 ] = 0;
  24855. }
  24856. if ( defined( vertical ) ) {
  24857. modelViewMatrix[ 1 ][ 0 ] = 0;
  24858. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  24859. modelViewMatrix[ 1 ][ 2 ] = 0;
  24860. }
  24861. modelViewMatrix[ 2 ][ 0 ] = 0;
  24862. modelViewMatrix[ 2 ][ 1 ] = 0;
  24863. modelViewMatrix[ 2 ][ 2 ] = 1;
  24864. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  24865. } );
  24866. /**
  24867. * A special version of a screen uv function that involves a depth comparison
  24868. * when computing the final uvs. The function mitigates visual errors when
  24869. * using viewport texture nodes for refraction purposes. Without this function
  24870. * objects in front of a refractive surface might appear on the refractive surface
  24871. * which is incorrect.
  24872. *
  24873. * @tsl
  24874. * @function
  24875. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  24876. * @return {Node<vec2>} The update uv coordinates.
  24877. */
  24878. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  24879. const depth = linearDepth();
  24880. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  24881. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  24882. return finalUV;
  24883. } );
  24884. /**
  24885. * Can be used to compute texture coordinates for animated sprite sheets.
  24886. *
  24887. * ```js
  24888. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  24889. *
  24890. * material.colorNode = texture( spriteSheet, uvNode );
  24891. * ```
  24892. *
  24893. * @augments Node
  24894. */
  24895. class SpriteSheetUVNode extends Node {
  24896. static get type() {
  24897. return 'SpriteSheetUVNode';
  24898. }
  24899. /**
  24900. * Constructs a new sprite sheet uv node.
  24901. *
  24902. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24903. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  24904. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  24905. */
  24906. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  24907. super( 'vec2' );
  24908. /**
  24909. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24910. *
  24911. * @type {Node<vec2>}
  24912. */
  24913. this.countNode = countNode;
  24914. /**
  24915. * The uv node.
  24916. *
  24917. * @type {Node<vec2>}
  24918. */
  24919. this.uvNode = uvNode;
  24920. /**
  24921. * The node that defines the current frame/sprite.
  24922. *
  24923. * @type {Node<float>}
  24924. */
  24925. this.frameNode = frameNode;
  24926. }
  24927. setup() {
  24928. const { frameNode, uvNode, countNode } = this;
  24929. const { width, height } = countNode;
  24930. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  24931. const column = frameNum.mod( width );
  24932. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  24933. const scale = countNode.reciprocal();
  24934. const uvFrameOffset = vec2( column, row );
  24935. return uvNode.add( uvFrameOffset ).mul( scale );
  24936. }
  24937. }
  24938. /**
  24939. * TSL function for creating a sprite sheet uv node.
  24940. *
  24941. * @tsl
  24942. * @function
  24943. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24944. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  24945. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  24946. * @returns {SpriteSheetUVNode}
  24947. */
  24948. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  24949. /**
  24950. * TSL function for creating a triplanar textures node.
  24951. *
  24952. * Can be used for triplanar texture mapping.
  24953. *
  24954. * ```js
  24955. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  24956. * ```
  24957. *
  24958. * @tsl
  24959. * @function
  24960. * @param {Node} textureXNode - First texture node.
  24961. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  24962. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  24963. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  24964. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  24965. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  24966. * @returns {Node<vec4>}
  24967. */
  24968. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  24969. // Reference: https://github.com/keijiro/StandardTriplanar
  24970. // Blending factor of triplanar mapping
  24971. let bf = normalNode.abs().normalize();
  24972. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  24973. // Triplanar mapping
  24974. const tx = positionNode.yz.mul( scaleNode );
  24975. const ty = positionNode.zx.mul( scaleNode );
  24976. const tz = positionNode.xy.mul( scaleNode );
  24977. // Base color
  24978. const textureX = textureXNode.value;
  24979. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  24980. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  24981. const cx = texture( textureX, tx ).mul( bf.x );
  24982. const cy = texture( textureY, ty ).mul( bf.y );
  24983. const cz = texture( textureZ, tz ).mul( bf.z );
  24984. return add( cx, cy, cz );
  24985. } );
  24986. /**
  24987. * TSL function for creating a triplanar textures node.
  24988. *
  24989. * @tsl
  24990. * @function
  24991. * @param {Node} textureXNode - First texture node.
  24992. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  24993. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  24994. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  24995. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  24996. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  24997. * @returns {Node<vec4>}
  24998. */
  24999. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  25000. const _reflectorPlane = new Plane();
  25001. const _normal = new Vector3();
  25002. const _reflectorWorldPosition = new Vector3();
  25003. const _cameraWorldPosition = new Vector3();
  25004. const _rotationMatrix = new Matrix4();
  25005. const _lookAtPosition = new Vector3( 0, 0, -1 );
  25006. const clipPlane = new Vector4();
  25007. const _view = new Vector3();
  25008. const _target = new Vector3();
  25009. const _q = new Vector4();
  25010. const _size$2 = new Vector2();
  25011. const _defaultRT = new RenderTarget();
  25012. const _defaultUV = screenUV.flipX();
  25013. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  25014. let _inReflector = false;
  25015. /**
  25016. * This node can be used to implement mirror-like flat reflective surfaces.
  25017. *
  25018. * ```js
  25019. * const groundReflector = reflector();
  25020. * material.colorNode = groundReflector;
  25021. *
  25022. * const plane = new Mesh( geometry, material );
  25023. * plane.add( groundReflector.target );
  25024. * ```
  25025. *
  25026. * @augments TextureNode
  25027. */
  25028. class ReflectorNode extends TextureNode {
  25029. static get type() {
  25030. return 'ReflectorNode';
  25031. }
  25032. /**
  25033. * Constructs a new reflector node.
  25034. *
  25035. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25036. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25037. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  25038. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25039. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25040. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25041. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25042. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  25043. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  25044. */
  25045. constructor( parameters = {} ) {
  25046. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  25047. /**
  25048. * A reference to the internal reflector base node which holds the actual implementation.
  25049. *
  25050. * @private
  25051. * @type {ReflectorBaseNode}
  25052. * @default ReflectorBaseNode
  25053. */
  25054. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  25055. /**
  25056. * A reference to the internal depth node.
  25057. *
  25058. * @private
  25059. * @type {?Node}
  25060. * @default null
  25061. */
  25062. this._depthNode = null;
  25063. this.setUpdateMatrix( false );
  25064. }
  25065. /**
  25066. * A reference to the internal reflector node.
  25067. *
  25068. * @type {ReflectorBaseNode}
  25069. */
  25070. get reflector() {
  25071. return this._reflectorBaseNode;
  25072. }
  25073. /**
  25074. * A reference to 3D object the reflector is linked to.
  25075. *
  25076. * @type {Object3D}
  25077. */
  25078. get target() {
  25079. return this._reflectorBaseNode.target;
  25080. }
  25081. /**
  25082. * Returns a node representing the mirror's depth. That can be used
  25083. * to implement more advanced reflection effects like distance attenuation.
  25084. *
  25085. * @return {Node} The depth node.
  25086. */
  25087. getDepthNode() {
  25088. if ( this._depthNode === null ) {
  25089. if ( this._reflectorBaseNode.depth !== true ) {
  25090. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  25091. }
  25092. this._depthNode = nodeObject( new ReflectorNode( {
  25093. defaultTexture: _defaultRT.depthTexture,
  25094. reflector: this._reflectorBaseNode
  25095. } ) );
  25096. }
  25097. return this._depthNode;
  25098. }
  25099. setup( builder ) {
  25100. // ignore if used in post-processing
  25101. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  25102. return super.setup( builder );
  25103. }
  25104. clone() {
  25105. const newNode = new this.constructor( this.reflectorNode );
  25106. newNode.uvNode = this.uvNode;
  25107. newNode.levelNode = this.levelNode;
  25108. newNode.biasNode = this.biasNode;
  25109. newNode.sampler = this.sampler;
  25110. newNode.depthNode = this.depthNode;
  25111. newNode.compareNode = this.compareNode;
  25112. newNode.gradNode = this.gradNode;
  25113. newNode.offsetNode = this.offsetNode;
  25114. newNode._reflectorBaseNode = this._reflectorBaseNode;
  25115. return newNode;
  25116. }
  25117. /**
  25118. * Frees internal resources. Should be called when the node is no longer in use.
  25119. */
  25120. dispose() {
  25121. super.dispose();
  25122. this._reflectorBaseNode.dispose();
  25123. }
  25124. }
  25125. /**
  25126. * Holds the actual implementation of the reflector.
  25127. *
  25128. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  25129. * in `ReflectorNode`, see #29619.
  25130. *
  25131. * @private
  25132. * @augments Node
  25133. */
  25134. class ReflectorBaseNode extends Node {
  25135. static get type() {
  25136. return 'ReflectorBaseNode';
  25137. }
  25138. /**
  25139. * Constructs a new reflector base node.
  25140. *
  25141. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  25142. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25143. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25144. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  25145. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25146. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25147. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25148. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25149. */
  25150. constructor( textureNode, parameters = {} ) {
  25151. super();
  25152. const {
  25153. target = new Object3D(),
  25154. resolutionScale = 1,
  25155. generateMipmaps = false,
  25156. bounces = true,
  25157. depth = false,
  25158. samples = 0
  25159. } = parameters;
  25160. /**
  25161. * Represents the rendered reflections as a texture node.
  25162. *
  25163. * @type {TextureNode}
  25164. */
  25165. this.textureNode = textureNode;
  25166. /**
  25167. * The 3D object the reflector is linked to.
  25168. *
  25169. * @type {Object3D}
  25170. * @default {new Object3D()}
  25171. */
  25172. this.target = target;
  25173. /**
  25174. * The resolution scale.
  25175. *
  25176. * @type {number}
  25177. * @default {1}
  25178. */
  25179. this.resolutionScale = resolutionScale;
  25180. if ( parameters.resolution !== undefined ) {
  25181. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  25182. this.resolutionScale = parameters.resolution;
  25183. }
  25184. /**
  25185. * Whether mipmaps should be generated or not.
  25186. *
  25187. * @type {boolean}
  25188. * @default {false}
  25189. */
  25190. this.generateMipmaps = generateMipmaps;
  25191. /**
  25192. * Whether reflectors can render other reflector nodes or not.
  25193. *
  25194. * @type {boolean}
  25195. * @default {true}
  25196. */
  25197. this.bounces = bounces;
  25198. /**
  25199. * Whether depth data should be generated or not.
  25200. *
  25201. * @type {boolean}
  25202. * @default {false}
  25203. */
  25204. this.depth = depth;
  25205. /**
  25206. * The number of anti-aliasing samples for the render-target
  25207. *
  25208. * @type {number}
  25209. * @default {0}
  25210. */
  25211. this.samples = samples;
  25212. /**
  25213. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  25214. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  25215. *
  25216. * @type {string}
  25217. * @default 'render'
  25218. */
  25219. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  25220. /**
  25221. * Weak map for managing virtual cameras.
  25222. *
  25223. * @type {WeakMap<Camera, Camera>}
  25224. */
  25225. this.virtualCameras = new WeakMap();
  25226. /**
  25227. * Weak map for managing render targets.
  25228. *
  25229. * @type {Map<Camera, RenderTarget>}
  25230. */
  25231. this.renderTargets = new Map();
  25232. /**
  25233. * Force render even if reflector is facing away from camera.
  25234. *
  25235. * @type {boolean}
  25236. * @default {false}
  25237. */
  25238. this.forceUpdate = false;
  25239. /**
  25240. * Whether the reflector has been rendered or not.
  25241. *
  25242. * When the reflector is facing away from the camera,
  25243. * this flag is set to `false` and the texture will be empty(black).
  25244. *
  25245. * @type {boolean}
  25246. * @default {false}
  25247. */
  25248. this.hasOutput = false;
  25249. }
  25250. /**
  25251. * Updates the resolution of the internal render target.
  25252. *
  25253. * @private
  25254. * @param {RenderTarget} renderTarget - The render target to resize.
  25255. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  25256. */
  25257. _updateResolution( renderTarget, renderer ) {
  25258. const resolution = this.resolutionScale;
  25259. renderer.getDrawingBufferSize( _size$2 );
  25260. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  25261. }
  25262. setup( builder ) {
  25263. this._updateResolution( _defaultRT, builder.renderer );
  25264. return super.setup( builder );
  25265. }
  25266. /**
  25267. * Frees internal resources. Should be called when the node is no longer in use.
  25268. */
  25269. dispose() {
  25270. super.dispose();
  25271. for ( const renderTarget of this.renderTargets.values() ) {
  25272. renderTarget.dispose();
  25273. }
  25274. }
  25275. /**
  25276. * Returns a virtual camera for the given camera. The virtual camera is used to
  25277. * render the scene from the reflector's view so correct reflections can be produced.
  25278. *
  25279. * @param {Camera} camera - The scene's camera.
  25280. * @return {Camera} The corresponding virtual camera.
  25281. */
  25282. getVirtualCamera( camera ) {
  25283. let virtualCamera = this.virtualCameras.get( camera );
  25284. if ( virtualCamera === undefined ) {
  25285. virtualCamera = camera.clone();
  25286. this.virtualCameras.set( camera, virtualCamera );
  25287. }
  25288. return virtualCamera;
  25289. }
  25290. /**
  25291. * Returns a render target for the given camera. The reflections are rendered
  25292. * into this render target.
  25293. *
  25294. * @param {Camera} camera - The scene's camera.
  25295. * @return {RenderTarget} The render target.
  25296. */
  25297. getRenderTarget( camera ) {
  25298. let renderTarget = this.renderTargets.get( camera );
  25299. if ( renderTarget === undefined ) {
  25300. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  25301. if ( this.generateMipmaps === true ) {
  25302. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  25303. renderTarget.texture.generateMipmaps = true;
  25304. }
  25305. if ( this.depth === true ) {
  25306. renderTarget.depthTexture = new DepthTexture();
  25307. }
  25308. this.renderTargets.set( camera, renderTarget );
  25309. }
  25310. return renderTarget;
  25311. }
  25312. updateBefore( frame ) {
  25313. if ( this.bounces === false && _inReflector ) return false;
  25314. _inReflector = true;
  25315. const { scene, camera, renderer, material } = frame;
  25316. const { target } = this;
  25317. const virtualCamera = this.getVirtualCamera( camera );
  25318. const renderTarget = this.getRenderTarget( virtualCamera );
  25319. renderer.getDrawingBufferSize( _size$2 );
  25320. this._updateResolution( renderTarget, renderer );
  25321. //
  25322. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  25323. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  25324. _rotationMatrix.extractRotation( target.matrixWorld );
  25325. _normal.set( 0, 0, 1 );
  25326. _normal.applyMatrix4( _rotationMatrix );
  25327. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  25328. // Avoid rendering when reflector is facing away unless forcing an update
  25329. const isFacingAway = _view.dot( _normal ) > 0;
  25330. let needsClear = false;
  25331. if ( isFacingAway === true && this.forceUpdate === false ) {
  25332. if ( this.hasOutput === false ) {
  25333. _inReflector = false;
  25334. return;
  25335. }
  25336. needsClear = true;
  25337. }
  25338. _view.reflect( _normal ).negate();
  25339. _view.add( _reflectorWorldPosition );
  25340. _rotationMatrix.extractRotation( camera.matrixWorld );
  25341. _lookAtPosition.set( 0, 0, -1 );
  25342. _lookAtPosition.applyMatrix4( _rotationMatrix );
  25343. _lookAtPosition.add( _cameraWorldPosition );
  25344. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  25345. _target.reflect( _normal ).negate();
  25346. _target.add( _reflectorWorldPosition );
  25347. //
  25348. virtualCamera.coordinateSystem = camera.coordinateSystem;
  25349. virtualCamera.position.copy( _view );
  25350. virtualCamera.up.set( 0, 1, 0 );
  25351. virtualCamera.up.applyMatrix4( _rotationMatrix );
  25352. virtualCamera.up.reflect( _normal );
  25353. virtualCamera.lookAt( _target );
  25354. virtualCamera.near = camera.near;
  25355. virtualCamera.far = camera.far;
  25356. virtualCamera.updateMatrixWorld();
  25357. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  25358. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  25359. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  25360. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  25361. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  25362. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  25363. const projectionMatrix = virtualCamera.projectionMatrix;
  25364. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  25365. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  25366. _q.z = -1;
  25367. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  25368. // Calculate the scaled plane vector
  25369. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  25370. const clipBias = 0;
  25371. // Replacing the third row of the projection matrix
  25372. projectionMatrix.elements[ 2 ] = clipPlane.x;
  25373. projectionMatrix.elements[ 6 ] = clipPlane.y;
  25374. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  25375. projectionMatrix.elements[ 14 ] = clipPlane.w;
  25376. //
  25377. this.textureNode.value = renderTarget.texture;
  25378. if ( this.depth === true ) {
  25379. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  25380. }
  25381. material.visible = false;
  25382. const currentRenderTarget = renderer.getRenderTarget();
  25383. const currentMRT = renderer.getMRT();
  25384. const currentAutoClear = renderer.autoClear;
  25385. renderer.setMRT( null );
  25386. renderer.setRenderTarget( renderTarget );
  25387. renderer.autoClear = true;
  25388. const previousName = scene.name;
  25389. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  25390. if ( needsClear ) {
  25391. renderer.clear();
  25392. this.hasOutput = false;
  25393. } else {
  25394. renderer.render( scene, virtualCamera );
  25395. this.hasOutput = true;
  25396. }
  25397. scene.name = previousName;
  25398. renderer.setMRT( currentMRT );
  25399. renderer.setRenderTarget( currentRenderTarget );
  25400. renderer.autoClear = currentAutoClear;
  25401. material.visible = true;
  25402. _inReflector = false;
  25403. this.forceUpdate = false;
  25404. }
  25405. /**
  25406. * The resolution scale.
  25407. *
  25408. * @deprecated
  25409. * @type {number}
  25410. * @default {1}
  25411. */
  25412. get resolution() {
  25413. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  25414. return this.resolutionScale;
  25415. }
  25416. set resolution( value ) {
  25417. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  25418. this.resolutionScale = value;
  25419. }
  25420. }
  25421. /**
  25422. * TSL function for creating a reflector node.
  25423. *
  25424. * @tsl
  25425. * @function
  25426. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25427. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25428. * @param {number} [parameters.resolution=1] - The resolution scale.
  25429. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25430. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25431. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25432. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25433. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  25434. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  25435. * @returns {ReflectorNode}
  25436. */
  25437. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  25438. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  25439. /**
  25440. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  25441. *
  25442. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  25443. *
  25444. * @private
  25445. * @augments BufferGeometry
  25446. */
  25447. class QuadGeometry extends BufferGeometry {
  25448. /**
  25449. * Constructs a new quad geometry.
  25450. *
  25451. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  25452. */
  25453. constructor( flipY = false ) {
  25454. super();
  25455. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  25456. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  25457. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  25458. }
  25459. }
  25460. const _geometry = /*@__PURE__*/ new QuadGeometry();
  25461. /**
  25462. * This module is a helper for passes which need to render a full
  25463. * screen effect which is quite common in context of post processing.
  25464. *
  25465. * The intended usage is to reuse a single quad mesh for rendering
  25466. * subsequent passes by just reassigning the `material` reference.
  25467. *
  25468. * Note: This module can only be used with `WebGPURenderer`.
  25469. *
  25470. * @augments Mesh
  25471. */
  25472. class QuadMesh extends Mesh {
  25473. /**
  25474. * Constructs a new quad mesh.
  25475. *
  25476. * @param {?Material} [material=null] - The material to render the quad mesh with.
  25477. */
  25478. constructor( material = null ) {
  25479. super( _geometry, material );
  25480. /**
  25481. * The camera to render the quad mesh with.
  25482. *
  25483. * @type {OrthographicCamera}
  25484. * @readonly
  25485. */
  25486. this.camera = _camera;
  25487. /**
  25488. * This flag can be used for type testing.
  25489. *
  25490. * @type {boolean}
  25491. * @readonly
  25492. * @default true
  25493. */
  25494. this.isQuadMesh = true;
  25495. }
  25496. /**
  25497. * Async version of `render()`.
  25498. *
  25499. * @async
  25500. * @deprecated
  25501. * @param {Renderer} renderer - The renderer.
  25502. * @return {Promise} A Promise that resolves when the render has been finished.
  25503. */
  25504. async renderAsync( renderer ) {
  25505. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  25506. await renderer.init();
  25507. renderer.render( this, _camera );
  25508. }
  25509. /**
  25510. * Renders the quad mesh
  25511. *
  25512. * @param {Renderer} renderer - The renderer.
  25513. */
  25514. render( renderer ) {
  25515. renderer.render( this, _camera );
  25516. }
  25517. }
  25518. const _size$1 = /*@__PURE__*/ new Vector2();
  25519. /**
  25520. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  25521. * This module is especially relevant in context of post processing where certain nodes require
  25522. * texture input for their effects. With the helper function `convertToTexture()` which is based
  25523. * on this module, the node system can automatically ensure texture input if required.
  25524. *
  25525. * @augments TextureNode
  25526. */
  25527. class RTTNode extends TextureNode {
  25528. static get type() {
  25529. return 'RTTNode';
  25530. }
  25531. /**
  25532. * Constructs a new RTT node.
  25533. *
  25534. * @param {Node} node - The node to render a texture with.
  25535. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25536. * @param {?number} [height=null] - The height of the internal render target.
  25537. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25538. */
  25539. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  25540. const renderTarget = new RenderTarget( width, height, options );
  25541. super( renderTarget.texture, uv$1() );
  25542. /**
  25543. * This flag can be used for type testing.
  25544. *
  25545. * @type {boolean}
  25546. * @readonly
  25547. * @default true
  25548. */
  25549. this.isRTTNode = true;
  25550. /**
  25551. * The node to render a texture with.
  25552. *
  25553. * @type {Node}
  25554. */
  25555. this.node = node;
  25556. /**
  25557. * The width of the internal render target.
  25558. * If not width is applied, the render target is automatically resized.
  25559. *
  25560. * @type {?number}
  25561. * @default null
  25562. */
  25563. this.width = width;
  25564. /**
  25565. * The height of the internal render target.
  25566. *
  25567. * @type {?number}
  25568. * @default null
  25569. */
  25570. this.height = height;
  25571. /**
  25572. * The pixel ratio
  25573. *
  25574. * @type {number}
  25575. * @default 1
  25576. */
  25577. this.pixelRatio = 1;
  25578. /**
  25579. * The render target
  25580. *
  25581. * @type {RenderTarget}
  25582. */
  25583. this.renderTarget = renderTarget;
  25584. /**
  25585. * Whether the texture requires an update or not.
  25586. *
  25587. * @type {boolean}
  25588. * @default true
  25589. */
  25590. this.textureNeedsUpdate = true;
  25591. /**
  25592. * Whether the texture should automatically be updated or not.
  25593. *
  25594. * @type {boolean}
  25595. * @default true
  25596. */
  25597. this.autoUpdate = true;
  25598. /**
  25599. * The node which is used with the quad mesh for RTT.
  25600. *
  25601. * @private
  25602. * @type {Node}
  25603. * @default null
  25604. */
  25605. this._rttNode = null;
  25606. /**
  25607. * The internal quad mesh for RTT.
  25608. *
  25609. * @private
  25610. * @type {QuadMesh}
  25611. */
  25612. this._quadMesh = new QuadMesh( new NodeMaterial() );
  25613. /**
  25614. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  25615. * the texture once per render in its {@link RTTNode#updateBefore} method.
  25616. *
  25617. * @type {string}
  25618. * @default 'render'
  25619. */
  25620. this.updateBeforeType = NodeUpdateType.RENDER;
  25621. }
  25622. /**
  25623. * Whether the internal render target should automatically be resized or not.
  25624. *
  25625. * @type {boolean}
  25626. * @readonly
  25627. * @default true
  25628. */
  25629. get autoResize() {
  25630. return this.width === null;
  25631. }
  25632. setup( builder ) {
  25633. this._rttNode = this.node.context( builder.getSharedContext() );
  25634. this._quadMesh.material.name = 'RTT';
  25635. this._quadMesh.material.needsUpdate = true;
  25636. return super.setup( builder );
  25637. }
  25638. /**
  25639. * Sets the size of the internal render target
  25640. *
  25641. * @param {number} width - The width to set.
  25642. * @param {number} height - The width to set.
  25643. */
  25644. setSize( width, height ) {
  25645. this.width = width;
  25646. this.height = height;
  25647. const effectiveWidth = width * this.pixelRatio;
  25648. const effectiveHeight = height * this.pixelRatio;
  25649. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25650. this.textureNeedsUpdate = true;
  25651. }
  25652. /**
  25653. * Sets the pixel ratio. This will also resize the render target.
  25654. *
  25655. * @param {number} pixelRatio - The pixel ratio to set.
  25656. */
  25657. setPixelRatio( pixelRatio ) {
  25658. this.pixelRatio = pixelRatio;
  25659. this.setSize( this.width, this.height );
  25660. }
  25661. updateBefore( { renderer } ) {
  25662. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  25663. this.textureNeedsUpdate = false;
  25664. //
  25665. if ( this.autoResize === true ) {
  25666. const pixelRatio = renderer.getPixelRatio();
  25667. const size = renderer.getSize( _size$1 );
  25668. const effectiveWidth = Math.floor( size.width * pixelRatio );
  25669. const effectiveHeight = Math.floor( size.height * pixelRatio );
  25670. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  25671. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25672. this.textureNeedsUpdate = true;
  25673. }
  25674. }
  25675. //
  25676. let name = 'RTT';
  25677. if ( this.node.name ) {
  25678. name = this.node.name + ' [ ' + name + ' ]';
  25679. }
  25680. this._quadMesh.material.fragmentNode = this._rttNode;
  25681. this._quadMesh.name = name;
  25682. //
  25683. const currentRenderTarget = renderer.getRenderTarget();
  25684. renderer.setRenderTarget( this.renderTarget );
  25685. this._quadMesh.render( renderer );
  25686. renderer.setRenderTarget( currentRenderTarget );
  25687. }
  25688. clone() {
  25689. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  25690. newNode.sampler = this.sampler;
  25691. newNode.referenceNode = this;
  25692. return newNode;
  25693. }
  25694. }
  25695. /**
  25696. * TSL function for creating a RTT node.
  25697. *
  25698. * @tsl
  25699. * @function
  25700. * @param {Node} node - The node to render a texture with.
  25701. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25702. * @param {?number} [height=null] - The height of the internal render target.
  25703. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25704. * @returns {RTTNode}
  25705. */
  25706. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  25707. /**
  25708. * TSL function for converting nodes to textures nodes.
  25709. *
  25710. * @tsl
  25711. * @function
  25712. * @param {Node} node - The node to render a texture with.
  25713. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25714. * @param {?number} [height=null] - The height of the internal render target.
  25715. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25716. * @returns {RTTNode}
  25717. */
  25718. const convertToTexture = ( node, ...params ) => {
  25719. if ( node.isSampleNode || node.isTextureNode ) return node;
  25720. if ( node.isPassNode ) return node.getTextureNode();
  25721. return rtt( node, ...params );
  25722. };
  25723. /**
  25724. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  25725. * depth value and the camera's inverse projection matrix.
  25726. *
  25727. * @tsl
  25728. * @function
  25729. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  25730. * @param {Node<float>} depth - The fragment's depth value.
  25731. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  25732. * @return {Node<vec3>} The fragments position in view space.
  25733. */
  25734. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  25735. let clipSpacePosition;
  25736. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25737. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  25738. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  25739. } else {
  25740. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  25741. }
  25742. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  25743. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  25744. } );
  25745. /**
  25746. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  25747. * and the camera's projection matrix
  25748. *
  25749. * @tsl
  25750. * @function
  25751. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  25752. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  25753. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  25754. */
  25755. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  25756. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  25757. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  25758. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  25759. } );
  25760. /**
  25761. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  25762. * target is available or if flat surface normals are required.
  25763. *
  25764. * @tsl
  25765. * @function
  25766. * @param {Node<vec2>} uv - The texture coordinate.
  25767. * @param {DepthTexture} depthTexture - The depth texture.
  25768. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  25769. * @return {Node<vec3>} The computed normal vector.
  25770. */
  25771. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  25772. const size = textureSize( textureLoad( depthTexture ) );
  25773. const p = ivec2( uv.mul( size ) ).toVar();
  25774. const c0 = textureLoad( depthTexture, p ).toVar();
  25775. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  25776. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  25777. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  25778. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  25779. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  25780. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  25781. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  25782. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  25783. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  25784. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  25785. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  25786. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  25787. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  25788. 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 ) ) );
  25789. 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 ) ) );
  25790. return normalize( cross( dpdx, dpdy ) );
  25791. } );
  25792. /**
  25793. * Interleaved Gradient Noise (IGN) from Jimenez 2014.
  25794. *
  25795. * IGN has "low discrepancy" resulting in evenly distributed samples. It's superior compared to
  25796. * default white noise, blue noise or Bayer.
  25797. *
  25798. * References:
  25799. * - {@link https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/}
  25800. * - {@link https://blog.demofox.org/2022/01/01/interleaved-gradient-noise-a-different-kind-of-low-discrepancy-sequence/}
  25801. *
  25802. * @tsl
  25803. * @function
  25804. * @param {Node<vec2>} position - The input position, usually screen coordinates.
  25805. * @return {Node<float>} The noise value.
  25806. */
  25807. const interleavedGradientNoise = Fn( ( [ position ] ) => {
  25808. return fract( float( 52.9829189 ).mul( fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ) );
  25809. } ).setLayout( {
  25810. name: 'interleavedGradientNoise',
  25811. type: 'float',
  25812. inputs: [
  25813. { name: 'position', type: 'vec2' }
  25814. ]
  25815. } );
  25816. /**
  25817. * Class representing a node that samples a value using a provided callback function.
  25818. *
  25819. * @extends Node
  25820. */
  25821. class SampleNode extends Node {
  25822. /**
  25823. * Returns the type of the node.
  25824. *
  25825. * @type {string}
  25826. * @readonly
  25827. * @static
  25828. */
  25829. static get type() {
  25830. return 'SampleNode';
  25831. }
  25832. /**
  25833. * Creates an instance of SampleNode.
  25834. *
  25835. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  25836. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  25837. */
  25838. constructor( callback, uvNode = null ) {
  25839. super();
  25840. this.callback = callback;
  25841. /**
  25842. * Represents the texture coordinates.
  25843. *
  25844. * @type {?Node<vec2|vec3>}
  25845. * @default null
  25846. */
  25847. this.uvNode = uvNode;
  25848. /**
  25849. * This flag can be used for type testing.
  25850. *
  25851. * @type {boolean}
  25852. * @readonly
  25853. * @default true
  25854. */
  25855. this.isSampleNode = true;
  25856. }
  25857. /**
  25858. * Sets up the node by sampling with the default UV accessor.
  25859. *
  25860. * @returns {Node} The result of the callback function when called with the UV node.
  25861. */
  25862. setup() {
  25863. return this.sample( uv$1() );
  25864. }
  25865. /**
  25866. * Calls the callback function with the provided UV node.
  25867. *
  25868. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  25869. * @returns {Node} The result of the callback function.
  25870. */
  25871. sample( uv ) {
  25872. return this.callback( uv );
  25873. }
  25874. }
  25875. /**
  25876. * Helper function to create a SampleNode wrapped as a node object.
  25877. *
  25878. * @function
  25879. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  25880. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  25881. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  25882. */
  25883. const sample = ( callback, uv = null ) => nodeObject( new SampleNode( callback, nodeObject( uv ) ) );
  25884. /**
  25885. * EventNode is a node that executes a callback during specific update phases.
  25886. *
  25887. * @augments Node
  25888. */
  25889. class EventNode extends Node {
  25890. static get type() {
  25891. return 'EventNode';
  25892. }
  25893. /**
  25894. * Creates an EventNode.
  25895. *
  25896. * @param {string} eventType - The type of event
  25897. * @param {Function} callback - The callback to execute on update.
  25898. */
  25899. constructor( eventType, callback ) {
  25900. super( 'void' );
  25901. this.eventType = eventType;
  25902. this.callback = callback;
  25903. if ( eventType === EventNode.OBJECT ) {
  25904. this.updateType = NodeUpdateType.OBJECT;
  25905. } else if ( eventType === EventNode.MATERIAL ) {
  25906. this.updateType = NodeUpdateType.RENDER;
  25907. } else if ( eventType === EventNode.BEFORE_OBJECT ) {
  25908. this.updateBeforeType = NodeUpdateType.OBJECT;
  25909. } else if ( eventType === EventNode.BEFORE_MATERIAL ) {
  25910. this.updateBeforeType = NodeUpdateType.RENDER;
  25911. }
  25912. }
  25913. update( frame ) {
  25914. this.callback( frame );
  25915. }
  25916. updateBefore( frame ) {
  25917. this.callback( frame );
  25918. }
  25919. }
  25920. EventNode.OBJECT = 'object';
  25921. EventNode.MATERIAL = 'material';
  25922. EventNode.BEFORE_OBJECT = 'beforeObject';
  25923. EventNode.BEFORE_MATERIAL = 'beforeMaterial';
  25924. /**
  25925. * Helper to create an EventNode and add it to the stack.
  25926. *
  25927. * @param {string} type - The event type.
  25928. * @param {Function} callback - The callback function.
  25929. * @returns {EventNode}
  25930. */
  25931. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  25932. /**
  25933. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  25934. *
  25935. * 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.
  25936. *
  25937. * @param {Function} callback - The callback function.
  25938. * @returns {EventNode}
  25939. */
  25940. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  25941. /**
  25942. * Creates an event that triggers a function when the first object that uses the material is rendered.
  25943. *
  25944. * 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.
  25945. *
  25946. * @param {Function} callback - The callback function.
  25947. * @returns {EventNode}
  25948. */
  25949. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  25950. /**
  25951. * Creates an event that triggers a function before an object (Mesh|Sprite) is updated.
  25952. *
  25953. * 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.
  25954. *
  25955. * @param {Function} callback - The callback function.
  25956. * @returns {EventNode}
  25957. */
  25958. const OnBeforeObjectUpdate = ( callback ) => createEvent( EventNode.BEFORE_OBJECT, callback );
  25959. /**
  25960. * Creates an event that triggers a function before the material is updated.
  25961. *
  25962. * 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.
  25963. *
  25964. * @param {Function} callback - The callback function.
  25965. * @returns {EventNode}
  25966. */
  25967. const OnBeforeMaterialUpdate = ( callback ) => createEvent( EventNode.BEFORE_MATERIAL, callback );
  25968. /**
  25969. * This special type of instanced buffer attribute is intended for compute shaders.
  25970. * In earlier three.js versions it was only possible to update attribute data
  25971. * on the CPU via JavaScript and then upload the data to the GPU. With the
  25972. * new material system and renderer it is now possible to use compute shaders
  25973. * to compute the data for an attribute more efficiently on the GPU.
  25974. *
  25975. * The idea is to create an instance of this class and provide it as an input
  25976. * to {@link StorageBufferNode}.
  25977. *
  25978. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  25979. *
  25980. * @augments InstancedBufferAttribute
  25981. */
  25982. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  25983. /**
  25984. * Constructs a new storage instanced buffer attribute.
  25985. *
  25986. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  25987. * The subsequent parameters are then obsolete.
  25988. * @param {number} itemSize - The item size.
  25989. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  25990. */
  25991. constructor( count, itemSize, typeClass = Float32Array ) {
  25992. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  25993. super( array, itemSize );
  25994. /**
  25995. * This flag can be used for type testing.
  25996. *
  25997. * @type {boolean}
  25998. * @readonly
  25999. * @default true
  26000. */
  26001. this.isStorageInstancedBufferAttribute = true;
  26002. }
  26003. }
  26004. /**
  26005. * This special type of buffer attribute is intended for compute shaders.
  26006. * In earlier three.js versions it was only possible to update attribute data
  26007. * on the CPU via JavaScript and then upload the data to the GPU. With the
  26008. * new material system and renderer it is now possible to use compute shaders
  26009. * to compute the data for an attribute more efficiently on the GPU.
  26010. *
  26011. * The idea is to create an instance of this class and provide it as an input
  26012. * to {@link StorageBufferNode}.
  26013. *
  26014. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  26015. *
  26016. * @augments BufferAttribute
  26017. */
  26018. class StorageBufferAttribute extends BufferAttribute {
  26019. /**
  26020. * Constructs a new storage buffer attribute.
  26021. *
  26022. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  26023. * The subsequent parameters are then obsolete.
  26024. * @param {number} itemSize - The item size.
  26025. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  26026. */
  26027. constructor( count, itemSize, typeClass = Float32Array ) {
  26028. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  26029. super( array, itemSize );
  26030. /**
  26031. * This flag can be used for type testing.
  26032. *
  26033. * @type {boolean}
  26034. * @readonly
  26035. * @default true
  26036. */
  26037. this.isStorageBufferAttribute = true;
  26038. }
  26039. }
  26040. /**
  26041. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  26042. *
  26043. * @tsl
  26044. * @function
  26045. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  26046. * @param {string|Struct} [type='float'] - The data type.
  26047. * @returns {StorageBufferNode}
  26048. */
  26049. const attributeArray = ( count, type = 'float' ) => {
  26050. let itemSize, typedArray;
  26051. if ( type.isStruct === true ) {
  26052. itemSize = type.layout.getLength();
  26053. typedArray = getTypedArrayFromType( 'float' );
  26054. } else {
  26055. itemSize = getLengthFromType( type );
  26056. typedArray = getTypedArrayFromType( type );
  26057. }
  26058. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  26059. const node = storage( buffer, type, count );
  26060. return node;
  26061. };
  26062. /**
  26063. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  26064. *
  26065. * @tsl
  26066. * @function
  26067. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  26068. * @param {string|Struct} [type='float'] - The data type.
  26069. * @returns {StorageBufferNode}
  26070. */
  26071. const instancedArray = ( count, type = 'float' ) => {
  26072. let itemSize, typedArray;
  26073. if ( type.isStruct === true ) {
  26074. itemSize = type.layout.getLength();
  26075. typedArray = getTypedArrayFromType( 'float' );
  26076. } else {
  26077. itemSize = getLengthFromType( type );
  26078. typedArray = getTypedArrayFromType( type );
  26079. }
  26080. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  26081. const node = storage( buffer, type, count );
  26082. return node;
  26083. };
  26084. /**
  26085. * A node for representing the uv coordinates of points.
  26086. *
  26087. * Can only be used with a WebGL backend. In WebGPU, point
  26088. * primitives always have the size of one pixel and can thus
  26089. * can't be used as sprite-like objects that display textures.
  26090. *
  26091. * @augments Node
  26092. */
  26093. class PointUVNode extends Node {
  26094. static get type() {
  26095. return 'PointUVNode';
  26096. }
  26097. /**
  26098. * Constructs a new point uv node.
  26099. */
  26100. constructor() {
  26101. super( 'vec2' );
  26102. /**
  26103. * This flag can be used for type testing.
  26104. *
  26105. * @type {boolean}
  26106. * @readonly
  26107. * @default true
  26108. */
  26109. this.isPointUVNode = true;
  26110. }
  26111. generate( /*builder*/ ) {
  26112. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  26113. }
  26114. }
  26115. /**
  26116. * TSL object that represents the uv coordinates of points.
  26117. *
  26118. * @tsl
  26119. * @type {PointUVNode}
  26120. */
  26121. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  26122. const _e1 = /*@__PURE__*/ new Euler();
  26123. const _m1 = /*@__PURE__*/ new Matrix4();
  26124. /**
  26125. * This module allows access to a collection of scene properties. The following predefined TSL objects
  26126. * are available for easier use:
  26127. *
  26128. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  26129. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  26130. * - `backgroundRotation`: A node that represents the scene's background rotation.
  26131. *
  26132. * @augments Node
  26133. */
  26134. class SceneNode extends Node {
  26135. static get type() {
  26136. return 'SceneNode';
  26137. }
  26138. /**
  26139. * Constructs a new scene node.
  26140. *
  26141. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  26142. * @param {?Scene} [scene=null] - A reference to the scene.
  26143. */
  26144. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  26145. super();
  26146. /**
  26147. * The scope defines the type of scene property that is accessed.
  26148. *
  26149. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  26150. */
  26151. this.scope = scope;
  26152. /**
  26153. * A reference to the scene that is going to be accessed.
  26154. *
  26155. * @type {?Scene}
  26156. * @default null
  26157. */
  26158. this.scene = scene;
  26159. }
  26160. /**
  26161. * Depending on the scope, the method returns a different type of node that represents
  26162. * the respective scene property.
  26163. *
  26164. * @param {NodeBuilder} builder - The current node builder.
  26165. * @return {Node} The output node.
  26166. */
  26167. setup( builder ) {
  26168. const scope = this.scope;
  26169. const scene = this.scene !== null ? this.scene : builder.scene;
  26170. let output;
  26171. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  26172. output = reference( 'backgroundBlurriness', 'float', scene );
  26173. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  26174. output = reference( 'backgroundIntensity', 'float', scene );
  26175. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  26176. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  26177. const background = scene.background;
  26178. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  26179. _e1.copy( scene.backgroundRotation );
  26180. // accommodate left-handed frame
  26181. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  26182. _m1.makeRotationFromEuler( _e1 );
  26183. } else {
  26184. _m1.identity();
  26185. }
  26186. return _m1;
  26187. } );
  26188. } else {
  26189. error( 'SceneNode: Unknown scope:', scope );
  26190. }
  26191. return output;
  26192. }
  26193. }
  26194. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  26195. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  26196. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  26197. /**
  26198. * TSL object that represents the scene's background blurriness.
  26199. *
  26200. * @tsl
  26201. * @type {SceneNode}
  26202. */
  26203. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  26204. /**
  26205. * TSL object that represents the scene's background intensity.
  26206. *
  26207. * @tsl
  26208. * @type {SceneNode}
  26209. */
  26210. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  26211. /**
  26212. * TSL object that represents the scene's background rotation.
  26213. *
  26214. * @tsl
  26215. * @type {SceneNode}
  26216. */
  26217. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  26218. /**
  26219. * This special version of a texture node can be used to
  26220. * write data into a storage texture with a compute shader.
  26221. *
  26222. * ```js
  26223. * const storageTexture = new THREE.StorageTexture( width, height );
  26224. *
  26225. * const computeTexture = Fn( ( { storageTexture } ) => {
  26226. *
  26227. * const posX = instanceIndex.mod( width );
  26228. * const posY = instanceIndex.div( width );
  26229. * const indexUV = uvec2( posX, posY );
  26230. *
  26231. * // generate RGB values
  26232. *
  26233. * const r = 1;
  26234. * const g = 1;
  26235. * const b = 1;
  26236. *
  26237. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  26238. *
  26239. * } );
  26240. *
  26241. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  26242. * renderer.computeAsync( computeNode );
  26243. * ```
  26244. *
  26245. * This node can only be used with a WebGPU backend.
  26246. *
  26247. * @augments TextureNode
  26248. */
  26249. class StorageTextureNode extends TextureNode {
  26250. static get type() {
  26251. return 'StorageTextureNode';
  26252. }
  26253. /**
  26254. * Constructs a new storage texture node.
  26255. *
  26256. * @param {StorageTexture} value - The storage texture.
  26257. * @param {Node<vec2|vec3>} uvNode - The uv node.
  26258. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26259. */
  26260. constructor( value, uvNode, storeNode = null ) {
  26261. super( value, uvNode );
  26262. /**
  26263. * The value node that should be stored in the texture.
  26264. *
  26265. * @type {?Node}
  26266. * @default null
  26267. */
  26268. this.storeNode = storeNode;
  26269. /**
  26270. * The mip level to write to for storage textures.
  26271. *
  26272. * @type {number}
  26273. * @default 0
  26274. */
  26275. this.mipLevel = 0;
  26276. /**
  26277. * This flag can be used for type testing.
  26278. *
  26279. * @type {boolean}
  26280. * @readonly
  26281. * @default true
  26282. */
  26283. this.isStorageTextureNode = true;
  26284. /**
  26285. * The access type of the texture node.
  26286. *
  26287. * @type {string}
  26288. * @default 'writeOnly'
  26289. */
  26290. this.access = NodeAccess.WRITE_ONLY;
  26291. }
  26292. /**
  26293. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  26294. *
  26295. * @param {NodeBuilder} builder - The current node builder.
  26296. * @return {string} The input type.
  26297. */
  26298. getInputType( /*builder*/ ) {
  26299. return 'storageTexture';
  26300. }
  26301. setup( builder ) {
  26302. super.setup( builder );
  26303. const properties = builder.getNodeProperties( this );
  26304. properties.storeNode = this.storeNode;
  26305. return properties;
  26306. }
  26307. /**
  26308. * Defines the node access.
  26309. *
  26310. * @param {string} value - The node access.
  26311. * @return {StorageTextureNode} A reference to this node.
  26312. */
  26313. setAccess( value ) {
  26314. this.access = value;
  26315. return this;
  26316. }
  26317. /**
  26318. * Sets the mip level to write to.
  26319. *
  26320. * @param {number} level - The mip level.
  26321. * @return {StorageTextureNode} A reference to this node.
  26322. */
  26323. setMipLevel( level ) {
  26324. this.mipLevel = level;
  26325. return this;
  26326. }
  26327. /**
  26328. * Generates the code snippet of the storage node. If no `storeNode`
  26329. * is defined, the texture node is generated as normal texture.
  26330. *
  26331. * @param {NodeBuilder} builder - The current node builder.
  26332. * @param {string} output - The current output.
  26333. * @return {string} The generated code snippet.
  26334. */
  26335. generate( builder, output ) {
  26336. let snippet;
  26337. if ( this.storeNode !== null ) {
  26338. snippet = this.generateStore( builder );
  26339. } else {
  26340. snippet = super.generate( builder, output );
  26341. }
  26342. return snippet;
  26343. }
  26344. /**
  26345. * Convenience method for configuring a read/write node access.
  26346. *
  26347. * @return {StorageTextureNode} A reference to this node.
  26348. */
  26349. toReadWrite() {
  26350. return this.setAccess( NodeAccess.READ_WRITE );
  26351. }
  26352. /**
  26353. * Convenience method for configuring a read-only node access.
  26354. *
  26355. * @return {StorageTextureNode} A reference to this node.
  26356. */
  26357. toReadOnly() {
  26358. return this.setAccess( NodeAccess.READ_ONLY );
  26359. }
  26360. /**
  26361. * Convenience method for configuring a write-only node access.
  26362. *
  26363. * @return {StorageTextureNode} A reference to this node.
  26364. */
  26365. toWriteOnly() {
  26366. return this.setAccess( NodeAccess.WRITE_ONLY );
  26367. }
  26368. /**
  26369. * Generates the code snippet of the storage texture node.
  26370. *
  26371. * @param {NodeBuilder} builder - The current node builder.
  26372. */
  26373. generateStore( builder ) {
  26374. const properties = builder.getNodeProperties( this );
  26375. const { uvNode, storeNode, depthNode } = properties;
  26376. const textureProperty = super.generate( builder, 'property' );
  26377. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  26378. const storeSnippet = storeNode.build( builder, 'vec4' );
  26379. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  26380. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  26381. builder.addLineFlowCode( snippet, this );
  26382. }
  26383. clone() {
  26384. const newNode = super.clone();
  26385. newNode.storeNode = this.storeNode;
  26386. newNode.mipLevel = this.mipLevel;
  26387. return newNode;
  26388. }
  26389. }
  26390. /**
  26391. * TSL function for creating a storage texture node.
  26392. *
  26393. * @tsl
  26394. * @function
  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. * @returns {StorageTextureNode}
  26399. */
  26400. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  26401. /**
  26402. * TODO: Explain difference to `storageTexture()`.
  26403. *
  26404. * @tsl
  26405. * @function
  26406. * @param {StorageTexture} value - The storage texture.
  26407. * @param {Node<vec2|vec3>} uvNode - The uv node.
  26408. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26409. * @returns {StorageTextureNode}
  26410. */
  26411. const textureStore = ( value, uvNode, storeNode ) => {
  26412. const node = storageTexture( value, uvNode, storeNode );
  26413. if ( storeNode !== null ) node.toStack();
  26414. return node;
  26415. };
  26416. const normal = Fn( ( { texture, uv } ) => {
  26417. const epsilon = 0.0001;
  26418. const ret = vec3().toVar();
  26419. If( uv.x.lessThan( epsilon ), () => {
  26420. ret.assign( vec3( 1, 0, 0 ) );
  26421. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  26422. ret.assign( vec3( 0, 1, 0 ) );
  26423. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  26424. ret.assign( vec3( 0, 0, 1 ) );
  26425. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  26426. ret.assign( vec3( -1, 0, 0 ) );
  26427. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  26428. ret.assign( vec3( 0, -1, 0 ) );
  26429. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  26430. ret.assign( vec3( 0, 0, -1 ) );
  26431. } ).Else( () => {
  26432. const step = 0.01;
  26433. 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 );
  26434. 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 );
  26435. 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 );
  26436. ret.assign( vec3( x, y, z ) );
  26437. } );
  26438. return ret.normalize();
  26439. } );
  26440. /**
  26441. * This type of uniform node represents a 3D texture.
  26442. *
  26443. * @augments TextureNode
  26444. */
  26445. class Texture3DNode extends TextureNode {
  26446. static get type() {
  26447. return 'Texture3DNode';
  26448. }
  26449. /**
  26450. * Constructs a new 3D texture node.
  26451. *
  26452. * @param {Data3DTexture} value - The 3D texture.
  26453. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  26454. * @param {?Node<int>} [levelNode=null] - The level node.
  26455. */
  26456. constructor( value, uvNode = null, levelNode = null ) {
  26457. super( value, uvNode, levelNode );
  26458. /**
  26459. * This flag can be used for type testing.
  26460. *
  26461. * @type {boolean}
  26462. * @readonly
  26463. * @default true
  26464. */
  26465. this.isTexture3DNode = true;
  26466. }
  26467. /**
  26468. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  26469. *
  26470. * @param {NodeBuilder} builder - The current node builder.
  26471. * @return {string} The input type.
  26472. */
  26473. getInputType( /*builder*/ ) {
  26474. return 'texture3D';
  26475. }
  26476. /**
  26477. * Returns a default uv node which is in context of 3D textures a three-dimensional
  26478. * uv node.
  26479. *
  26480. * @return {Node<vec3>} The default uv node.
  26481. */
  26482. getDefaultUV() {
  26483. return vec3( 0.5, 0.5, 0.5 );
  26484. }
  26485. /**
  26486. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  26487. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  26488. *
  26489. * @param {boolean} value - The update toggle.
  26490. */
  26491. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  26492. /**
  26493. * Overwrites the default implementation to return the unmodified uv node.
  26494. *
  26495. * @param {NodeBuilder} builder - The current node builder.
  26496. * @param {Node} uvNode - The uv node to setup.
  26497. * @return {Node} The unmodified uv node.
  26498. */
  26499. setupUV( builder, uvNode ) {
  26500. const texture = this.value;
  26501. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  26502. if ( this.sampler ) {
  26503. uvNode = uvNode.flipY();
  26504. } else {
  26505. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  26506. }
  26507. }
  26508. return uvNode;
  26509. }
  26510. /**
  26511. * Generates the uv code snippet.
  26512. *
  26513. * @param {NodeBuilder} builder - The current node builder.
  26514. * @param {Node} uvNode - The uv node to generate code for.
  26515. * @return {string} The generated code snippet.
  26516. */
  26517. generateUV( builder, uvNode ) {
  26518. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  26519. }
  26520. /**
  26521. * Generates the offset code snippet.
  26522. *
  26523. * @param {NodeBuilder} builder - The current node builder.
  26524. * @param {Node} offsetNode - The offset node to generate code for.
  26525. * @return {string} The generated code snippet.
  26526. */
  26527. generateOffset( builder, offsetNode ) {
  26528. return offsetNode.build( builder, 'ivec3' );
  26529. }
  26530. /**
  26531. * TODO.
  26532. *
  26533. * @param {Node<vec3>} uvNode - The uv node .
  26534. * @return {Node<vec3>} TODO.
  26535. */
  26536. normal( uvNode ) {
  26537. return normal( { texture: this, uv: uvNode } );
  26538. }
  26539. }
  26540. /**
  26541. * TSL function for creating a 3D texture node.
  26542. *
  26543. * @tsl
  26544. * @function
  26545. * @param {Data3DTexture} value - The 3D texture.
  26546. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26547. * @param {?Node<int>} [levelNode=null] - The level node.
  26548. * @returns {Texture3DNode}
  26549. */
  26550. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  26551. /**
  26552. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  26553. *
  26554. * @tsl
  26555. * @function
  26556. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  26557. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26558. * @param {?Node<int>} [levelNode=null] - The level node.
  26559. * @param {?Node<float>} [biasNode=null] - The bias node.
  26560. * @returns {TextureNode}
  26561. */
  26562. const texture3DLoad = ( ...params ) => texture3D( ...params ).setSampler( false );
  26563. /**
  26564. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  26565. *
  26566. * @tsl
  26567. * @function
  26568. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  26569. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26570. * @param {?Node<int>} [levelNode=null] - The level node.
  26571. * @returns {TextureNode}
  26572. */
  26573. const texture3DLevel = ( value, uvNode, levelNode ) => texture3D( value, uvNode ).level( levelNode );
  26574. /**
  26575. * A special type of reference node that allows to link values in
  26576. * `userData` fields to node objects.
  26577. * ```js
  26578. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  26579. *
  26580. * const material = new THREE.SpriteNodeMaterial();
  26581. * material.rotationNode = userData( 'rotation', 'float' );
  26582. * ```
  26583. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  26584. * will automatically be updated when the `rotation` user data field changes.
  26585. *
  26586. * @augments ReferenceNode
  26587. */
  26588. class UserDataNode extends ReferenceNode {
  26589. static get type() {
  26590. return 'UserDataNode';
  26591. }
  26592. /**
  26593. * Constructs a new user data node.
  26594. *
  26595. * @param {string} property - The property name that should be referenced by the node.
  26596. * @param {string} inputType - The node data type of the reference.
  26597. * @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.
  26598. */
  26599. constructor( property, inputType, userData = null ) {
  26600. super( property, inputType, userData );
  26601. /**
  26602. * A reference to the `userData` object. If not provided, the `userData`
  26603. * property of the 3D object that uses the node material is evaluated.
  26604. *
  26605. * @type {?Object}
  26606. * @default null
  26607. */
  26608. this.userData = userData;
  26609. }
  26610. /**
  26611. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  26612. * `userData` field.
  26613. *
  26614. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  26615. * @return {Object} A reference to the `userData` field.
  26616. */
  26617. updateReference( state ) {
  26618. this.reference = this.userData !== null ? this.userData : state.object.userData;
  26619. return this.reference;
  26620. }
  26621. }
  26622. /**
  26623. * TSL function for creating a user data node.
  26624. *
  26625. * @tsl
  26626. * @function
  26627. * @param {string} name - The property name that should be referenced by the node.
  26628. * @param {string} inputType - The node data type of the reference.
  26629. * @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.
  26630. * @returns {UserDataNode}
  26631. */
  26632. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  26633. const _objectData = new WeakMap();
  26634. /**
  26635. * A node for representing motion or velocity vectors. Foundation
  26636. * for advanced post processing effects like motion blur or TRAA.
  26637. *
  26638. * The node keeps track of the model, view and projection matrices
  26639. * of the previous frame and uses them to compute offsets in NDC space.
  26640. * These offsets represent the final velocity.
  26641. *
  26642. * @augments TempNode
  26643. */
  26644. class VelocityNode extends TempNode {
  26645. static get type() {
  26646. return 'VelocityNode';
  26647. }
  26648. /**
  26649. * Constructs a new vertex color node.
  26650. */
  26651. constructor() {
  26652. super( 'vec2' );
  26653. /**
  26654. * The current projection matrix.
  26655. *
  26656. * @type {?Matrix4}
  26657. * @default null
  26658. */
  26659. this.projectionMatrix = null;
  26660. /**
  26661. * Overwritten since velocity nodes are updated per object.
  26662. *
  26663. * @type {string}
  26664. * @default 'object'
  26665. */
  26666. this.updateType = NodeUpdateType.OBJECT;
  26667. /**
  26668. * Overwritten since velocity nodes save data after the update.
  26669. *
  26670. * @type {string}
  26671. * @default 'object'
  26672. */
  26673. this.updateAfterType = NodeUpdateType.OBJECT;
  26674. /**
  26675. * Uniform node representing the previous model matrix in world space.
  26676. *
  26677. * @type {UniformNode<mat4>}
  26678. * @default null
  26679. */
  26680. this.previousModelWorldMatrix = uniform( new Matrix4() );
  26681. /**
  26682. * Uniform node representing the previous projection matrix.
  26683. *
  26684. * @type {UniformNode<mat4>}
  26685. * @default null
  26686. */
  26687. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  26688. /**
  26689. * Uniform node representing the previous view matrix.
  26690. *
  26691. * @type {UniformNode<mat4>}
  26692. * @default null
  26693. */
  26694. this.previousCameraViewMatrix = uniform( new Matrix4() );
  26695. }
  26696. /**
  26697. * Sets the given projection matrix.
  26698. *
  26699. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  26700. */
  26701. setProjectionMatrix( projectionMatrix ) {
  26702. this.projectionMatrix = projectionMatrix;
  26703. }
  26704. /**
  26705. * Updates velocity specific uniforms.
  26706. *
  26707. * @param {NodeFrame} frame - A reference to the current node frame.
  26708. */
  26709. update( { frameId, camera, object } ) {
  26710. const previousModelMatrix = getPreviousMatrix( object );
  26711. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  26712. //
  26713. const cameraData = getData( camera );
  26714. if ( cameraData.frameId !== frameId ) {
  26715. cameraData.frameId = frameId;
  26716. if ( cameraData.previousProjectionMatrix === undefined ) {
  26717. cameraData.previousProjectionMatrix = new Matrix4();
  26718. cameraData.previousCameraViewMatrix = new Matrix4();
  26719. cameraData.currentProjectionMatrix = new Matrix4();
  26720. cameraData.currentCameraViewMatrix = new Matrix4();
  26721. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  26722. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  26723. } else {
  26724. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  26725. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  26726. }
  26727. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  26728. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  26729. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  26730. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  26731. }
  26732. }
  26733. /**
  26734. * Overwritten to updated velocity specific uniforms.
  26735. *
  26736. * @param {NodeFrame} frame - A reference to the current node frame.
  26737. */
  26738. updateAfter( { object } ) {
  26739. getPreviousMatrix( object ).copy( object.matrixWorld );
  26740. }
  26741. /**
  26742. * Implements the velocity computation based on the previous and current vertex data.
  26743. *
  26744. * @param {NodeBuilder} builder - A reference to the current node builder.
  26745. * @return {Node<vec2>} The motion vector.
  26746. */
  26747. setup( /*builder*/ ) {
  26748. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  26749. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  26750. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  26751. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  26752. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  26753. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  26754. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  26755. return velocity;
  26756. }
  26757. }
  26758. function getData( object ) {
  26759. let objectData = _objectData.get( object );
  26760. if ( objectData === undefined ) {
  26761. objectData = {};
  26762. _objectData.set( object, objectData );
  26763. }
  26764. return objectData;
  26765. }
  26766. function getPreviousMatrix( object, index = 0 ) {
  26767. const objectData = getData( object );
  26768. let matrix = objectData[ index ];
  26769. if ( matrix === undefined ) {
  26770. objectData[ index ] = matrix = new Matrix4();
  26771. objectData[ index ].copy( object.matrixWorld );
  26772. }
  26773. return matrix;
  26774. }
  26775. /**
  26776. * TSL object that represents the velocity of a render pass.
  26777. *
  26778. * @tsl
  26779. * @type {VelocityNode}
  26780. */
  26781. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  26782. /**
  26783. * Computes a grayscale value for the given RGB color value.
  26784. *
  26785. * @tsl
  26786. * @function
  26787. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  26788. * @return {Node<vec3>} The grayscale color.
  26789. */
  26790. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  26791. return luminance( color.rgb );
  26792. } );
  26793. /**
  26794. * Super-saturates or desaturates the given RGB color.
  26795. *
  26796. * @tsl
  26797. * @function
  26798. * @param {Node<vec3>} color - The input color.
  26799. * @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.
  26800. * @return {Node<vec3>} The saturated color.
  26801. */
  26802. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26803. return adjustment.mix( luminance( color.rgb ), color.rgb );
  26804. } );
  26805. /**
  26806. * Selectively enhance the intensity of less saturated RGB colors. Can result
  26807. * in a more natural and visually appealing image with enhanced color depth
  26808. * compared to {@link ColorAdjustment#saturation}.
  26809. *
  26810. * @tsl
  26811. * @function
  26812. * @param {Node<vec3>} color - The input color.
  26813. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  26814. * @return {Node<vec3>} The updated color.
  26815. */
  26816. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26817. const average = add( color.r, color.g, color.b ).div( 3.0 );
  26818. const mx = color.r.max( color.g.max( color.b ) );
  26819. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  26820. return mix( color.rgb, mx, amt );
  26821. } );
  26822. /**
  26823. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  26824. *
  26825. * @tsl
  26826. * @function
  26827. * @param {Node<vec3>} color - The input color.
  26828. * @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.
  26829. * @return {Node<vec3>} The updated color.
  26830. */
  26831. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26832. const k = vec3( 0.57735, 0.57735, 0.57735 );
  26833. const cosAngle = adjustment.cos();
  26834. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  26835. } );
  26836. /**
  26837. * Computes the luminance for the given RGB color value.
  26838. *
  26839. * @tsl
  26840. * @function
  26841. * @param {Node<vec3>} color - The color value to compute the luminance for.
  26842. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  26843. * @return {Node<float>} The luminance.
  26844. */
  26845. const luminance = (
  26846. color,
  26847. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  26848. ) => dot( color, luminanceCoefficients );
  26849. /**
  26850. * Color Decision List (CDL) v1.2
  26851. *
  26852. * Compact representation of color grading information, defined by slope, offset, power, and
  26853. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  26854. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  26855. *
  26856. * @tsl
  26857. * @function
  26858. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  26859. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  26860. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  26861. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  26862. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  26863. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  26864. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  26865. *
  26866. * References:
  26867. * - ASC CDL v1.2
  26868. * - {@link https://blender.stackexchange.com/a/55239/43930}
  26869. * - {@link https://docs.acescentral.com/specifications/acescc/}
  26870. */
  26871. const cdl = /*@__PURE__*/ Fn( ( [
  26872. color,
  26873. slope = vec3( 1 ),
  26874. offset = vec3( 0 ),
  26875. power = vec3( 1 ),
  26876. saturation = float( 1 ),
  26877. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  26878. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  26879. ] ) => {
  26880. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  26881. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  26882. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  26883. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  26884. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  26885. const pv = v.pow( power ).toVar();
  26886. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  26887. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  26888. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  26889. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  26890. return vec4( v.rgb, color.a );
  26891. } );
  26892. /**
  26893. * Represents a posterize effect which reduces the number of colors
  26894. * in an image, resulting in a more blocky and stylized appearance.
  26895. *
  26896. * @augments TempNode
  26897. */
  26898. class PosterizeNode extends TempNode {
  26899. static get type() {
  26900. return 'PosterizeNode';
  26901. }
  26902. /**
  26903. * Constructs a new posterize node.
  26904. *
  26905. * @param {Node} sourceNode - The input color.
  26906. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  26907. */
  26908. constructor( sourceNode, stepsNode ) {
  26909. super();
  26910. /**
  26911. * The input color.
  26912. *
  26913. * @type {Node}
  26914. */
  26915. this.sourceNode = sourceNode;
  26916. /**
  26917. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  26918. *
  26919. * @type {Node}
  26920. */
  26921. this.stepsNode = stepsNode;
  26922. }
  26923. setup() {
  26924. const { sourceNode, stepsNode } = this;
  26925. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  26926. }
  26927. }
  26928. /**
  26929. * TSL function for creating a posterize node.
  26930. *
  26931. * @tsl
  26932. * @function
  26933. * @param {Node} sourceNode - The input color.
  26934. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  26935. * @returns {PosterizeNode}
  26936. */
  26937. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  26938. const _size = /*@__PURE__*/ new Vector2();
  26939. /**
  26940. * Represents the texture of a pass node.
  26941. *
  26942. * @augments TextureNode
  26943. */
  26944. class PassTextureNode extends TextureNode {
  26945. static get type() {
  26946. return 'PassTextureNode';
  26947. }
  26948. /**
  26949. * Constructs a new pass texture node.
  26950. *
  26951. * @param {PassNode} passNode - The pass node.
  26952. * @param {Texture} texture - The output texture.
  26953. */
  26954. constructor( passNode, texture ) {
  26955. super( texture );
  26956. /**
  26957. * A reference to the pass node.
  26958. *
  26959. * @type {PassNode}
  26960. */
  26961. this.passNode = passNode;
  26962. this.setUpdateMatrix( false );
  26963. }
  26964. setup( builder ) {
  26965. this.passNode.build( builder );
  26966. return super.setup( builder );
  26967. }
  26968. clone() {
  26969. return new this.constructor( this.passNode, this.value );
  26970. }
  26971. }
  26972. /**
  26973. * An extension of `PassTextureNode` which allows to manage more than one
  26974. * internal texture. Relevant for the `getPreviousTexture()` related API.
  26975. *
  26976. * @augments PassTextureNode
  26977. */
  26978. class PassMultipleTextureNode extends PassTextureNode {
  26979. static get type() {
  26980. return 'PassMultipleTextureNode';
  26981. }
  26982. /**
  26983. * Constructs a new pass texture node.
  26984. *
  26985. * @param {PassNode} passNode - The pass node.
  26986. * @param {string} textureName - The output texture name.
  26987. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  26988. */
  26989. constructor( passNode, textureName, previousTexture = false ) {
  26990. // null is passed to the super call since this class does not
  26991. // use an external texture for rendering pass data into. Instead
  26992. // the texture is managed by the pass node itself
  26993. super( passNode, null );
  26994. /**
  26995. * The output texture name.
  26996. *
  26997. * @type {string}
  26998. */
  26999. this.textureName = textureName;
  27000. /**
  27001. * Whether previous frame data should be used or not.
  27002. *
  27003. * @type {boolean}
  27004. */
  27005. this.previousTexture = previousTexture;
  27006. }
  27007. /**
  27008. * Updates the texture reference of this node.
  27009. */
  27010. updateTexture() {
  27011. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  27012. }
  27013. setup( builder ) {
  27014. this.updateTexture();
  27015. return super.setup( builder );
  27016. }
  27017. clone() {
  27018. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  27019. newNode.uvNode = this.uvNode;
  27020. newNode.levelNode = this.levelNode;
  27021. newNode.biasNode = this.biasNode;
  27022. newNode.sampler = this.sampler;
  27023. newNode.depthNode = this.depthNode;
  27024. newNode.compareNode = this.compareNode;
  27025. newNode.gradNode = this.gradNode;
  27026. newNode.offsetNode = this.offsetNode;
  27027. return newNode;
  27028. }
  27029. }
  27030. /**
  27031. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  27032. * This pass produces a render for the given scene and camera and can provide multiple outputs
  27033. * via MRT for further processing.
  27034. *
  27035. * ```js
  27036. * const postProcessing = new PostProcessing( renderer );
  27037. *
  27038. * const scenePass = pass( scene, camera );
  27039. *
  27040. * postProcessing.outputNode = scenePass;
  27041. * ```
  27042. *
  27043. * @augments TempNode
  27044. */
  27045. class PassNode extends TempNode {
  27046. static get type() {
  27047. return 'PassNode';
  27048. }
  27049. /**
  27050. * Constructs a new pass node.
  27051. *
  27052. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  27053. * @param {Scene} scene - A reference to the scene.
  27054. * @param {Camera} camera - A reference to the camera.
  27055. * @param {Object} options - Options for the internal render target.
  27056. */
  27057. constructor( scope, scene, camera, options = {} ) {
  27058. super( 'vec4' );
  27059. /**
  27060. * The scope of the pass. The scope determines whether the node outputs color or depth.
  27061. *
  27062. * @type {('color'|'depth')}
  27063. */
  27064. this.scope = scope;
  27065. /**
  27066. * A reference to the scene.
  27067. *
  27068. * @type {Scene}
  27069. */
  27070. this.scene = scene;
  27071. /**
  27072. * A reference to the camera.
  27073. *
  27074. * @type {Camera}
  27075. */
  27076. this.camera = camera;
  27077. /**
  27078. * Options for the internal render target.
  27079. *
  27080. * @type {Object}
  27081. */
  27082. this.options = options;
  27083. /**
  27084. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  27085. *
  27086. * @private
  27087. * @type {number}
  27088. * @default 1
  27089. */
  27090. this._pixelRatio = 1;
  27091. /**
  27092. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  27093. * @private
  27094. * @type {number}
  27095. * @default 1
  27096. */
  27097. this._width = 1;
  27098. /**
  27099. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  27100. * @private
  27101. * @type {number}
  27102. * @default 1
  27103. */
  27104. this._height = 1;
  27105. const depthTexture = new DepthTexture();
  27106. depthTexture.isRenderTargetTexture = true;
  27107. //depthTexture.type = FloatType;
  27108. depthTexture.name = 'depth';
  27109. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  27110. renderTarget.texture.name = 'output';
  27111. renderTarget.depthTexture = depthTexture;
  27112. /**
  27113. * The pass's render target.
  27114. *
  27115. * @type {RenderTarget}
  27116. */
  27117. this.renderTarget = renderTarget;
  27118. /**
  27119. * An optional override material for the pass.
  27120. *
  27121. * @type {Material|null}
  27122. */
  27123. this.overrideMaterial = null;
  27124. /**
  27125. * Whether the pass is transparent.
  27126. *
  27127. * @type {boolean}
  27128. * @default false
  27129. */
  27130. this.transparent = true;
  27131. /**
  27132. * Whether the pass is opaque.
  27133. *
  27134. * @type {boolean}
  27135. * @default true
  27136. */
  27137. this.opaque = true;
  27138. /**
  27139. * An optional global context for the pass.
  27140. *
  27141. * @type {ContextNode|null}
  27142. */
  27143. this.contextNode = null;
  27144. /**
  27145. * A cache for the context node.
  27146. *
  27147. * @private
  27148. * @type {?Object}
  27149. * @default null
  27150. */
  27151. this._contextNodeCache = null;
  27152. /**
  27153. * A dictionary holding the internal result textures.
  27154. *
  27155. * @private
  27156. * @type {Object<string, Texture>}
  27157. */
  27158. this._textures = {
  27159. output: renderTarget.texture,
  27160. depth: depthTexture
  27161. };
  27162. /**
  27163. * A dictionary holding the internal texture nodes.
  27164. *
  27165. * @private
  27166. * @type {Object<string, TextureNode>}
  27167. */
  27168. this._textureNodes = {};
  27169. /**
  27170. * A dictionary holding the internal depth nodes.
  27171. *
  27172. * @private
  27173. * @type {Object}
  27174. */
  27175. this._linearDepthNodes = {};
  27176. /**
  27177. * A dictionary holding the internal viewZ nodes.
  27178. *
  27179. * @private
  27180. * @type {Object}
  27181. */
  27182. this._viewZNodes = {};
  27183. /**
  27184. * A dictionary holding the texture data of the previous frame.
  27185. * Used for computing velocity/motion vectors.
  27186. *
  27187. * @private
  27188. * @type {Object<string, Texture>}
  27189. */
  27190. this._previousTextures = {};
  27191. /**
  27192. * A dictionary holding the texture nodes of the previous frame.
  27193. * Used for computing velocity/motion vectors.
  27194. *
  27195. * @private
  27196. * @type {Object<string, TextureNode>}
  27197. */
  27198. this._previousTextureNodes = {};
  27199. /**
  27200. * The `near` property of the camera as a uniform.
  27201. *
  27202. * @private
  27203. * @type {UniformNode}
  27204. */
  27205. this._cameraNear = uniform( 0 );
  27206. /**
  27207. * The `far` property of the camera as a uniform.
  27208. *
  27209. * @private
  27210. * @type {UniformNode}
  27211. */
  27212. this._cameraFar = uniform( 0 );
  27213. /**
  27214. * A MRT node configuring the MRT settings.
  27215. *
  27216. * @private
  27217. * @type {?MRTNode}
  27218. * @default null
  27219. */
  27220. this._mrt = null;
  27221. /**
  27222. * Layer object for configuring the camera that is used
  27223. * to produce the pass.
  27224. *
  27225. * @private
  27226. * @type {?Layers}
  27227. * @default null
  27228. */
  27229. this._layers = null;
  27230. /**
  27231. * Scales the resolution of the internal render target.
  27232. *
  27233. * @private
  27234. * @type {number}
  27235. * @default 1
  27236. */
  27237. this._resolutionScale = 1;
  27238. /**
  27239. * Custom viewport definition.
  27240. *
  27241. * @private
  27242. * @type {?Vector4}
  27243. * @default null
  27244. */
  27245. this._viewport = null;
  27246. /**
  27247. * Custom scissor definition.
  27248. *
  27249. * @private
  27250. * @type {?Vector4}
  27251. * @default null
  27252. */
  27253. this._scissor = null;
  27254. /**
  27255. * This flag can be used for type testing.
  27256. *
  27257. * @type {boolean}
  27258. * @readonly
  27259. * @default true
  27260. */
  27261. this.isPassNode = true;
  27262. /**
  27263. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  27264. * scene once per frame in its {@link PassNode#updateBefore} method.
  27265. *
  27266. * @type {string}
  27267. * @default 'frame'
  27268. */
  27269. this.updateBeforeType = NodeUpdateType.FRAME;
  27270. /**
  27271. * This flag is used for global cache.
  27272. *
  27273. * @type {boolean}
  27274. * @default true
  27275. */
  27276. this.global = true;
  27277. }
  27278. /**
  27279. * Sets the resolution scale for the pass.
  27280. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  27281. *
  27282. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  27283. * @return {PassNode} A reference to this pass.
  27284. */
  27285. setResolutionScale( resolutionScale ) {
  27286. this._resolutionScale = resolutionScale;
  27287. return this;
  27288. }
  27289. /**
  27290. * Gets the current resolution scale of the pass.
  27291. *
  27292. * @return {number} The current resolution scale. A value of `1` means full resolution.
  27293. */
  27294. getResolutionScale() {
  27295. return this._resolutionScale;
  27296. }
  27297. /**
  27298. * Sets the resolution for the pass.
  27299. * The resolution is a factor that is multiplied with the renderer's width and height.
  27300. *
  27301. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  27302. * @return {PassNode} A reference to this pass.
  27303. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  27304. */
  27305. setResolution( resolution ) { // @deprecated, r181
  27306. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  27307. return this.setResolutionScale( resolution );
  27308. }
  27309. /**
  27310. * Gets the current resolution of the pass.
  27311. *
  27312. * @return {number} The current resolution. A value of `1` means full resolution.
  27313. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  27314. */
  27315. getResolution() { // @deprecated, r181
  27316. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  27317. return this.getResolutionScale();
  27318. }
  27319. /**
  27320. * Sets the layer configuration that should be used when rendering the pass.
  27321. *
  27322. * @param {Layers} layers - The layers object to set.
  27323. * @return {PassNode} A reference to this pass.
  27324. */
  27325. setLayers( layers ) {
  27326. this._layers = layers;
  27327. return this;
  27328. }
  27329. /**
  27330. * Gets the current layer configuration of the pass.
  27331. *
  27332. * @return {?Layers} .
  27333. */
  27334. getLayers() {
  27335. return this._layers;
  27336. }
  27337. /**
  27338. * Sets the given MRT node to setup MRT for this pass.
  27339. *
  27340. * @param {MRTNode} mrt - The MRT object.
  27341. * @return {PassNode} A reference to this pass.
  27342. */
  27343. setMRT( mrt ) {
  27344. this._mrt = mrt;
  27345. return this;
  27346. }
  27347. /**
  27348. * Returns the current MRT node.
  27349. *
  27350. * @return {MRTNode} The current MRT node.
  27351. */
  27352. getMRT() {
  27353. return this._mrt;
  27354. }
  27355. /**
  27356. * Returns the texture for the given output name.
  27357. *
  27358. * @param {string} name - The output name to get the texture for.
  27359. * @return {Texture} The texture.
  27360. */
  27361. getTexture( name ) {
  27362. let texture = this._textures[ name ];
  27363. if ( texture === undefined ) {
  27364. const refTexture = this.renderTarget.texture;
  27365. texture = refTexture.clone();
  27366. texture.name = name;
  27367. this._textures[ name ] = texture;
  27368. this.renderTarget.textures.push( texture );
  27369. }
  27370. return texture;
  27371. }
  27372. /**
  27373. * Returns the texture holding the data of the previous frame for the given output name.
  27374. *
  27375. * @param {string} name - The output name to get the texture for.
  27376. * @return {Texture} The texture holding the data of the previous frame.
  27377. */
  27378. getPreviousTexture( name ) {
  27379. let texture = this._previousTextures[ name ];
  27380. if ( texture === undefined ) {
  27381. texture = this.getTexture( name ).clone();
  27382. this._previousTextures[ name ] = texture;
  27383. }
  27384. return texture;
  27385. }
  27386. /**
  27387. * Switches current and previous textures for the given output name.
  27388. *
  27389. * @param {string} name - The output name.
  27390. */
  27391. toggleTexture( name ) {
  27392. const prevTexture = this._previousTextures[ name ];
  27393. if ( prevTexture !== undefined ) {
  27394. const texture = this._textures[ name ];
  27395. const index = this.renderTarget.textures.indexOf( texture );
  27396. this.renderTarget.textures[ index ] = prevTexture;
  27397. this._textures[ name ] = prevTexture;
  27398. this._previousTextures[ name ] = texture;
  27399. this._textureNodes[ name ].updateTexture();
  27400. this._previousTextureNodes[ name ].updateTexture();
  27401. }
  27402. }
  27403. /**
  27404. * Returns the texture node for the given output name.
  27405. *
  27406. * @param {string} [name='output'] - The output name to get the texture node for.
  27407. * @return {TextureNode} The texture node.
  27408. */
  27409. getTextureNode( name = 'output' ) {
  27410. let textureNode = this._textureNodes[ name ];
  27411. if ( textureNode === undefined ) {
  27412. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  27413. textureNode.updateTexture();
  27414. this._textureNodes[ name ] = textureNode;
  27415. }
  27416. return textureNode;
  27417. }
  27418. /**
  27419. * Returns the previous texture node for the given output name.
  27420. *
  27421. * @param {string} [name='output'] - The output name to get the previous texture node for.
  27422. * @return {TextureNode} The previous texture node.
  27423. */
  27424. getPreviousTextureNode( name = 'output' ) {
  27425. let textureNode = this._previousTextureNodes[ name ];
  27426. if ( textureNode === undefined ) {
  27427. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  27428. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  27429. textureNode.updateTexture();
  27430. this._previousTextureNodes[ name ] = textureNode;
  27431. }
  27432. return textureNode;
  27433. }
  27434. /**
  27435. * Returns a viewZ node of this pass.
  27436. *
  27437. * @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.
  27438. * @return {Node} The viewZ node.
  27439. */
  27440. getViewZNode( name = 'depth' ) {
  27441. let viewZNode = this._viewZNodes[ name ];
  27442. if ( viewZNode === undefined ) {
  27443. const cameraNear = this._cameraNear;
  27444. const cameraFar = this._cameraFar;
  27445. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  27446. }
  27447. return viewZNode;
  27448. }
  27449. /**
  27450. * Returns a linear depth node of this pass.
  27451. *
  27452. * @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.
  27453. * @return {Node} The linear depth node.
  27454. */
  27455. getLinearDepthNode( name = 'depth' ) {
  27456. let linearDepthNode = this._linearDepthNodes[ name ];
  27457. if ( linearDepthNode === undefined ) {
  27458. const cameraNear = this._cameraNear;
  27459. const cameraFar = this._cameraFar;
  27460. const viewZNode = this.getViewZNode( name );
  27461. // TODO: just if ( builder.camera.isPerspectiveCamera )
  27462. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  27463. }
  27464. return linearDepthNode;
  27465. }
  27466. /**
  27467. * Precompiles the pass.
  27468. *
  27469. * Note that this method must be called after the pass configuration is complete.
  27470. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  27471. *
  27472. * @async
  27473. * @param {Renderer} renderer - The renderer.
  27474. * @return {Promise} A Promise that resolves when the compile has been finished.
  27475. * @see {@link Renderer#compileAsync}
  27476. */
  27477. async compileAsync( renderer ) {
  27478. const currentRenderTarget = renderer.getRenderTarget();
  27479. const currentMRT = renderer.getMRT();
  27480. renderer.setRenderTarget( this.renderTarget );
  27481. renderer.setMRT( this._mrt );
  27482. await renderer.compileAsync( this.scene, this.camera );
  27483. renderer.setRenderTarget( currentRenderTarget );
  27484. renderer.setMRT( currentMRT );
  27485. }
  27486. setup( { renderer } ) {
  27487. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  27488. this.renderTarget.texture.type = renderer.getColorBufferType();
  27489. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  27490. }
  27491. updateBefore( frame ) {
  27492. const { renderer } = frame;
  27493. const { scene } = this;
  27494. let camera;
  27495. let pixelRatio;
  27496. const outputRenderTarget = renderer.getOutputRenderTarget();
  27497. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  27498. pixelRatio = 1;
  27499. camera = renderer.xr.getCamera();
  27500. renderer.xr.updateCamera( camera );
  27501. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  27502. } else {
  27503. camera = this.camera;
  27504. pixelRatio = renderer.getPixelRatio();
  27505. renderer.getSize( _size );
  27506. }
  27507. this._pixelRatio = pixelRatio;
  27508. this.setSize( _size.width, _size.height );
  27509. const currentRenderTarget = renderer.getRenderTarget();
  27510. const currentMRT = renderer.getMRT();
  27511. const currentAutoClear = renderer.autoClear;
  27512. const currentTransparent = renderer.transparent;
  27513. const currentOpaque = renderer.opaque;
  27514. const currentMask = camera.layers.mask;
  27515. const currentContextNode = renderer.contextNode;
  27516. const currentOverrideMaterial = scene.overrideMaterial;
  27517. this._cameraNear.value = camera.near;
  27518. this._cameraFar.value = camera.far;
  27519. if ( this._layers !== null ) {
  27520. camera.layers.mask = this._layers.mask;
  27521. }
  27522. for ( const name in this._previousTextures ) {
  27523. this.toggleTexture( name );
  27524. }
  27525. if ( this.overrideMaterial !== null ) {
  27526. scene.overrideMaterial = this.overrideMaterial;
  27527. }
  27528. renderer.setRenderTarget( this.renderTarget );
  27529. renderer.setMRT( this._mrt );
  27530. renderer.autoClear = true;
  27531. renderer.transparent = this.transparent;
  27532. renderer.opaque = this.opaque;
  27533. if ( this.contextNode !== null ) {
  27534. if ( this._contextNodeCache === null || this._contextNodeCache.version !== this.version ) {
  27535. this._contextNodeCache = {
  27536. version: this.version,
  27537. context: context( { ...renderer.contextNode.getFlowContextData(), ...this.contextNode.getFlowContextData() } )
  27538. };
  27539. }
  27540. renderer.contextNode = this._contextNodeCache.context;
  27541. }
  27542. const currentSceneName = scene.name;
  27543. scene.name = this.name ? this.name : scene.name;
  27544. renderer.render( scene, camera );
  27545. scene.name = currentSceneName;
  27546. scene.overrideMaterial = currentOverrideMaterial;
  27547. renderer.setRenderTarget( currentRenderTarget );
  27548. renderer.setMRT( currentMRT );
  27549. renderer.autoClear = currentAutoClear;
  27550. renderer.transparent = currentTransparent;
  27551. renderer.opaque = currentOpaque;
  27552. renderer.contextNode = currentContextNode;
  27553. camera.layers.mask = currentMask;
  27554. }
  27555. /**
  27556. * Sets the size of the pass's render target. Honors the pixel ratio.
  27557. *
  27558. * @param {number} width - The width to set.
  27559. * @param {number} height - The height to set.
  27560. */
  27561. setSize( width, height ) {
  27562. this._width = width;
  27563. this._height = height;
  27564. const effectiveWidth = Math.floor( this._width * this._pixelRatio * this._resolutionScale );
  27565. const effectiveHeight = Math.floor( this._height * this._pixelRatio * this._resolutionScale );
  27566. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  27567. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  27568. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  27569. }
  27570. /**
  27571. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  27572. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  27573. * with `null` as the single argument.
  27574. *
  27575. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  27576. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  27577. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  27578. * @param {number} width - The width of the scissor box in logical pixel unit.
  27579. * @param {number} height - The height of the scissor box in logical pixel unit.
  27580. */
  27581. setScissor( x, y, width, height ) {
  27582. if ( x === null ) {
  27583. this._scissor = null;
  27584. } else {
  27585. if ( this._scissor === null ) this._scissor = new Vector4();
  27586. if ( x.isVector4 ) {
  27587. this._scissor.copy( x );
  27588. } else {
  27589. this._scissor.set( x, y, width, height );
  27590. }
  27591. this._scissor.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  27592. }
  27593. }
  27594. /**
  27595. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  27596. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  27597. * with `null` as the single argument.
  27598. *
  27599. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  27600. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  27601. * @param {number} width - The width of the viewport in logical pixel unit.
  27602. * @param {number} height - The height of the viewport in logical pixel unit.
  27603. */
  27604. setViewport( x, y, width, height ) {
  27605. if ( x === null ) {
  27606. this._viewport = null;
  27607. } else {
  27608. if ( this._viewport === null ) this._viewport = new Vector4();
  27609. if ( x.isVector4 ) {
  27610. this._viewport.copy( x );
  27611. } else {
  27612. this._viewport.set( x, y, width, height );
  27613. }
  27614. this._viewport.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  27615. }
  27616. }
  27617. /**
  27618. * Sets the pixel ratio the pass's render target and updates the size.
  27619. *
  27620. * @param {number} pixelRatio - The pixel ratio to set.
  27621. */
  27622. setPixelRatio( pixelRatio ) {
  27623. this._pixelRatio = pixelRatio;
  27624. this.setSize( this._width, this._height );
  27625. }
  27626. /**
  27627. * Frees internal resources. Should be called when the node is no longer in use.
  27628. */
  27629. dispose() {
  27630. this.renderTarget.dispose();
  27631. }
  27632. }
  27633. /**
  27634. * @static
  27635. * @type {'color'}
  27636. * @default 'color'
  27637. */
  27638. PassNode.COLOR = 'color';
  27639. /**
  27640. * @static
  27641. * @type {'depth'}
  27642. * @default 'depth'
  27643. */
  27644. PassNode.DEPTH = 'depth';
  27645. /**
  27646. * TSL function for creating a pass node.
  27647. *
  27648. * @tsl
  27649. * @function
  27650. * @param {Scene} scene - A reference to the scene.
  27651. * @param {Camera} camera - A reference to the camera.
  27652. * @param {Object} options - Options for the internal render target.
  27653. * @returns {PassNode}
  27654. */
  27655. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  27656. /**
  27657. * TSL function for creating a pass texture node.
  27658. *
  27659. * @tsl
  27660. * @function
  27661. * @param {PassNode} pass - The pass node.
  27662. * @param {Texture} texture - The output texture.
  27663. * @returns {PassTextureNode}
  27664. */
  27665. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  27666. /**
  27667. * TSL function for creating a depth pass node.
  27668. *
  27669. * @tsl
  27670. * @function
  27671. * @param {Scene} scene - A reference to the scene.
  27672. * @param {Camera} camera - A reference to the camera.
  27673. * @param {Object} options - Options for the internal render target.
  27674. * @returns {PassNode}
  27675. */
  27676. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  27677. /**
  27678. * Represents a render pass for producing a toon outline effect on compatible objects.
  27679. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  27680. * will receive the outline.
  27681. *
  27682. * ```js
  27683. * const postProcessing = new PostProcessing( renderer );
  27684. *
  27685. * const scenePass = toonOutlinePass( scene, camera );
  27686. *
  27687. * postProcessing.outputNode = scenePass;
  27688. * ```
  27689. * @augments PassNode
  27690. */
  27691. class ToonOutlinePassNode extends PassNode {
  27692. static get type() {
  27693. return 'ToonOutlinePassNode';
  27694. }
  27695. /**
  27696. * Constructs a new outline pass node.
  27697. *
  27698. * @param {Scene} scene - A reference to the scene.
  27699. * @param {Camera} camera - A reference to the camera.
  27700. * @param {Node} colorNode - Defines the outline's color.
  27701. * @param {Node} thicknessNode - Defines the outline's thickness.
  27702. * @param {Node} alphaNode - Defines the outline's alpha.
  27703. */
  27704. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  27705. super( PassNode.COLOR, scene, camera );
  27706. /**
  27707. * Defines the outline's color.
  27708. *
  27709. * @type {Node}
  27710. */
  27711. this.colorNode = colorNode;
  27712. /**
  27713. * Defines the outline's thickness.
  27714. *
  27715. * @type {Node}
  27716. */
  27717. this.thicknessNode = thicknessNode;
  27718. /**
  27719. * Defines the outline's alpha.
  27720. *
  27721. * @type {Node}
  27722. */
  27723. this.alphaNode = alphaNode;
  27724. /**
  27725. * An internal material cache.
  27726. *
  27727. * @private
  27728. * @type {WeakMap<Material, NodeMaterial>}
  27729. */
  27730. this._materialCache = new WeakMap();
  27731. /**
  27732. * The name of this pass.
  27733. *
  27734. * @type {string}
  27735. * @default 'Outline Pass'
  27736. */
  27737. this.name = 'Outline Pass';
  27738. }
  27739. updateBefore( frame ) {
  27740. const { renderer } = frame;
  27741. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  27742. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  27743. // only render outline for supported materials
  27744. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  27745. if ( material.wireframe === false ) {
  27746. const outlineMaterial = this._getOutlineMaterial( material );
  27747. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  27748. }
  27749. }
  27750. // default
  27751. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  27752. } );
  27753. super.updateBefore( frame );
  27754. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  27755. }
  27756. /**
  27757. * Creates the material used for outline rendering.
  27758. *
  27759. * @private
  27760. * @return {NodeMaterial} The outline material.
  27761. */
  27762. _createMaterial() {
  27763. const material = new NodeMaterial();
  27764. material.isMeshToonOutlineMaterial = true;
  27765. material.name = 'Toon_Outline';
  27766. material.side = BackSide;
  27767. // vertex node
  27768. const outlineNormal = normalLocal.negate();
  27769. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  27770. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  27771. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  27772. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  27773. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  27774. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  27775. // color node
  27776. material.colorNode = vec4( this.colorNode, this.alphaNode );
  27777. return material;
  27778. }
  27779. /**
  27780. * For the given toon material, this method returns a corresponding
  27781. * outline material.
  27782. *
  27783. * @private
  27784. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  27785. * @return {NodeMaterial} The outline material.
  27786. */
  27787. _getOutlineMaterial( originalMaterial ) {
  27788. let outlineMaterial = this._materialCache.get( originalMaterial );
  27789. if ( outlineMaterial === undefined ) {
  27790. outlineMaterial = this._createMaterial();
  27791. this._materialCache.set( originalMaterial, outlineMaterial );
  27792. }
  27793. return outlineMaterial;
  27794. }
  27795. }
  27796. /**
  27797. * TSL function for creating a toon outline pass node.
  27798. *
  27799. * @tsl
  27800. * @function
  27801. * @param {Scene} scene - A reference to the scene.
  27802. * @param {Camera} camera - A reference to the camera.
  27803. * @param {Color} color - Defines the outline's color.
  27804. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  27805. * @param {number} [alpha=1] - Defines the outline's alpha.
  27806. * @returns {ToonOutlinePassNode}
  27807. */
  27808. 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 ) ) );
  27809. /**
  27810. * Linear tone mapping, exposure only.
  27811. *
  27812. * @tsl
  27813. * @function
  27814. * @param {Node<vec3>} color - The color that should be tone mapped.
  27815. * @param {Node<float>} exposure - The exposure.
  27816. * @return {Node<vec3>} The tone mapped color.
  27817. */
  27818. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27819. return color.mul( exposure ).clamp();
  27820. } ).setLayout( {
  27821. name: 'linearToneMapping',
  27822. type: 'vec3',
  27823. inputs: [
  27824. { name: 'color', type: 'vec3' },
  27825. { name: 'exposure', type: 'float' }
  27826. ]
  27827. } );
  27828. /**
  27829. * Reinhard tone mapping.
  27830. *
  27831. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  27832. *
  27833. * @tsl
  27834. * @function
  27835. * @param {Node<vec3>} color - The color that should be tone mapped.
  27836. * @param {Node<float>} exposure - The exposure.
  27837. * @return {Node<vec3>} The tone mapped color.
  27838. */
  27839. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27840. color = color.mul( exposure );
  27841. return color.div( color.add( 1.0 ) ).clamp();
  27842. } ).setLayout( {
  27843. name: 'reinhardToneMapping',
  27844. type: 'vec3',
  27845. inputs: [
  27846. { name: 'color', type: 'vec3' },
  27847. { name: 'exposure', type: 'float' }
  27848. ]
  27849. } );
  27850. /**
  27851. * Cineon tone mapping.
  27852. *
  27853. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  27854. *
  27855. * @tsl
  27856. * @function
  27857. * @param {Node<vec3>} color - The color that should be tone mapped.
  27858. * @param {Node<float>} exposure - The exposure.
  27859. * @return {Node<vec3>} The tone mapped color.
  27860. */
  27861. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27862. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  27863. color = color.mul( exposure );
  27864. color = color.sub( 0.004 ).max( 0.0 );
  27865. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  27866. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  27867. return a.div( b ).pow( 2.2 );
  27868. } ).setLayout( {
  27869. name: 'cineonToneMapping',
  27870. type: 'vec3',
  27871. inputs: [
  27872. { name: 'color', type: 'vec3' },
  27873. { name: 'exposure', type: 'float' }
  27874. ]
  27875. } );
  27876. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  27877. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  27878. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  27879. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  27880. return a.div( b );
  27881. } );
  27882. /**
  27883. * ACESFilmic tone mapping.
  27884. *
  27885. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  27886. *
  27887. * @tsl
  27888. * @function
  27889. * @param {Node<vec3>} color - The color that should be tone mapped.
  27890. * @param {Node<float>} exposure - The exposure.
  27891. * @return {Node<vec3>} The tone mapped color.
  27892. */
  27893. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27894. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  27895. const ACESInputMat = mat3(
  27896. 0.59719, 0.35458, 0.04823,
  27897. 0.07600, 0.90834, 0.01566,
  27898. 0.02840, 0.13383, 0.83777
  27899. );
  27900. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  27901. const ACESOutputMat = mat3(
  27902. 1.60475, -0.53108, -0.07367,
  27903. -0.10208, 1.10813, -605e-5,
  27904. -327e-5, -0.07276, 1.07602
  27905. );
  27906. color = color.mul( exposure ).div( 0.6 );
  27907. color = ACESInputMat.mul( color );
  27908. // Apply RRT and ODT
  27909. color = RRTAndODTFit( color );
  27910. color = ACESOutputMat.mul( color );
  27911. // Clamp to [0, 1]
  27912. return color.clamp();
  27913. } ).setLayout( {
  27914. name: 'acesFilmicToneMapping',
  27915. type: 'vec3',
  27916. inputs: [
  27917. { name: 'color', type: 'vec3' },
  27918. { name: 'exposure', type: 'float' }
  27919. ]
  27920. } );
  27921. 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 ) );
  27922. 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 ) );
  27923. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  27924. const x = vec3( x_immutable ).toVar();
  27925. const x2 = vec3( x.mul( x ) ).toVar();
  27926. const x4 = vec3( x2.mul( x2 ) ).toVar();
  27927. 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 ) ) ) );
  27928. } );
  27929. /**
  27930. * AgX tone mapping.
  27931. *
  27932. * @tsl
  27933. * @function
  27934. * @param {Node<vec3>} color - The color that should be tone mapped.
  27935. * @param {Node<float>} exposure - The exposure.
  27936. * @return {Node<vec3>} The tone mapped color.
  27937. */
  27938. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27939. const colortone = vec3( color ).toVar();
  27940. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  27941. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  27942. const AgxMinEv = float( -12.47393 );
  27943. const AgxMaxEv = float( 4.026069 );
  27944. colortone.mulAssign( exposure );
  27945. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  27946. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  27947. colortone.assign( max$1( colortone, 1e-10 ) );
  27948. colortone.assign( log2( colortone ) );
  27949. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  27950. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  27951. colortone.assign( agxDefaultContrastApprox( colortone ) );
  27952. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  27953. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  27954. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  27955. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  27956. return colortone;
  27957. } ).setLayout( {
  27958. name: 'agxToneMapping',
  27959. type: 'vec3',
  27960. inputs: [
  27961. { name: 'color', type: 'vec3' },
  27962. { name: 'exposure', type: 'float' }
  27963. ]
  27964. } );
  27965. /**
  27966. * Neutral tone mapping.
  27967. *
  27968. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  27969. *
  27970. * @tsl
  27971. * @function
  27972. * @param {Node<vec3>} color - The color that should be tone mapped.
  27973. * @param {Node<float>} exposure - The exposure.
  27974. * @return {Node<vec3>} The tone mapped color.
  27975. */
  27976. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27977. const StartCompression = float( 0.8 - 0.04 );
  27978. const Desaturation = float( 0.15 );
  27979. color = color.mul( exposure );
  27980. const x = min$1( color.r, min$1( color.g, color.b ) );
  27981. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  27982. color.subAssign( offset );
  27983. const peak = max$1( color.r, max$1( color.g, color.b ) );
  27984. If( peak.lessThan( StartCompression ), () => {
  27985. return color;
  27986. } );
  27987. const d = sub( 1, StartCompression );
  27988. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  27989. color.mulAssign( newPeak.div( peak ) );
  27990. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  27991. return mix( color, vec3( newPeak ), g );
  27992. } ).setLayout( {
  27993. name: 'neutralToneMapping',
  27994. type: 'vec3',
  27995. inputs: [
  27996. { name: 'color', type: 'vec3' },
  27997. { name: 'exposure', type: 'float' }
  27998. ]
  27999. } );
  28000. /**
  28001. * This class represents native code sections. It is the base
  28002. * class for modules like {@link FunctionNode} which allows to implement
  28003. * functions with native shader languages.
  28004. *
  28005. * @augments Node
  28006. */
  28007. class CodeNode extends Node {
  28008. static get type() {
  28009. return 'CodeNode';
  28010. }
  28011. /**
  28012. * Constructs a new code node.
  28013. *
  28014. * @param {string} [code=''] - The native code.
  28015. * @param {Array<Node>} [includes=[]] - An array of includes.
  28016. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28017. */
  28018. constructor( code = '', includes = [], language = '' ) {
  28019. super( 'code' );
  28020. /**
  28021. * This flag can be used for type testing.
  28022. *
  28023. * @type {boolean}
  28024. * @readonly
  28025. * @default true
  28026. */
  28027. this.isCodeNode = true;
  28028. /**
  28029. * This flag is used for global cache.
  28030. *
  28031. * @type {boolean}
  28032. * @default true
  28033. */
  28034. this.global = true;
  28035. /**
  28036. * The native code.
  28037. *
  28038. * @type {string}
  28039. * @default ''
  28040. */
  28041. this.code = code;
  28042. /**
  28043. * An array of includes
  28044. *
  28045. * @type {Array<Node>}
  28046. * @default []
  28047. */
  28048. this.includes = includes;
  28049. /**
  28050. * The used language.
  28051. *
  28052. * @type {('js'|'wgsl'|'glsl')}
  28053. * @default ''
  28054. */
  28055. this.language = language;
  28056. }
  28057. /**
  28058. * Sets the includes of this code node.
  28059. *
  28060. * @param {Array<Node>} includes - The includes to set.
  28061. * @return {CodeNode} A reference to this node.
  28062. */
  28063. setIncludes( includes ) {
  28064. this.includes = includes;
  28065. return this;
  28066. }
  28067. /**
  28068. * Returns the includes of this code node.
  28069. *
  28070. * @param {NodeBuilder} builder - The current node builder.
  28071. * @return {Array<Node>} The includes.
  28072. */
  28073. getIncludes( /*builder*/ ) {
  28074. return this.includes;
  28075. }
  28076. generate( builder ) {
  28077. const includes = this.getIncludes( builder );
  28078. for ( const include of includes ) {
  28079. include.build( builder );
  28080. }
  28081. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  28082. nodeCode.code = this.code;
  28083. return nodeCode.code;
  28084. }
  28085. serialize( data ) {
  28086. super.serialize( data );
  28087. data.code = this.code;
  28088. data.language = this.language;
  28089. }
  28090. deserialize( data ) {
  28091. super.deserialize( data );
  28092. this.code = data.code;
  28093. this.language = data.language;
  28094. }
  28095. }
  28096. /**
  28097. * TSL function for creating a code node.
  28098. *
  28099. * @tsl
  28100. * @function
  28101. * @param {string} [code] - The native code.
  28102. * @param {?Array<Node>} [includes=[]] - An array of includes.
  28103. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28104. * @returns {CodeNode}
  28105. */
  28106. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  28107. /**
  28108. * TSL function for creating a JS code node.
  28109. *
  28110. * @tsl
  28111. * @function
  28112. * @param {string} src - The native code.
  28113. * @param {Array<Node>} includes - An array of includes.
  28114. * @returns {CodeNode}
  28115. */
  28116. const js = ( src, includes ) => code( src, includes, 'js' );
  28117. /**
  28118. * TSL function for creating a WGSL code node.
  28119. *
  28120. * @tsl
  28121. * @function
  28122. * @param {string} src - The native code.
  28123. * @param {Array<Node>} includes - An array of includes.
  28124. * @returns {CodeNode}
  28125. */
  28126. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  28127. /**
  28128. * TSL function for creating a GLSL code node.
  28129. *
  28130. * @tsl
  28131. * @function
  28132. * @param {string} src - The native code.
  28133. * @param {Array<Node>} includes - An array of includes.
  28134. * @returns {CodeNode}
  28135. */
  28136. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  28137. /**
  28138. * This class represents a native shader function. It can be used to implement
  28139. * certain aspects of a node material with native shader code. There are two predefined
  28140. * TSL functions for easier usage.
  28141. *
  28142. * - `wgslFn`: Creates a WGSL function node.
  28143. * - `glslFn`: Creates a GLSL function node.
  28144. *
  28145. * A basic example with one include looks like so:
  28146. *
  28147. * ```js
  28148. * const desaturateWGSLFn = wgslFn( `
  28149. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  28150. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  28151. * return vec3<f32>( dot( lum, color ) );
  28152. * }`
  28153. *);
  28154. * const someWGSLFn = wgslFn( `
  28155. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  28156. * return desaturate( color );
  28157. * }
  28158. * `, [ desaturateWGSLFn ] );
  28159. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  28160. *```
  28161. * @augments CodeNode
  28162. */
  28163. class FunctionNode extends CodeNode {
  28164. static get type() {
  28165. return 'FunctionNode';
  28166. }
  28167. /**
  28168. * Constructs a new function node.
  28169. *
  28170. * @param {string} [code=''] - The native code.
  28171. * @param {Array<Node>} [includes=[]] - An array of includes.
  28172. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28173. */
  28174. constructor( code = '', includes = [], language = '' ) {
  28175. super( code, includes, language );
  28176. }
  28177. /**
  28178. * Returns the type of this function node.
  28179. *
  28180. * @param {NodeBuilder} builder - The current node builder.
  28181. * @return {string} The type.
  28182. */
  28183. getNodeType( builder ) {
  28184. return this.getNodeFunction( builder ).type;
  28185. }
  28186. /**
  28187. * Returns the type of a member of this function node.
  28188. *
  28189. * @param {NodeBuilder} builder - The current node builder.
  28190. * @param {string} name - The name of the member.
  28191. * @return {string} The type of the member.
  28192. */
  28193. getMemberType( builder, name ) {
  28194. const type = this.getNodeType( builder );
  28195. const structType = builder.getStructTypeNode( type );
  28196. return structType.getMemberType( builder, name );
  28197. }
  28198. /**
  28199. * Returns the inputs of this function node.
  28200. *
  28201. * @param {NodeBuilder} builder - The current node builder.
  28202. * @return {Array<NodeFunctionInput>} The inputs.
  28203. */
  28204. getInputs( builder ) {
  28205. return this.getNodeFunction( builder ).inputs;
  28206. }
  28207. /**
  28208. * Returns the node function for this function node.
  28209. *
  28210. * @param {NodeBuilder} builder - The current node builder.
  28211. * @return {NodeFunction} The node function.
  28212. */
  28213. getNodeFunction( builder ) {
  28214. const nodeData = builder.getDataFromNode( this );
  28215. let nodeFunction = nodeData.nodeFunction;
  28216. if ( nodeFunction === undefined ) {
  28217. nodeFunction = builder.parser.parseFunction( this.code );
  28218. nodeData.nodeFunction = nodeFunction;
  28219. }
  28220. return nodeFunction;
  28221. }
  28222. generate( builder, output ) {
  28223. super.generate( builder );
  28224. const nodeFunction = this.getNodeFunction( builder );
  28225. const name = nodeFunction.name;
  28226. const type = nodeFunction.type;
  28227. const nodeCode = builder.getCodeFromNode( this, type );
  28228. if ( name !== '' ) {
  28229. // use a custom property name
  28230. nodeCode.name = name;
  28231. }
  28232. const propertyName = builder.getPropertyName( nodeCode );
  28233. const code = this.getNodeFunction( builder ).getCode( propertyName );
  28234. nodeCode.code = code + '\n';
  28235. if ( output === 'property' ) {
  28236. return propertyName;
  28237. } else {
  28238. return builder.format( `${ propertyName }()`, type, output );
  28239. }
  28240. }
  28241. }
  28242. const nativeFn = ( code, includes = [], language = '' ) => {
  28243. for ( let i = 0; i < includes.length; i ++ ) {
  28244. const include = includes[ i ];
  28245. // TSL Function: glslFn, wgslFn
  28246. if ( typeof include === 'function' ) {
  28247. includes[ i ] = include.functionNode;
  28248. }
  28249. }
  28250. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  28251. const fn = ( ...params ) => functionNode.call( ...params );
  28252. fn.functionNode = functionNode;
  28253. return fn;
  28254. };
  28255. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  28256. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  28257. /**
  28258. * `ScriptableNode` uses this class to manage script inputs and outputs.
  28259. *
  28260. * @augments Node
  28261. */
  28262. class ScriptableValueNode extends Node {
  28263. static get type() {
  28264. return 'ScriptableValueNode';
  28265. }
  28266. /**
  28267. * Constructs a new scriptable node.
  28268. *
  28269. * @param {any} [value=null] - The value.
  28270. */
  28271. constructor( value = null ) {
  28272. super();
  28273. /**
  28274. * A reference to the value.
  28275. *
  28276. * @private
  28277. * @default null
  28278. */
  28279. this._value = value;
  28280. /**
  28281. * Depending on the type of `_value`, this property might cache parsed data.
  28282. *
  28283. * @private
  28284. * @default null
  28285. */
  28286. this._cache = null;
  28287. /**
  28288. * If this node represents an input, this property represents the input type.
  28289. *
  28290. * @type {?string}
  28291. * @default null
  28292. */
  28293. this.inputType = null;
  28294. /**
  28295. * If this node represents an output, this property represents the output type.
  28296. *
  28297. * @type {?string}
  28298. * @default null
  28299. */
  28300. this.outputType = null;
  28301. /**
  28302. * An event dispatcher for managing events.
  28303. *
  28304. * @type {EventDispatcher}
  28305. */
  28306. this.events = new EventDispatcher();
  28307. /**
  28308. * This flag can be used for type testing.
  28309. *
  28310. * @type {boolean}
  28311. * @readonly
  28312. * @default true
  28313. */
  28314. this.isScriptableValueNode = true;
  28315. }
  28316. /**
  28317. * Whether this node represents an output or not.
  28318. *
  28319. * @type {boolean}
  28320. * @readonly
  28321. * @default true
  28322. */
  28323. get isScriptableOutputNode() {
  28324. return this.outputType !== null;
  28325. }
  28326. set value( val ) {
  28327. if ( this._value === val ) return;
  28328. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  28329. URL.revokeObjectURL( this._cache );
  28330. this._cache = null;
  28331. }
  28332. this._value = val;
  28333. this.events.dispatchEvent( { type: 'change' } );
  28334. this.refresh();
  28335. }
  28336. /**
  28337. * The node's value.
  28338. *
  28339. * @type {any}
  28340. */
  28341. get value() {
  28342. return this._value;
  28343. }
  28344. /**
  28345. * Dispatches the `refresh` event.
  28346. */
  28347. refresh() {
  28348. this.events.dispatchEvent( { type: 'refresh' } );
  28349. }
  28350. /**
  28351. * The `value` property usually represents a node or even binary data in form of array buffers.
  28352. * In this case, this method tries to return the actual value behind the complex type.
  28353. *
  28354. * @return {any} The value.
  28355. */
  28356. getValue() {
  28357. const value = this.value;
  28358. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  28359. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  28360. } else if ( value && value.value !== null && value.value !== undefined && (
  28361. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  28362. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  28363. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  28364. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  28365. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  28366. ( this.inputType === 'Color' && value.value.isColor ) ||
  28367. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  28368. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  28369. ) ) {
  28370. return value.value;
  28371. }
  28372. return this._cache || value;
  28373. }
  28374. /**
  28375. * Overwritten since the node type is inferred from the value.
  28376. *
  28377. * @param {NodeBuilder} builder - The current node builder.
  28378. * @return {string} The node type.
  28379. */
  28380. getNodeType( builder ) {
  28381. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  28382. }
  28383. setup() {
  28384. return this.value && this.value.isNode ? this.value : float();
  28385. }
  28386. serialize( data ) {
  28387. super.serialize( data );
  28388. if ( this.value !== null ) {
  28389. if ( this.inputType === 'ArrayBuffer' ) {
  28390. data.value = arrayBufferToBase64( this.value );
  28391. } else {
  28392. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  28393. }
  28394. } else {
  28395. data.value = null;
  28396. }
  28397. data.inputType = this.inputType;
  28398. data.outputType = this.outputType;
  28399. }
  28400. deserialize( data ) {
  28401. super.deserialize( data );
  28402. let value = null;
  28403. if ( data.value !== null ) {
  28404. if ( data.inputType === 'ArrayBuffer' ) {
  28405. value = base64ToArrayBuffer( data.value );
  28406. } else if ( data.inputType === 'Texture' ) {
  28407. value = data.meta.textures[ data.value ];
  28408. } else {
  28409. value = data.meta.nodes[ data.value ] || null;
  28410. }
  28411. }
  28412. this.value = value;
  28413. this.inputType = data.inputType;
  28414. this.outputType = data.outputType;
  28415. }
  28416. }
  28417. /**
  28418. * TSL function for creating a scriptable value node.
  28419. *
  28420. * @tsl
  28421. * @function
  28422. * @param {any} [value] - The value.
  28423. * @returns {ScriptableValueNode}
  28424. */
  28425. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  28426. /**
  28427. * A Map-like data structure for managing resources of scriptable nodes.
  28428. *
  28429. * @augments Map
  28430. */
  28431. class Resources extends Map {
  28432. get( key, callback = null, ...params ) {
  28433. if ( this.has( key ) ) return super.get( key );
  28434. if ( callback !== null ) {
  28435. const value = callback( ...params );
  28436. this.set( key, value );
  28437. return value;
  28438. }
  28439. }
  28440. }
  28441. class Parameters {
  28442. constructor( scriptableNode ) {
  28443. this.scriptableNode = scriptableNode;
  28444. }
  28445. get parameters() {
  28446. return this.scriptableNode.parameters;
  28447. }
  28448. get layout() {
  28449. return this.scriptableNode.getLayout();
  28450. }
  28451. getInputLayout( id ) {
  28452. return this.scriptableNode.getInputLayout( id );
  28453. }
  28454. get( name ) {
  28455. const param = this.parameters[ name ];
  28456. const value = param ? param.getValue() : null;
  28457. return value;
  28458. }
  28459. }
  28460. /**
  28461. * Defines the resources (e.g. namespaces) of scriptable nodes.
  28462. *
  28463. * @type {Resources}
  28464. */
  28465. const ScriptableNodeResources = new Resources();
  28466. /**
  28467. * This type of node allows to implement nodes with custom scripts. The script
  28468. * section is represented as an instance of `CodeNode` written with JavaScript.
  28469. * The script itself must adhere to a specific structure.
  28470. *
  28471. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  28472. * - layout: The layout object defines the script's interface (inputs and outputs).
  28473. *
  28474. * ```js
  28475. * ScriptableNodeResources.set( 'TSL', TSL );
  28476. *
  28477. * const scriptableNode = scriptable( js( `
  28478. * layout = {
  28479. * outputType: 'node',
  28480. * elements: [
  28481. * { name: 'source', inputType: 'node' },
  28482. * ]
  28483. * };
  28484. *
  28485. * const { mul, oscSine } = TSL;
  28486. *
  28487. * function main() {
  28488. * const source = parameters.get( 'source' ) || float();
  28489. * return mul( source, oscSine() ) );
  28490. * }
  28491. *
  28492. * ` ) );
  28493. *
  28494. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  28495. *
  28496. * const material = new THREE.MeshBasicNodeMaterial();
  28497. * material.colorNode = scriptableNode;
  28498. * ```
  28499. *
  28500. * @augments Node
  28501. */
  28502. class ScriptableNode extends Node {
  28503. static get type() {
  28504. return 'ScriptableNode';
  28505. }
  28506. /**
  28507. * Constructs a new scriptable node.
  28508. *
  28509. * @param {?CodeNode} [codeNode=null] - The code node.
  28510. * @param {Object} [parameters={}] - The parameters definition.
  28511. */
  28512. constructor( codeNode = null, parameters = {} ) {
  28513. super();
  28514. /**
  28515. * The code node.
  28516. *
  28517. * @type {?CodeNode}
  28518. * @default null
  28519. */
  28520. this.codeNode = codeNode;
  28521. /**
  28522. * The parameters definition.
  28523. *
  28524. * @type {Object}
  28525. * @default {}
  28526. */
  28527. this.parameters = parameters;
  28528. this._local = new Resources();
  28529. this._output = scriptableValue( null );
  28530. this._outputs = {};
  28531. this._source = this.source;
  28532. this._method = null;
  28533. this._object = null;
  28534. this._value = null;
  28535. this._needsOutputUpdate = true;
  28536. this.onRefresh = this.onRefresh.bind( this );
  28537. /**
  28538. * This flag can be used for type testing.
  28539. *
  28540. * @type {boolean}
  28541. * @readonly
  28542. * @default true
  28543. */
  28544. this.isScriptableNode = true;
  28545. }
  28546. /**
  28547. * The source code of the scriptable node.
  28548. *
  28549. * @type {string}
  28550. */
  28551. get source() {
  28552. return this.codeNode ? this.codeNode.code : '';
  28553. }
  28554. /**
  28555. * Sets the reference of a local script variable.
  28556. *
  28557. * @param {string} name - The variable name.
  28558. * @param {Object} value - The reference to set.
  28559. * @return {Resources} The resource map
  28560. */
  28561. setLocal( name, value ) {
  28562. return this._local.set( name, value );
  28563. }
  28564. /**
  28565. * Gets the value of a local script variable.
  28566. *
  28567. * @param {string} name - The variable name.
  28568. * @return {Object} The value.
  28569. */
  28570. getLocal( name ) {
  28571. return this._local.get( name );
  28572. }
  28573. /**
  28574. * Event listener for the `refresh` event.
  28575. */
  28576. onRefresh() {
  28577. this._refresh();
  28578. }
  28579. /**
  28580. * Returns an input from the layout with the given id/name.
  28581. *
  28582. * @param {string} id - The id/name of the input.
  28583. * @return {Object} The element entry.
  28584. */
  28585. getInputLayout( id ) {
  28586. for ( const element of this.getLayout() ) {
  28587. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  28588. return element;
  28589. }
  28590. }
  28591. }
  28592. /**
  28593. * Returns an output from the layout with the given id/name.
  28594. *
  28595. * @param {string} id - The id/name of the output.
  28596. * @return {Object} The element entry.
  28597. */
  28598. getOutputLayout( id ) {
  28599. for ( const element of this.getLayout() ) {
  28600. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  28601. return element;
  28602. }
  28603. }
  28604. }
  28605. /**
  28606. * Defines a script output for the given name and value.
  28607. *
  28608. * @param {string} name - The name of the output.
  28609. * @param {Node} value - The node value.
  28610. * @return {ScriptableNode} A reference to this node.
  28611. */
  28612. setOutput( name, value ) {
  28613. const outputs = this._outputs;
  28614. if ( outputs[ name ] === undefined ) {
  28615. outputs[ name ] = scriptableValue( value );
  28616. } else {
  28617. outputs[ name ].value = value;
  28618. }
  28619. return this;
  28620. }
  28621. /**
  28622. * Returns a script output for the given name.
  28623. *
  28624. * @param {string} name - The name of the output.
  28625. * @return {ScriptableValueNode} The node value.
  28626. */
  28627. getOutput( name ) {
  28628. return this._outputs[ name ];
  28629. }
  28630. /**
  28631. * Returns a parameter for the given name
  28632. *
  28633. * @param {string} name - The name of the parameter.
  28634. * @return {ScriptableValueNode} The node value.
  28635. */
  28636. getParameter( name ) {
  28637. return this.parameters[ name ];
  28638. }
  28639. /**
  28640. * Sets a value for the given parameter name.
  28641. *
  28642. * @param {string} name - The parameter name.
  28643. * @param {any} value - The parameter value.
  28644. * @return {ScriptableNode} A reference to this node.
  28645. */
  28646. setParameter( name, value ) {
  28647. const parameters = this.parameters;
  28648. if ( value && value.isScriptableNode ) {
  28649. this.deleteParameter( name );
  28650. parameters[ name ] = value;
  28651. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  28652. } else if ( value && value.isScriptableValueNode ) {
  28653. this.deleteParameter( name );
  28654. parameters[ name ] = value;
  28655. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  28656. } else if ( parameters[ name ] === undefined ) {
  28657. parameters[ name ] = scriptableValue( value );
  28658. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  28659. } else {
  28660. parameters[ name ].value = value;
  28661. }
  28662. return this;
  28663. }
  28664. /**
  28665. * Returns the value of this node which is the value of
  28666. * the default output.
  28667. *
  28668. * @return {Node} The value.
  28669. */
  28670. getValue() {
  28671. return this.getDefaultOutput().getValue();
  28672. }
  28673. /**
  28674. * Deletes a parameter from the script.
  28675. *
  28676. * @param {string} name - The parameter to remove.
  28677. * @return {ScriptableNode} A reference to this node.
  28678. */
  28679. deleteParameter( name ) {
  28680. let valueNode = this.parameters[ name ];
  28681. if ( valueNode ) {
  28682. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  28683. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  28684. }
  28685. return this;
  28686. }
  28687. /**
  28688. * Deletes all parameters from the script.
  28689. *
  28690. * @return {ScriptableNode} A reference to this node.
  28691. */
  28692. clearParameters() {
  28693. for ( const name of Object.keys( this.parameters ) ) {
  28694. this.deleteParameter( name );
  28695. }
  28696. this.needsUpdate = true;
  28697. return this;
  28698. }
  28699. /**
  28700. * Calls a function from the script.
  28701. *
  28702. * @param {string} name - The function name.
  28703. * @param {...any} params - A list of parameters.
  28704. * @return {any} The result of the function call.
  28705. */
  28706. call( name, ...params ) {
  28707. const object = this.getObject();
  28708. const method = object[ name ];
  28709. if ( typeof method === 'function' ) {
  28710. return method( ...params );
  28711. }
  28712. }
  28713. /**
  28714. * Asynchronously calls a function from the script.
  28715. *
  28716. * @param {string} name - The function name.
  28717. * @param {...any} params - A list of parameters.
  28718. * @return {Promise<any>} The result of the function call.
  28719. */
  28720. async callAsync( name, ...params ) {
  28721. const object = this.getObject();
  28722. const method = object[ name ];
  28723. if ( typeof method === 'function' ) {
  28724. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  28725. }
  28726. }
  28727. /**
  28728. * Overwritten since the node types is inferred from the script's output.
  28729. *
  28730. * @param {NodeBuilder} builder - The current node builder
  28731. * @return {string} The node type.
  28732. */
  28733. getNodeType( builder ) {
  28734. return this.getDefaultOutputNode().getNodeType( builder );
  28735. }
  28736. /**
  28737. * Refreshes the script node.
  28738. *
  28739. * @param {?string} [output=null] - An optional output.
  28740. */
  28741. refresh( output = null ) {
  28742. if ( output !== null ) {
  28743. this.getOutput( output ).refresh();
  28744. } else {
  28745. this._refresh();
  28746. }
  28747. }
  28748. /**
  28749. * Returns an object representation of the script.
  28750. *
  28751. * @return {Object} The result object.
  28752. */
  28753. getObject() {
  28754. if ( this.needsUpdate ) this.dispose();
  28755. if ( this._object !== null ) return this._object;
  28756. //
  28757. const refresh = () => this.refresh();
  28758. const setOutput = ( id, value ) => this.setOutput( id, value );
  28759. const parameters = new Parameters( this );
  28760. const THREE = ScriptableNodeResources.get( 'THREE' );
  28761. const TSL = ScriptableNodeResources.get( 'TSL' );
  28762. const method = this.getMethod();
  28763. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  28764. this._object = method( ...params );
  28765. const layout = this._object.layout;
  28766. if ( layout ) {
  28767. if ( layout.cache === false ) {
  28768. this._local.clear();
  28769. }
  28770. // default output
  28771. this._output.outputType = layout.outputType || null;
  28772. if ( Array.isArray( layout.elements ) ) {
  28773. for ( const element of layout.elements ) {
  28774. const id = element.id || element.name;
  28775. if ( element.inputType ) {
  28776. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  28777. this.getParameter( id ).inputType = element.inputType;
  28778. }
  28779. if ( element.outputType ) {
  28780. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  28781. this.getOutput( id ).outputType = element.outputType;
  28782. }
  28783. }
  28784. }
  28785. }
  28786. return this._object;
  28787. }
  28788. deserialize( data ) {
  28789. super.deserialize( data );
  28790. for ( const name in this.parameters ) {
  28791. let valueNode = this.parameters[ name ];
  28792. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  28793. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  28794. }
  28795. }
  28796. /**
  28797. * Returns the layout of the script.
  28798. *
  28799. * @return {Object} The script's layout.
  28800. */
  28801. getLayout() {
  28802. return this.getObject().layout;
  28803. }
  28804. /**
  28805. * Returns default node output of the script.
  28806. *
  28807. * @return {Node} The default node output.
  28808. */
  28809. getDefaultOutputNode() {
  28810. const output = this.getDefaultOutput().value;
  28811. if ( output && output.isNode ) {
  28812. return output;
  28813. }
  28814. return float();
  28815. }
  28816. /**
  28817. * Returns default output of the script.
  28818. *
  28819. * @return {ScriptableValueNode} The default output.
  28820. */
  28821. getDefaultOutput() {
  28822. return this._exec()._output;
  28823. }
  28824. /**
  28825. * Returns a function created from the node's script.
  28826. *
  28827. * @return {Function} The function representing the node's code.
  28828. */
  28829. getMethod() {
  28830. if ( this.needsUpdate ) this.dispose();
  28831. if ( this._method !== null ) return this._method;
  28832. //
  28833. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  28834. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  28835. const properties = interfaceProps.join( ', ' );
  28836. const declarations = 'var ' + properties + '; var output = {};\n';
  28837. const returns = '\nreturn { ...output, ' + properties + ' };';
  28838. const code = declarations + this.codeNode.code + returns;
  28839. //
  28840. this._method = new Function( ...parametersProps, code );
  28841. return this._method;
  28842. }
  28843. /**
  28844. * Frees all internal resources.
  28845. */
  28846. dispose() {
  28847. if ( this._method === null ) return;
  28848. if ( this._object && typeof this._object.dispose === 'function' ) {
  28849. this._object.dispose();
  28850. }
  28851. this._method = null;
  28852. this._object = null;
  28853. this._source = null;
  28854. this._value = null;
  28855. this._needsOutputUpdate = true;
  28856. this._output.value = null;
  28857. this._outputs = {};
  28858. }
  28859. setup() {
  28860. return this.getDefaultOutputNode();
  28861. }
  28862. getCacheKey( force ) {
  28863. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  28864. for ( const param in this.parameters ) {
  28865. values.push( this.parameters[ param ].getCacheKey( force ) );
  28866. }
  28867. return hashArray( values );
  28868. }
  28869. set needsUpdate( value ) {
  28870. if ( value === true ) this.dispose();
  28871. }
  28872. get needsUpdate() {
  28873. return this.source !== this._source;
  28874. }
  28875. /**
  28876. * Executes the `main` function of the script.
  28877. *
  28878. * @private
  28879. * @return {ScriptableNode} A reference to this node.
  28880. */
  28881. _exec() {
  28882. if ( this.codeNode === null ) return this;
  28883. if ( this._needsOutputUpdate === true ) {
  28884. this._value = this.call( 'main' );
  28885. this._needsOutputUpdate = false;
  28886. }
  28887. this._output.value = this._value;
  28888. return this;
  28889. }
  28890. /**
  28891. * Executes the refresh.
  28892. *
  28893. * @private
  28894. */
  28895. _refresh() {
  28896. this.needsUpdate = true;
  28897. this._exec();
  28898. this._output.refresh();
  28899. }
  28900. }
  28901. /**
  28902. * TSL function for creating a scriptable node.
  28903. *
  28904. * @tsl
  28905. * @function
  28906. * @param {CodeNode} [codeNode] - The code node.
  28907. * @param {?Object} [parameters={}] - The parameters definition.
  28908. * @returns {ScriptableNode}
  28909. */
  28910. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  28911. /**
  28912. * Returns a node that represents the `z` coordinate in view space
  28913. * for the current fragment. It's a different representation of the
  28914. * default depth value.
  28915. *
  28916. * This value can be part of a computation that defines how the fog
  28917. * density increases when moving away from the camera.
  28918. *
  28919. * @param {NodeBuilder} builder - The current node builder.
  28920. * @return {Node} The viewZ node.
  28921. */
  28922. function getViewZNode( builder ) {
  28923. let viewZ;
  28924. const getViewZ = builder.context.getViewZ;
  28925. if ( getViewZ !== undefined ) {
  28926. viewZ = getViewZ( this );
  28927. }
  28928. return ( viewZ || positionView.z ).negate();
  28929. }
  28930. /**
  28931. * Constructs a new range factor node.
  28932. *
  28933. * @tsl
  28934. * @function
  28935. * @param {Node} near - Defines the near value.
  28936. * @param {Node} far - Defines the far value.
  28937. */
  28938. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  28939. const viewZ = getViewZNode( builder );
  28940. return smoothstep( near, far, viewZ );
  28941. } );
  28942. /**
  28943. * Represents an exponential squared fog. This type of fog gives
  28944. * a clear view near the camera and a faster than exponentially
  28945. * densening fog farther from the camera.
  28946. *
  28947. * @tsl
  28948. * @function
  28949. * @param {Node} density - Defines the fog density.
  28950. */
  28951. const densityFogFactor = Fn( ( [ density ], builder ) => {
  28952. const viewZ = getViewZNode( builder );
  28953. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  28954. } );
  28955. /**
  28956. * This class can be used to configure a fog for the scene.
  28957. * Nodes of this type are assigned to `Scene.fogNode`.
  28958. *
  28959. * @tsl
  28960. * @function
  28961. * @param {Node} color - Defines the color of the fog.
  28962. * @param {Node} factor - Defines how the fog is factored in the scene.
  28963. */
  28964. const fog = Fn( ( [ color, factor ] ) => {
  28965. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  28966. } );
  28967. // Deprecated
  28968. /**
  28969. * @tsl
  28970. * @function
  28971. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  28972. *
  28973. * @param {Node} color
  28974. * @param {Node} near
  28975. * @param {Node} far
  28976. * @returns {Function}
  28977. */
  28978. function rangeFog( color, near, far ) { // @deprecated, r171
  28979. warn( 'TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  28980. return fog( color, rangeFogFactor( near, far ) );
  28981. }
  28982. /**
  28983. * @tsl
  28984. * @function
  28985. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  28986. *
  28987. * @param {Node} color
  28988. * @param {Node} density
  28989. * @returns {Function}
  28990. */
  28991. function densityFog( color, density ) { // @deprecated, r171
  28992. warn( 'TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  28993. return fog( color, densityFogFactor( density ) );
  28994. }
  28995. let min = null;
  28996. let max = null;
  28997. /**
  28998. * `RangeNode` generates random instanced attribute data in a defined range.
  28999. * An exemplary use case for this utility node is to generate random per-instance
  29000. * colors:
  29001. * ```js
  29002. * const material = new MeshBasicNodeMaterial();
  29003. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  29004. * const mesh = new InstancedMesh( geometry, material, count );
  29005. * ```
  29006. * @augments Node
  29007. */
  29008. class RangeNode extends Node {
  29009. static get type() {
  29010. return 'RangeNode';
  29011. }
  29012. /**
  29013. * Constructs a new range node.
  29014. *
  29015. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29016. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29017. */
  29018. constructor( minNode = float(), maxNode = float() ) {
  29019. super();
  29020. /**
  29021. * A node defining the lower bound of the range.
  29022. *
  29023. * @type {Node<any>}
  29024. * @default float()
  29025. */
  29026. this.minNode = minNode;
  29027. /**
  29028. * A node defining the upper bound of the range.
  29029. *
  29030. * @type {Node<any>}
  29031. * @default float()
  29032. */
  29033. this.maxNode = maxNode;
  29034. }
  29035. /**
  29036. * Returns the vector length which is computed based on the range definition.
  29037. *
  29038. * @param {NodeBuilder} builder - The current node builder.
  29039. * @return {number} The vector length.
  29040. */
  29041. getVectorLength( builder ) {
  29042. const minNode = this.getConstNode( this.minNode );
  29043. const maxNode = this.getConstNode( this.maxNode );
  29044. const minLength = builder.getTypeLength( getValueType( minNode.value ) );
  29045. const maxLength = builder.getTypeLength( getValueType( maxNode.value ) );
  29046. return minLength > maxLength ? minLength : maxLength;
  29047. }
  29048. /**
  29049. * This method is overwritten since the node type is inferred from range definition.
  29050. *
  29051. * @param {NodeBuilder} builder - The current node builder.
  29052. * @return {string} The node type.
  29053. */
  29054. getNodeType( builder ) {
  29055. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  29056. }
  29057. /**
  29058. * Returns a constant node from the given node by traversing it.
  29059. *
  29060. * @param {Node} node - The node to traverse.
  29061. * @returns {Node} The constant node, if found.
  29062. */
  29063. getConstNode( node ) {
  29064. let output = null;
  29065. node.traverse( n => {
  29066. if ( n.isConstNode === true ) {
  29067. output = n;
  29068. }
  29069. } );
  29070. if ( output === null ) {
  29071. throw new Error( 'THREE.TSL: No "ConstNode" found in node graph.' );
  29072. }
  29073. return output;
  29074. }
  29075. setup( builder ) {
  29076. const object = builder.object;
  29077. let output = null;
  29078. if ( object.count > 1 ) {
  29079. const minNode = this.getConstNode( this.minNode );
  29080. const maxNode = this.getConstNode( this.maxNode );
  29081. const minValue = minNode.value;
  29082. const maxValue = maxNode.value;
  29083. const minLength = builder.getTypeLength( getValueType( minValue ) );
  29084. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  29085. min = min || new Vector4();
  29086. max = max || new Vector4();
  29087. min.setScalar( 0 );
  29088. max.setScalar( 0 );
  29089. if ( minLength === 1 ) min.setScalar( minValue );
  29090. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  29091. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  29092. if ( maxLength === 1 ) max.setScalar( maxValue );
  29093. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  29094. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  29095. const stride = 4;
  29096. const length = stride * object.count;
  29097. const array = new Float32Array( length );
  29098. for ( let i = 0; i < length; i ++ ) {
  29099. const index = i % stride;
  29100. const minElementValue = min.getComponent( index );
  29101. const maxElementValue = max.getComponent( index );
  29102. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  29103. }
  29104. const nodeType = this.getNodeType( builder );
  29105. if ( object.count <= 4096 ) {
  29106. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  29107. } else {
  29108. // TODO: Improve anonymous buffer attribute creation removing this part
  29109. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  29110. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  29111. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  29112. }
  29113. } else {
  29114. output = float( 0 );
  29115. }
  29116. return output;
  29117. }
  29118. }
  29119. /**
  29120. * TSL function for creating a range node.
  29121. *
  29122. * @tsl
  29123. * @function
  29124. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29125. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29126. * @returns {RangeNode}
  29127. */
  29128. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  29129. /**
  29130. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  29131. * about the currently running dispatch and/or the device it is running on.
  29132. *
  29133. * This node can only be used with a WebGPU backend.
  29134. *
  29135. * @augments Node
  29136. */
  29137. class ComputeBuiltinNode extends Node {
  29138. static get type() {
  29139. return 'ComputeBuiltinNode';
  29140. }
  29141. /**
  29142. * Constructs a new compute builtin node.
  29143. *
  29144. * @param {string} builtinName - The built-in name.
  29145. * @param {string} nodeType - The node type.
  29146. */
  29147. constructor( builtinName, nodeType ) {
  29148. super( nodeType );
  29149. /**
  29150. * The built-in name.
  29151. *
  29152. * @private
  29153. * @type {string}
  29154. */
  29155. this._builtinName = builtinName;
  29156. }
  29157. /**
  29158. * This method is overwritten since hash is derived from the built-in name.
  29159. *
  29160. * @param {NodeBuilder} builder - The current node builder.
  29161. * @return {string} The hash.
  29162. */
  29163. getHash( builder ) {
  29164. return this.getBuiltinName( builder );
  29165. }
  29166. /**
  29167. * This method is overwritten since the node type is simply derived from `nodeType`..
  29168. *
  29169. * @param {NodeBuilder} builder - The current node builder.
  29170. * @return {string} The node type.
  29171. */
  29172. getNodeType( /*builder*/ ) {
  29173. return this.nodeType;
  29174. }
  29175. /**
  29176. * Sets the builtin name.
  29177. *
  29178. * @param {string} builtinName - The built-in name.
  29179. * @return {ComputeBuiltinNode} A reference to this node.
  29180. */
  29181. setBuiltinName( builtinName ) {
  29182. this._builtinName = builtinName;
  29183. return this;
  29184. }
  29185. /**
  29186. * Returns the builtin name.
  29187. *
  29188. * @param {NodeBuilder} builder - The current node builder.
  29189. * @return {string} The builtin name.
  29190. */
  29191. getBuiltinName( /*builder*/ ) {
  29192. return this._builtinName;
  29193. }
  29194. /**
  29195. * Whether the current node builder has the builtin or not.
  29196. *
  29197. * @param {NodeBuilder} builder - The current node builder.
  29198. * @return {boolean} Whether the builder has the builtin or not.
  29199. */
  29200. hasBuiltin( builder ) {
  29201. return builder.hasBuiltin( this._builtinName );
  29202. }
  29203. generate( builder, output ) {
  29204. const builtinName = this.getBuiltinName( builder );
  29205. const nodeType = this.getNodeType( builder );
  29206. if ( builder.shaderStage === 'compute' ) {
  29207. return builder.format( builtinName, nodeType, output );
  29208. } else {
  29209. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  29210. return builder.generateConst( nodeType );
  29211. }
  29212. }
  29213. serialize( data ) {
  29214. super.serialize( data );
  29215. data.global = this.global;
  29216. data._builtinName = this._builtinName;
  29217. }
  29218. deserialize( data ) {
  29219. super.deserialize( data );
  29220. this.global = data.global;
  29221. this._builtinName = data._builtinName;
  29222. }
  29223. }
  29224. /**
  29225. * TSL function for creating a compute builtin node.
  29226. *
  29227. * @tsl
  29228. * @function
  29229. * @param {string} name - The built-in name.
  29230. * @param {string} nodeType - The node type.
  29231. * @returns {ComputeBuiltinNode}
  29232. */
  29233. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  29234. /**
  29235. * Represents the number of workgroups dispatched by the compute shader.
  29236. * ```js
  29237. * // Run 512 invocations/threads with a workgroup size of 128.
  29238. * const computeFn = Fn(() => {
  29239. *
  29240. * // numWorkgroups.x = 4
  29241. * storageBuffer.element(0).assign(numWorkgroups.x)
  29242. *
  29243. * })().compute(512, [128]);
  29244. *
  29245. * // Run 512 invocations/threads with the default workgroup size of 64.
  29246. * const computeFn = Fn(() => {
  29247. *
  29248. * // numWorkgroups.x = 8
  29249. * storageBuffer.element(0).assign(numWorkgroups.x)
  29250. *
  29251. * })().compute(512);
  29252. * ```
  29253. *
  29254. * @tsl
  29255. * @type {ComputeBuiltinNode<uvec3>}
  29256. */
  29257. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  29258. /**
  29259. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  29260. * ```js
  29261. * // Execute 12 compute threads with a workgroup size of 3.
  29262. * const computeFn = Fn( () => {
  29263. *
  29264. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  29265. *
  29266. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  29267. *
  29268. * } ).Else( () => {
  29269. *
  29270. * storageBuffer.element( instanceIndex ).assign( 0 );
  29271. *
  29272. * } );
  29273. *
  29274. * } )().compute( 12, [ 3 ] );
  29275. *
  29276. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  29277. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  29278. * ```
  29279. *
  29280. * @tsl
  29281. * @type {ComputeBuiltinNode<uvec3>}
  29282. */
  29283. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  29284. /**
  29285. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  29286. *
  29287. * @tsl
  29288. * @type {ComputeBuiltinNode<uvec3>}
  29289. */
  29290. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  29291. /**
  29292. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  29293. *
  29294. * @tsl
  29295. * @type {ComputeBuiltinNode<uvec3>}
  29296. */
  29297. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  29298. /**
  29299. * A device dependent variable that exposes the size of the current invocation's subgroup.
  29300. *
  29301. * @tsl
  29302. * @type {ComputeBuiltinNode<uint>}
  29303. */
  29304. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  29305. /**
  29306. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  29307. *
  29308. * This node can only be used with a WebGPU backend.
  29309. *
  29310. * @augments Node
  29311. */
  29312. class BarrierNode extends Node {
  29313. /**
  29314. * Constructs a new barrier node.
  29315. *
  29316. * @param {string} scope - The scope defines the behavior of the node.
  29317. */
  29318. constructor( scope ) {
  29319. super();
  29320. this.scope = scope;
  29321. }
  29322. generate( builder ) {
  29323. const { scope } = this;
  29324. const { renderer } = builder;
  29325. if ( renderer.backend.isWebGLBackend === true ) {
  29326. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  29327. } else {
  29328. builder.addLineFlowCode( `${scope}Barrier()`, this );
  29329. }
  29330. }
  29331. }
  29332. /**
  29333. * TSL function for creating a barrier node.
  29334. *
  29335. * @tsl
  29336. * @function
  29337. * @param {string} scope - The scope defines the behavior of the node..
  29338. * @returns {BarrierNode}
  29339. */
  29340. const barrier = nodeProxy( BarrierNode );
  29341. /**
  29342. * TSL function for creating a workgroup barrier. All compute shader
  29343. * invocations must wait for each invocation within a workgroup to
  29344. * complete before the barrier can be surpassed.
  29345. *
  29346. * @tsl
  29347. * @function
  29348. * @returns {BarrierNode}
  29349. */
  29350. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  29351. /**
  29352. * TSL function for creating a storage barrier. All invocations must
  29353. * wait for each access to variables within the 'storage' address space
  29354. * to complete before the barrier can be passed.
  29355. *
  29356. * @tsl
  29357. * @function
  29358. * @returns {BarrierNode}
  29359. */
  29360. const storageBarrier = () => barrier( 'storage' ).toStack();
  29361. /**
  29362. * TSL function for creating a texture barrier. All invocations must
  29363. * wait for each access to variables within the 'texture' address space
  29364. * to complete before the barrier can be passed.
  29365. *
  29366. * @tsl
  29367. * @function
  29368. * @returns {BarrierNode}
  29369. */
  29370. const textureBarrier = () => barrier( 'texture' ).toStack();
  29371. /**
  29372. * Represents an element of a 'workgroup' scoped buffer.
  29373. *
  29374. * @augments ArrayElementNode
  29375. */
  29376. class WorkgroupInfoElementNode extends ArrayElementNode {
  29377. /**
  29378. * Constructs a new workgroup info element node.
  29379. *
  29380. * @param {Node} workgroupInfoNode - The workgroup info node.
  29381. * @param {Node} indexNode - The index node that defines the element access.
  29382. */
  29383. constructor( workgroupInfoNode, indexNode ) {
  29384. super( workgroupInfoNode, indexNode );
  29385. /**
  29386. * This flag can be used for type testing.
  29387. *
  29388. * @type {boolean}
  29389. * @readonly
  29390. * @default true
  29391. */
  29392. this.isWorkgroupInfoElementNode = true;
  29393. }
  29394. generate( builder, output ) {
  29395. let snippet;
  29396. const isAssignContext = builder.context.assign;
  29397. snippet = super.generate( builder );
  29398. if ( isAssignContext !== true ) {
  29399. const type = this.getNodeType( builder );
  29400. snippet = builder.format( snippet, type, output );
  29401. }
  29402. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  29403. return snippet;
  29404. }
  29405. }
  29406. /**
  29407. * A node allowing the user to create a 'workgroup' scoped buffer within the
  29408. * context of a compute shader. Typically, workgroup scoped buffers are
  29409. * created to hold data that is transferred from a global storage scope into
  29410. * a local workgroup scope. For invocations within a workgroup, data
  29411. * access speeds on 'workgroup' scoped buffers can be significantly faster
  29412. * than similar access operations on globally accessible storage buffers.
  29413. *
  29414. * This node can only be used with a WebGPU backend.
  29415. *
  29416. * @augments Node
  29417. */
  29418. class WorkgroupInfoNode extends Node {
  29419. /**
  29420. * Constructs a new buffer scoped to type scope.
  29421. *
  29422. * @param {string} scope - TODO.
  29423. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  29424. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  29425. */
  29426. constructor( scope, bufferType, bufferCount = 0 ) {
  29427. super( bufferType );
  29428. /**
  29429. * The buffer type.
  29430. *
  29431. * @type {string}
  29432. */
  29433. this.bufferType = bufferType;
  29434. /**
  29435. * The buffer count.
  29436. *
  29437. * @type {number}
  29438. * @default 0
  29439. */
  29440. this.bufferCount = bufferCount;
  29441. /**
  29442. * This flag can be used for type testing.
  29443. *
  29444. * @type {boolean}
  29445. * @readonly
  29446. * @default true
  29447. */
  29448. this.isWorkgroupInfoNode = true;
  29449. /**
  29450. * The data type of the array buffer.
  29451. *
  29452. * @type {string}
  29453. */
  29454. this.elementType = bufferType;
  29455. /**
  29456. * TODO.
  29457. *
  29458. * @type {string}
  29459. */
  29460. this.scope = scope;
  29461. /**
  29462. * The name of the workgroup scoped buffer.
  29463. *
  29464. * @type {string}
  29465. * @default ''
  29466. */
  29467. this.name = '';
  29468. }
  29469. /**
  29470. * Sets the name of this node.
  29471. *
  29472. * @param {string} name - The name to set.
  29473. * @return {WorkgroupInfoNode} A reference to this node.
  29474. */
  29475. setName( name ) {
  29476. this.name = name;
  29477. return this;
  29478. }
  29479. /**
  29480. * Sets the name/label of this node.
  29481. *
  29482. * @deprecated
  29483. * @param {string} name - The name to set.
  29484. * @return {WorkgroupInfoNode} A reference to this node.
  29485. */
  29486. label( name ) {
  29487. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  29488. return this.setName( name );
  29489. }
  29490. /**
  29491. * Sets the scope of this node.
  29492. *
  29493. * @param {string} scope - The scope to set.
  29494. * @return {WorkgroupInfoNode} A reference to this node.
  29495. */
  29496. setScope( scope ) {
  29497. this.scope = scope;
  29498. return this;
  29499. }
  29500. /**
  29501. * The data type of the array buffer.
  29502. *
  29503. * @return {string} The element type.
  29504. */
  29505. getElementType() {
  29506. return this.elementType;
  29507. }
  29508. /**
  29509. * Overwrites the default implementation since the input type
  29510. * is inferred from the scope.
  29511. *
  29512. * @param {NodeBuilder} builder - The current node builder.
  29513. * @return {string} The input type.
  29514. */
  29515. getInputType( /*builder*/ ) {
  29516. return `${this.scope}Array`;
  29517. }
  29518. /**
  29519. * This method can be used to access elements via an index node.
  29520. *
  29521. * @param {IndexNode} indexNode - indexNode.
  29522. * @return {WorkgroupInfoElementNode} A reference to an element.
  29523. */
  29524. element( indexNode ) {
  29525. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  29526. }
  29527. generate( builder ) {
  29528. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  29529. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  29530. }
  29531. }
  29532. /**
  29533. * TSL function for creating a workgroup info node.
  29534. * Creates a new 'workgroup' scoped array buffer.
  29535. *
  29536. * @tsl
  29537. * @function
  29538. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  29539. * @param {number} [count=0] - The number of elements in the buffer.
  29540. * @returns {WorkgroupInfoNode}
  29541. */
  29542. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  29543. /**
  29544. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  29545. * within a shader. In an atomic function, any modification to an atomic variable will
  29546. * occur as an indivisible step with a defined order relative to other modifications.
  29547. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  29548. * atomic operations will not interfere with each other.
  29549. *
  29550. * This node can only be used with a WebGPU backend.
  29551. *
  29552. * @augments Node
  29553. */
  29554. class AtomicFunctionNode extends Node {
  29555. static get type() {
  29556. return 'AtomicFunctionNode';
  29557. }
  29558. /**
  29559. * Constructs a new atomic function node.
  29560. *
  29561. * @param {string} method - The signature of the atomic function to construct.
  29562. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29563. * @param {Node} valueNode - The value that mutates the atomic variable.
  29564. */
  29565. constructor( method, pointerNode, valueNode ) {
  29566. super( 'uint' );
  29567. /**
  29568. * The signature of the atomic function to construct.
  29569. *
  29570. * @type {string}
  29571. */
  29572. this.method = method;
  29573. /**
  29574. * An atomic variable or element of an atomic buffer.
  29575. *
  29576. * @type {Node}
  29577. */
  29578. this.pointerNode = pointerNode;
  29579. /**
  29580. * A value that modifies the atomic variable.
  29581. *
  29582. * @type {Node}
  29583. */
  29584. this.valueNode = valueNode;
  29585. /**
  29586. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  29587. *
  29588. * @type {boolean}
  29589. * @default true
  29590. */
  29591. this.parents = true;
  29592. }
  29593. /**
  29594. * Overwrites the default implementation to return the type of
  29595. * the pointer node.
  29596. *
  29597. * @param {NodeBuilder} builder - The current node builder.
  29598. * @return {string} The input type.
  29599. */
  29600. getInputType( builder ) {
  29601. return this.pointerNode.getNodeType( builder );
  29602. }
  29603. /**
  29604. * Overwritten since the node type is inferred from the input type.
  29605. *
  29606. * @param {NodeBuilder} builder - The current node builder.
  29607. * @return {string} The node type.
  29608. */
  29609. getNodeType( builder ) {
  29610. return this.getInputType( builder );
  29611. }
  29612. generate( builder ) {
  29613. const properties = builder.getNodeProperties( this );
  29614. const parents = properties.parents;
  29615. const method = this.method;
  29616. const type = this.getNodeType( builder );
  29617. const inputType = this.getInputType( builder );
  29618. const a = this.pointerNode;
  29619. const b = this.valueNode;
  29620. const params = [];
  29621. params.push( `&${ a.build( builder, inputType ) }` );
  29622. if ( b !== null ) {
  29623. params.push( b.build( builder, inputType ) );
  29624. }
  29625. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  29626. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  29627. if ( isVoid ) {
  29628. builder.addLineFlowCode( methodSnippet, this );
  29629. } else {
  29630. if ( properties.constNode === undefined ) {
  29631. properties.constNode = expression( methodSnippet, type ).toConst();
  29632. }
  29633. return properties.constNode.build( builder );
  29634. }
  29635. }
  29636. }
  29637. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  29638. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  29639. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  29640. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  29641. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  29642. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  29643. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  29644. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  29645. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  29646. /**
  29647. * TSL function for creating an atomic function node.
  29648. *
  29649. * @tsl
  29650. * @function
  29651. * @param {string} method - The signature of the atomic function to construct.
  29652. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29653. * @param {Node} valueNode - The value that mutates the atomic variable.
  29654. * @returns {AtomicFunctionNode}
  29655. */
  29656. const atomicNode = nodeProxy( AtomicFunctionNode );
  29657. /**
  29658. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  29659. *
  29660. * @tsl
  29661. * @function
  29662. * @param {string} method - The signature of the atomic function to construct.
  29663. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29664. * @param {Node} valueNode - The value that mutates the atomic variable.
  29665. * @returns {AtomicFunctionNode}
  29666. */
  29667. const atomicFunc = ( method, pointerNode, valueNode ) => {
  29668. return atomicNode( method, pointerNode, valueNode ).toStack();
  29669. };
  29670. /**
  29671. * Loads the value stored in the atomic variable.
  29672. *
  29673. * @tsl
  29674. * @function
  29675. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29676. * @returns {AtomicFunctionNode}
  29677. */
  29678. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  29679. /**
  29680. * Stores a value in the atomic variable.
  29681. *
  29682. * @tsl
  29683. * @function
  29684. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29685. * @param {Node} valueNode - The value that mutates the atomic variable.
  29686. * @returns {AtomicFunctionNode}
  29687. */
  29688. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  29689. /**
  29690. * Increments the value stored in the atomic variable.
  29691. *
  29692. * @tsl
  29693. * @function
  29694. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29695. * @param {Node} valueNode - The value that mutates the atomic variable.
  29696. * @returns {AtomicFunctionNode}
  29697. */
  29698. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  29699. /**
  29700. * Decrements the value stored in the atomic variable.
  29701. *
  29702. * @tsl
  29703. * @function
  29704. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29705. * @param {Node} valueNode - The value that mutates the atomic variable.
  29706. * @returns {AtomicFunctionNode}
  29707. */
  29708. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  29709. /**
  29710. * Stores in an atomic variable the maximum between its current value and a parameter.
  29711. *
  29712. * @tsl
  29713. * @function
  29714. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29715. * @param {Node} valueNode - The value that mutates the atomic variable.
  29716. * @returns {AtomicFunctionNode}
  29717. */
  29718. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  29719. /**
  29720. * Stores in an atomic variable the minimum between its current value and a parameter.
  29721. *
  29722. * @tsl
  29723. * @function
  29724. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29725. * @param {Node} valueNode - The value that mutates the atomic variable.
  29726. * @returns {AtomicFunctionNode}
  29727. */
  29728. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  29729. /**
  29730. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  29731. *
  29732. * @tsl
  29733. * @function
  29734. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29735. * @param {Node} valueNode - The value that mutates the atomic variable.
  29736. * @returns {AtomicFunctionNode}
  29737. */
  29738. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  29739. /**
  29740. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  29741. *
  29742. * @tsl
  29743. * @function
  29744. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29745. * @param {Node} valueNode - The value that mutates the atomic variable.
  29746. * @returns {AtomicFunctionNode}
  29747. */
  29748. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  29749. /**
  29750. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  29751. *
  29752. * @tsl
  29753. * @function
  29754. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29755. * @param {Node} valueNode - The value that mutates the atomic variable.
  29756. * @returns {AtomicFunctionNode}
  29757. */
  29758. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  29759. /**
  29760. * This class represents a set of built in WGSL shader functions that sync
  29761. * synchronously execute an operation across a subgroup, or 'warp', of compute
  29762. * or fragment shader invocations within a workgroup. Typically, these functions
  29763. * will synchronously execute an operation using data from all active invocations
  29764. * within the subgroup, then broadcast that result to all active invocations. In
  29765. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  29766. * (DirectX/HLSL) or warp intrinsics (CUDA).
  29767. *
  29768. * @augments TempNode
  29769. */
  29770. class SubgroupFunctionNode extends TempNode {
  29771. static get type() {
  29772. return 'SubgroupFunctionNode';
  29773. }
  29774. /**
  29775. * Constructs a new function node.
  29776. *
  29777. * @param {string} method - The subgroup/wave intrinsic method to construct.
  29778. * @param {Node} [aNode=null] - The method's first argument.
  29779. * @param {Node} [bNode=null] - The method's second argument.
  29780. */
  29781. constructor( method, aNode = null, bNode = null ) {
  29782. super();
  29783. /**
  29784. * The subgroup/wave intrinsic method to construct.
  29785. *
  29786. * @type {String}
  29787. */
  29788. this.method = method;
  29789. /**
  29790. * The method's first argument.
  29791. *
  29792. * @type {Node}
  29793. */
  29794. this.aNode = aNode;
  29795. /**
  29796. * The method's second argument.
  29797. *
  29798. * @type {Node}
  29799. */
  29800. this.bNode = bNode;
  29801. }
  29802. getInputType( builder ) {
  29803. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  29804. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  29805. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  29806. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  29807. if ( aLen > bLen ) {
  29808. return aType;
  29809. } else {
  29810. return bType;
  29811. }
  29812. }
  29813. getNodeType( builder ) {
  29814. const method = this.method;
  29815. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  29816. return 'bool';
  29817. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  29818. return 'uvec4';
  29819. } else {
  29820. return this.getInputType( builder );
  29821. }
  29822. }
  29823. generate( builder, output ) {
  29824. const method = this.method;
  29825. const type = this.getNodeType( builder );
  29826. const inputType = this.getInputType( builder );
  29827. const a = this.aNode;
  29828. const b = this.bNode;
  29829. const params = [];
  29830. if (
  29831. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  29832. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  29833. method === SubgroupFunctionNode.QUAD_BROADCAST
  29834. ) {
  29835. const bType = b.getNodeType( builder );
  29836. params.push(
  29837. a.build( builder, type ),
  29838. b.build( builder, bType === 'float' ? 'int' : type )
  29839. );
  29840. } else if (
  29841. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  29842. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  29843. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  29844. ) {
  29845. params.push(
  29846. a.build( builder, type ),
  29847. b.build( builder, 'uint' )
  29848. );
  29849. } else {
  29850. if ( a !== null ) params.push( a.build( builder, inputType ) );
  29851. if ( b !== null ) params.push( b.build( builder, inputType ) );
  29852. }
  29853. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  29854. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  29855. }
  29856. serialize( data ) {
  29857. super.serialize( data );
  29858. data.method = this.method;
  29859. }
  29860. deserialize( data ) {
  29861. super.deserialize( data );
  29862. this.method = data.method;
  29863. }
  29864. }
  29865. // 0 inputs
  29866. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  29867. // 1 input
  29868. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  29869. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  29870. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  29871. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  29872. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  29873. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  29874. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  29875. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  29876. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  29877. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  29878. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  29879. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  29880. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  29881. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  29882. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  29883. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  29884. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  29885. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  29886. // 2 inputs
  29887. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  29888. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  29889. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  29890. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  29891. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  29892. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  29893. /**
  29894. * Returns true if this invocation has the lowest subgroup_invocation_id
  29895. * among active invocations in the subgroup.
  29896. *
  29897. * @tsl
  29898. * @method
  29899. * @return {bool} The result of the computation.
  29900. */
  29901. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  29902. /**
  29903. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  29904. * is 1 if pred is true for that active invocation and 0 otherwise.
  29905. *
  29906. * @tsl
  29907. * @method
  29908. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  29909. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  29910. */
  29911. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  29912. /**
  29913. * A reduction that adds e among all active invocations and returns that result.
  29914. *
  29915. * @tsl
  29916. * @method
  29917. * @param {number} e - The value provided to the reduction by the current invocation.
  29918. * @return {number} The accumulated result of the reduction operation.
  29919. */
  29920. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  29921. /**
  29922. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  29923. *
  29924. * @tsl
  29925. * @method
  29926. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  29927. * @return {number} The accumulated result of the inclusive scan operation.
  29928. */
  29929. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  29930. /**
  29931. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  29932. *
  29933. * @tsl
  29934. * @method
  29935. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  29936. * @return {number} The accumulated result of the exclusive scan operation.
  29937. */
  29938. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  29939. /**
  29940. * A reduction that multiplies e among all active invocations and returns that result.
  29941. *
  29942. * @tsl
  29943. * @method
  29944. * @param {number} e - The value provided to the reduction by the current invocation.
  29945. * @return {number} The accumulated result of the reduction operation.
  29946. */
  29947. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  29948. /**
  29949. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  29950. *
  29951. * @tsl
  29952. * @method
  29953. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  29954. * @return {number} The accumulated result of the inclusive scan operation.
  29955. */
  29956. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  29957. /**
  29958. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  29959. *
  29960. * @tsl
  29961. * @method
  29962. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  29963. * @return {number} The accumulated result of the exclusive scan operation.
  29964. */
  29965. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  29966. /**
  29967. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  29968. *
  29969. * @tsl
  29970. * @method
  29971. * @param {number} e - The value provided to the reduction by the current invocation.
  29972. * @return {number} The result of the reduction operation.
  29973. */
  29974. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  29975. /**
  29976. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  29977. *
  29978. * @tsl
  29979. * @method
  29980. * @param {number} e - The value provided to the reduction by the current invocation.
  29981. * @return {number} The result of the reduction operation.
  29982. */
  29983. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  29984. /**
  29985. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  29986. *
  29987. * @tsl
  29988. * @method
  29989. * @param {number} e - The value provided to the reduction by the current invocation.
  29990. * @return {number} The result of the reduction operation.
  29991. */
  29992. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  29993. /**
  29994. * A reduction that performs a min of e among all active invocations and returns that result.
  29995. *
  29996. * @tsl
  29997. * @method
  29998. * @param {number} e - The value provided to the reduction by the current invocation.
  29999. * @return {number} The result of the reduction operation.
  30000. */
  30001. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  30002. /**
  30003. * A reduction that performs a max of e among all active invocations and returns that result.
  30004. *
  30005. * @tsl
  30006. * @method
  30007. * @param {number} e - The value provided to the reduction by the current invocation.
  30008. * @return {number} The result of the reduction operation.
  30009. */
  30010. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  30011. /**
  30012. * Returns true if e is true for all active invocations in the subgroup.
  30013. *
  30014. * @tsl
  30015. * @method
  30016. * @return {bool} The result of the computation.
  30017. */
  30018. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  30019. /**
  30020. * Returns true if e is true for any active invocation in the subgroup
  30021. *
  30022. * @tsl
  30023. * @method
  30024. * @return {bool} The result of the computation.
  30025. */
  30026. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  30027. /**
  30028. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  30029. *
  30030. * @tsl
  30031. * @method
  30032. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  30033. * @param {number} id - The subgroup invocation to broadcast from.
  30034. * @return {number} The broadcast value.
  30035. */
  30036. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  30037. /**
  30038. * Swaps e between invocations in the quad in the X direction.
  30039. *
  30040. * @tsl
  30041. * @method
  30042. * @param {number} e - The value to swap from the current invocation.
  30043. * @return {number} The value received from the swap operation.
  30044. */
  30045. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  30046. /**
  30047. * Swaps e between invocations in the quad in the Y direction.
  30048. *
  30049. * @tsl
  30050. * @method
  30051. * @param {number} e - The value to swap from the current invocation.
  30052. * @return {number} The value received from the swap operation.
  30053. */
  30054. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  30055. /**
  30056. * Swaps e between invocations in the quad diagonally.
  30057. *
  30058. * @tsl
  30059. * @method
  30060. * @param {number} e - The value to swap from the current invocation.
  30061. * @return {number} The value received from the swap operation.
  30062. */
  30063. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  30064. /**
  30065. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  30066. *
  30067. * @tsl
  30068. * @method
  30069. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  30070. * @param {number} id - The subgroup invocation to broadcast from.
  30071. * @return {number} The broadcast value.
  30072. */
  30073. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  30074. /**
  30075. * Returns v from the active invocation whose subgroup_invocation_id matches id
  30076. *
  30077. * @tsl
  30078. * @method
  30079. * @param {number} v - The value to return from subgroup invocation id^mask.
  30080. * @param {number} id - The subgroup invocation which returns the value v.
  30081. * @return {number} The broadcast value.
  30082. */
  30083. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  30084. /**
  30085. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  30086. *
  30087. * @tsl
  30088. * @method
  30089. * @param {number} v - The value to return from subgroup invocation id^mask.
  30090. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  30091. * @return {number} The broadcast value.
  30092. */
  30093. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  30094. /**
  30095. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  30096. *
  30097. * @tsl
  30098. * @method
  30099. * @param {number} v - The value to return from subgroup invocation id^mask.
  30100. * @param {number} delta - A value that offsets the current in.
  30101. * @return {number} The broadcast value.
  30102. */
  30103. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  30104. /**
  30105. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  30106. *
  30107. * @tsl
  30108. * @method
  30109. * @param {number} v - The value to return from subgroup invocation id^mask.
  30110. * @param {number} delta - A value that offsets the current subgroup invocation.
  30111. * @return {number} The broadcast value.
  30112. */
  30113. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  30114. /**
  30115. * Broadcasts e from the quad invocation with id equal to id.
  30116. *
  30117. * @tsl
  30118. * @method
  30119. * @param {number} e - The value to broadcast.
  30120. * @return {number} The broadcast value.
  30121. */
  30122. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  30123. let uniformsLib;
  30124. function getLightData( light ) {
  30125. uniformsLib = uniformsLib || new WeakMap();
  30126. let uniforms = uniformsLib.get( light );
  30127. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  30128. return uniforms;
  30129. }
  30130. /**
  30131. * TSL function for getting a shadow matrix uniform node for the given light.
  30132. *
  30133. * @tsl
  30134. * @function
  30135. * @param {Light} light -The light source.
  30136. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  30137. */
  30138. function lightShadowMatrix( light ) {
  30139. const data = getLightData( light );
  30140. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  30141. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  30142. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  30143. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  30144. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  30145. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  30146. light.shadow.camera.updateProjectionMatrix();
  30147. }
  30148. light.shadow.updateMatrices( light );
  30149. }
  30150. return light.shadow.matrix;
  30151. } ) );
  30152. }
  30153. /**
  30154. * TSL function for getting projected uv coordinates for the given light.
  30155. * Relevant when using maps with spot lights.
  30156. *
  30157. * @tsl
  30158. * @function
  30159. * @param {Light} light -The light source.
  30160. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  30161. * @returns {Node<vec3>} The projected uvs.
  30162. */
  30163. function lightProjectionUV( light, position = positionWorld ) {
  30164. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  30165. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  30166. return projectionUV;
  30167. }
  30168. /**
  30169. * TSL function for getting the position in world space for the given light.
  30170. *
  30171. * @tsl
  30172. * @function
  30173. * @param {Light} light -The light source.
  30174. * @returns {UniformNode<vec3>} The light's position in world space.
  30175. */
  30176. function lightPosition( light ) {
  30177. const data = getLightData( light );
  30178. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  30179. }
  30180. /**
  30181. * TSL function for getting the light target position in world space for the given light.
  30182. *
  30183. * @tsl
  30184. * @function
  30185. * @param {Light} light -The light source.
  30186. * @returns {UniformNode<vec3>} The light target position in world space.
  30187. */
  30188. function lightTargetPosition( light ) {
  30189. const data = getLightData( light );
  30190. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  30191. }
  30192. /**
  30193. * TSL function for getting the position in view space for the given light.
  30194. *
  30195. * @tsl
  30196. * @function
  30197. * @param {Light} light - The light source.
  30198. * @returns {UniformNode<vec3>} The light's position in view space.
  30199. */
  30200. function lightViewPosition( light ) {
  30201. const data = getLightData( light );
  30202. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  30203. self.value = self.value || new Vector3();
  30204. self.value.setFromMatrixPosition( light.matrixWorld );
  30205. self.value.applyMatrix4( camera.matrixWorldInverse );
  30206. } ) );
  30207. }
  30208. /**
  30209. * TSL function for getting the light target direction for the given light.
  30210. *
  30211. * @tsl
  30212. * @function
  30213. * @param {Light} light -The light source.
  30214. * @returns {Node<vec3>} The light's target direction.
  30215. */
  30216. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  30217. const sortLights = ( lights ) => {
  30218. return lights.sort( ( a, b ) => a.id - b.id );
  30219. };
  30220. const getLightNodeById = ( id, lightNodes ) => {
  30221. for ( const lightNode of lightNodes ) {
  30222. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  30223. return lightNode;
  30224. }
  30225. }
  30226. return null;
  30227. };
  30228. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  30229. const _hashData = [];
  30230. /**
  30231. * This node represents the scene's lighting and manages the lighting model's life cycle
  30232. * for the current build 3D object. It is responsible for computing the total outgoing
  30233. * light in a given lighting context.
  30234. *
  30235. * @augments Node
  30236. */
  30237. class LightsNode extends Node {
  30238. static get type() {
  30239. return 'LightsNode';
  30240. }
  30241. /**
  30242. * Constructs a new lights node.
  30243. */
  30244. constructor() {
  30245. super( 'vec3' );
  30246. /**
  30247. * A node representing the total diffuse light.
  30248. *
  30249. * @type {Node<vec3>}
  30250. */
  30251. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  30252. /**
  30253. * A node representing the total specular light.
  30254. *
  30255. * @type {Node<vec3>}
  30256. */
  30257. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  30258. /**
  30259. * A node representing the outgoing light.
  30260. *
  30261. * @type {Node<vec3>}
  30262. */
  30263. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  30264. /**
  30265. * An array representing the lights in the scene.
  30266. *
  30267. * @private
  30268. * @type {Array<Light>}
  30269. */
  30270. this._lights = [];
  30271. /**
  30272. * For each light in the scene, this node will create a
  30273. * corresponding light node.
  30274. *
  30275. * @private
  30276. * @type {?Array<LightingNode>}
  30277. * @default null
  30278. */
  30279. this._lightNodes = null;
  30280. /**
  30281. * A hash for identifying the current light nodes setup.
  30282. *
  30283. * @private
  30284. * @type {?string}
  30285. * @default null
  30286. */
  30287. this._lightNodesHash = null;
  30288. /**
  30289. * `LightsNode` sets this property to `true` by default.
  30290. *
  30291. * @type {boolean}
  30292. * @default true
  30293. */
  30294. this.global = true;
  30295. }
  30296. /**
  30297. * Overwrites the default {@link Node#customCacheKey} implementation by including
  30298. * light data into the cache key.
  30299. *
  30300. * @return {number} The custom cache key.
  30301. */
  30302. customCacheKey() {
  30303. const lights = this._lights;
  30304. for ( let i = 0; i < lights.length; i ++ ) {
  30305. const light = lights[ i ];
  30306. _hashData.push( light.id );
  30307. _hashData.push( light.castShadow ? 1 : 0 );
  30308. if ( light.isSpotLight === true ) {
  30309. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  30310. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  30311. _hashData.push( hashMap, hashColorNode );
  30312. }
  30313. }
  30314. const cacheKey = hashArray( _hashData );
  30315. _hashData.length = 0;
  30316. return cacheKey;
  30317. }
  30318. /**
  30319. * Computes a hash value for identifying the current light nodes setup.
  30320. *
  30321. * @param {NodeBuilder} builder - A reference to the current node builder.
  30322. * @return {string} The computed hash.
  30323. */
  30324. getHash( builder ) {
  30325. if ( this._lightNodesHash === null ) {
  30326. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30327. const hash = [];
  30328. for ( const lightNode of this._lightNodes ) {
  30329. hash.push( lightNode.getHash() );
  30330. }
  30331. this._lightNodesHash = 'lights-' + hash.join( ',' );
  30332. }
  30333. return this._lightNodesHash;
  30334. }
  30335. analyze( builder ) {
  30336. const properties = builder.getNodeProperties( this );
  30337. for ( const node of properties.nodes ) {
  30338. node.build( builder );
  30339. }
  30340. properties.outputNode.build( builder );
  30341. }
  30342. /**
  30343. * Creates lighting nodes for each scene light. This makes it possible to further
  30344. * process lights in the node system.
  30345. *
  30346. * @param {NodeBuilder} builder - A reference to the current node builder.
  30347. */
  30348. setupLightsNode( builder ) {
  30349. const lightNodes = [];
  30350. const previousLightNodes = this._lightNodes;
  30351. const lights = sortLights( this._lights );
  30352. const nodeLibrary = builder.renderer.library;
  30353. for ( const light of lights ) {
  30354. if ( light.isNode ) {
  30355. lightNodes.push( nodeObject( light ) );
  30356. } else {
  30357. let lightNode = null;
  30358. if ( previousLightNodes !== null ) {
  30359. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  30360. }
  30361. if ( lightNode === null ) {
  30362. // find the corresponding node type for a given light
  30363. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  30364. if ( lightNodeClass === null ) {
  30365. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  30366. continue;
  30367. }
  30368. let lightNode = null;
  30369. if ( ! _lightsNodeRef.has( light ) ) {
  30370. lightNode = nodeObject( new lightNodeClass( light ) );
  30371. _lightsNodeRef.set( light, lightNode );
  30372. } else {
  30373. lightNode = _lightsNodeRef.get( light );
  30374. }
  30375. lightNodes.push( lightNode );
  30376. }
  30377. }
  30378. }
  30379. this._lightNodes = lightNodes;
  30380. }
  30381. /**
  30382. * Sets up a direct light in the lighting model.
  30383. *
  30384. * @param {Object} builder - The builder object containing the context and stack.
  30385. * @param {Object} lightNode - The light node.
  30386. * @param {Object} lightData - The light object containing color and direction properties.
  30387. */
  30388. setupDirectLight( builder, lightNode, lightData ) {
  30389. const { lightingModel, reflectedLight } = builder.context;
  30390. lightingModel.direct( {
  30391. ...lightData,
  30392. lightNode,
  30393. reflectedLight
  30394. }, builder );
  30395. }
  30396. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  30397. const { lightingModel, reflectedLight } = builder.context;
  30398. lightingModel.directRectArea( {
  30399. ...lightData,
  30400. lightNode,
  30401. reflectedLight
  30402. }, builder );
  30403. }
  30404. /**
  30405. * Setups the internal lights by building all respective
  30406. * light nodes.
  30407. *
  30408. * @param {NodeBuilder} builder - A reference to the current node builder.
  30409. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  30410. */
  30411. setupLights( builder, lightNodes ) {
  30412. for ( const lightNode of lightNodes ) {
  30413. lightNode.build( builder );
  30414. }
  30415. }
  30416. getLightNodes( builder ) {
  30417. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30418. return this._lightNodes;
  30419. }
  30420. /**
  30421. * The implementation makes sure that for each light in the scene
  30422. * there is a corresponding light node. By building the light nodes
  30423. * and evaluating the lighting model the outgoing light is computed.
  30424. *
  30425. * @param {NodeBuilder} builder - A reference to the current node builder.
  30426. * @return {Node<vec3>} A node representing the outgoing light.
  30427. */
  30428. setup( builder ) {
  30429. const currentLightsNode = builder.lightsNode;
  30430. builder.lightsNode = this;
  30431. //
  30432. let outgoingLightNode = this.outgoingLightNode;
  30433. const context = builder.context;
  30434. const lightingModel = context.lightingModel;
  30435. const properties = builder.getNodeProperties( this );
  30436. if ( lightingModel ) {
  30437. const { totalDiffuseNode, totalSpecularNode } = this;
  30438. context.outgoingLight = outgoingLightNode;
  30439. const stack = builder.addStack();
  30440. //
  30441. properties.nodes = stack.nodes;
  30442. //
  30443. lightingModel.start( builder );
  30444. //
  30445. const { backdrop, backdropAlpha } = context;
  30446. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  30447. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  30448. if ( backdrop !== null ) {
  30449. if ( backdropAlpha !== null ) {
  30450. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  30451. } else {
  30452. totalDiffuse = vec3( backdrop );
  30453. }
  30454. }
  30455. totalDiffuseNode.assign( totalDiffuse );
  30456. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  30457. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  30458. //
  30459. lightingModel.finish( builder );
  30460. //
  30461. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  30462. } else {
  30463. properties.nodes = [];
  30464. }
  30465. //
  30466. builder.lightsNode = currentLightsNode;
  30467. return outgoingLightNode;
  30468. }
  30469. /**
  30470. * Configures this node with an array of lights.
  30471. *
  30472. * @param {Array<Light>} lights - An array of lights.
  30473. * @return {LightsNode} A reference to this node.
  30474. */
  30475. setLights( lights ) {
  30476. this._lights = lights;
  30477. this._lightNodes = null;
  30478. this._lightNodesHash = null;
  30479. return this;
  30480. }
  30481. /**
  30482. * Returns an array of the scene's lights.
  30483. *
  30484. * @return {Array<Light>} The scene's lights.
  30485. */
  30486. getLights() {
  30487. return this._lights;
  30488. }
  30489. /**
  30490. * Whether the scene has lights or not.
  30491. *
  30492. * @type {boolean}
  30493. */
  30494. get hasLights() {
  30495. return this._lights.length > 0;
  30496. }
  30497. }
  30498. /**
  30499. * TSL function for creating an instance of `LightsNode` and configuring
  30500. * it with the given array of lights.
  30501. *
  30502. * @tsl
  30503. * @function
  30504. * @param {Array<Light>} lights - An array of lights.
  30505. * @return {LightsNode} The created lights node.
  30506. */
  30507. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  30508. /**
  30509. * Base class for all shadow nodes.
  30510. *
  30511. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  30512. * Lighting nodes might share the same shadow node type or use specific ones depending on
  30513. * their requirements.
  30514. *
  30515. * @augments Node
  30516. */
  30517. class ShadowBaseNode extends Node {
  30518. static get type() {
  30519. return 'ShadowBaseNode';
  30520. }
  30521. /**
  30522. * Constructs a new shadow base node.
  30523. *
  30524. * @param {Light} light - The shadow casting light.
  30525. */
  30526. constructor( light ) {
  30527. super();
  30528. /**
  30529. * The shadow casting light.
  30530. *
  30531. * @type {Light}
  30532. */
  30533. this.light = light;
  30534. /**
  30535. * Overwritten since shadows are updated by default per render.
  30536. *
  30537. * @type {string}
  30538. * @default 'render'
  30539. */
  30540. this.updateBeforeType = NodeUpdateType.RENDER;
  30541. /**
  30542. * This flag can be used for type testing.
  30543. *
  30544. * @type {boolean}
  30545. * @readonly
  30546. * @default true
  30547. */
  30548. this.isShadowBaseNode = true;
  30549. }
  30550. /**
  30551. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  30552. *
  30553. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  30554. */
  30555. setupShadowPosition( { context, material } ) {
  30556. // Use assign inside an Fn()
  30557. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  30558. }
  30559. }
  30560. /**
  30561. * TSL object that represents the vertex position in world space during the shadow pass.
  30562. *
  30563. * @tsl
  30564. * @type {Node<vec3>}
  30565. */
  30566. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  30567. /**
  30568. * Saves the state of the given renderer and stores it into the given state object.
  30569. *
  30570. * If not state object is provided, the function creates one.
  30571. *
  30572. * @private
  30573. * @function
  30574. * @param {Renderer} renderer - The renderer.
  30575. * @param {Object} [state={}] - The state.
  30576. * @return {Object} The state.
  30577. */
  30578. function saveRendererState( renderer, state = {} ) {
  30579. state.toneMapping = renderer.toneMapping;
  30580. state.toneMappingExposure = renderer.toneMappingExposure;
  30581. state.outputColorSpace = renderer.outputColorSpace;
  30582. state.renderTarget = renderer.getRenderTarget();
  30583. state.activeCubeFace = renderer.getActiveCubeFace();
  30584. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  30585. state.renderObjectFunction = renderer.getRenderObjectFunction();
  30586. state.pixelRatio = renderer.getPixelRatio();
  30587. state.mrt = renderer.getMRT();
  30588. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  30589. state.clearAlpha = renderer.getClearAlpha();
  30590. state.autoClear = renderer.autoClear;
  30591. state.scissorTest = renderer.getScissorTest();
  30592. return state;
  30593. }
  30594. /**
  30595. * Saves the state of the given renderer and stores it into the given state object.
  30596. * Besides, the function also resets the state of the renderer to its default values.
  30597. *
  30598. * If not state object is provided, the function creates one.
  30599. *
  30600. * @private
  30601. * @function
  30602. * @param {Renderer} renderer - The renderer.
  30603. * @param {Object} [state={}] - The state.
  30604. * @return {Object} The state.
  30605. */
  30606. function resetRendererState( renderer, state ) {
  30607. state = saveRendererState( renderer, state );
  30608. renderer.setMRT( null );
  30609. renderer.setRenderObjectFunction( null );
  30610. renderer.setClearColor( 0x000000, 1 );
  30611. renderer.autoClear = true;
  30612. return state;
  30613. }
  30614. /**
  30615. * Restores the state of the given renderer from the given state object.
  30616. *
  30617. * @private
  30618. * @function
  30619. * @param {Renderer} renderer - The renderer.
  30620. * @param {Object} state - The state to restore.
  30621. */
  30622. function restoreRendererState( renderer, state ) {
  30623. renderer.toneMapping = state.toneMapping;
  30624. renderer.toneMappingExposure = state.toneMappingExposure;
  30625. renderer.outputColorSpace = state.outputColorSpace;
  30626. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  30627. renderer.setRenderObjectFunction( state.renderObjectFunction );
  30628. renderer.setPixelRatio( state.pixelRatio );
  30629. renderer.setMRT( state.mrt );
  30630. renderer.setClearColor( state.clearColor, state.clearAlpha );
  30631. renderer.autoClear = state.autoClear;
  30632. renderer.setScissorTest( state.scissorTest );
  30633. }
  30634. /**
  30635. * Saves the state of the given scene and stores it into the given state object.
  30636. *
  30637. * If not state object is provided, the function creates one.
  30638. *
  30639. * @private
  30640. * @function
  30641. * @param {Scene} scene - The scene.
  30642. * @param {Object} [state={}] - The state.
  30643. * @return {Object} The state.
  30644. */
  30645. function saveSceneState( scene, state = {} ) {
  30646. state.background = scene.background;
  30647. state.backgroundNode = scene.backgroundNode;
  30648. state.overrideMaterial = scene.overrideMaterial;
  30649. return state;
  30650. }
  30651. /**
  30652. * Saves the state of the given scene and stores it into the given state object.
  30653. * Besides, the function also resets the state of the scene to its default values.
  30654. *
  30655. * If not state object is provided, the function creates one.
  30656. *
  30657. * @private
  30658. * @function
  30659. * @param {Scene} scene - The scene.
  30660. * @param {Object} [state={}] - The state.
  30661. * @return {Object} The state.
  30662. */
  30663. function resetSceneState( scene, state ) {
  30664. state = saveSceneState( scene, state );
  30665. scene.background = null;
  30666. scene.backgroundNode = null;
  30667. scene.overrideMaterial = null;
  30668. return state;
  30669. }
  30670. /**
  30671. * Restores the state of the given scene from the given state object.
  30672. *
  30673. * @private
  30674. * @function
  30675. * @param {Scene} scene - The scene.
  30676. * @param {Object} state - The state to restore.
  30677. */
  30678. function restoreSceneState( scene, state ) {
  30679. scene.background = state.background;
  30680. scene.backgroundNode = state.backgroundNode;
  30681. scene.overrideMaterial = state.overrideMaterial;
  30682. }
  30683. /**
  30684. * Saves the state of the given renderer and scene and stores it into the given state object.
  30685. *
  30686. * If not state object is provided, the function creates one.
  30687. *
  30688. * @private
  30689. * @function
  30690. * @param {Renderer} renderer - The renderer.
  30691. * @param {Scene} scene - The scene.
  30692. * @param {Object} [state={}] - The state.
  30693. * @return {Object} The state.
  30694. */
  30695. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  30696. state = saveRendererState( renderer, state );
  30697. state = saveSceneState( scene, state );
  30698. return state;
  30699. }
  30700. /**
  30701. * Saves the state of the given renderer and scene and stores it into the given state object.
  30702. * Besides, the function also resets the state of the renderer and scene to its default values.
  30703. *
  30704. * If not state object is provided, the function creates one.
  30705. *
  30706. * @private
  30707. * @function
  30708. * @param {Renderer} renderer - The renderer.
  30709. * @param {Scene} scene - The scene.
  30710. * @param {Object} [state={}] - The state.
  30711. * @return {Object} The state.
  30712. */
  30713. function resetRendererAndSceneState( renderer, scene, state ) {
  30714. state = resetRendererState( renderer, state );
  30715. state = resetSceneState( scene, state );
  30716. return state;
  30717. }
  30718. /**
  30719. * Restores the state of the given renderer and scene from the given state object.
  30720. *
  30721. * @private
  30722. * @function
  30723. * @param {Renderer} renderer - The renderer.
  30724. * @param {Scene} scene - The scene.
  30725. * @param {Object} state - The state to restore.
  30726. */
  30727. function restoreRendererAndSceneState( renderer, scene, state ) {
  30728. restoreRendererState( renderer, state );
  30729. restoreSceneState( scene, state );
  30730. }
  30731. var RendererUtils = /*#__PURE__*/Object.freeze({
  30732. __proto__: null,
  30733. resetRendererAndSceneState: resetRendererAndSceneState,
  30734. resetRendererState: resetRendererState,
  30735. resetSceneState: resetSceneState,
  30736. restoreRendererAndSceneState: restoreRendererAndSceneState,
  30737. restoreRendererState: restoreRendererState,
  30738. restoreSceneState: restoreSceneState,
  30739. saveRendererAndSceneState: saveRendererAndSceneState,
  30740. saveRendererState: saveRendererState,
  30741. saveSceneState: saveSceneState
  30742. });
  30743. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  30744. /**
  30745. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  30746. * with a binary `[0,1]` result.
  30747. *
  30748. * @method
  30749. * @param {Object} inputs - The input parameter object.
  30750. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30751. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30752. * @return {Node<float>} The filtering result.
  30753. */
  30754. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  30755. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  30756. if ( depthTexture.isArrayTexture ) {
  30757. basic = basic.depth( depthLayer );
  30758. }
  30759. return basic.compare( shadowCoord.z );
  30760. } );
  30761. /**
  30762. * A shadow filtering function performing PCF filtering.
  30763. *
  30764. * @method
  30765. * @param {Object} inputs - The input parameter object.
  30766. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30767. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30768. * @param {LightShadow} inputs.shadow - The light shadow.
  30769. * @return {Node<float>} The filtering result.
  30770. */
  30771. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30772. const depthCompare = ( uv, compare ) => {
  30773. let depth = texture( depthTexture, uv );
  30774. if ( depthTexture.isArrayTexture ) {
  30775. depth = depth.depth( depthLayer );
  30776. }
  30777. return depth.compare( compare );
  30778. };
  30779. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30780. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30781. const texelSize = vec2( 1 ).div( mapSize );
  30782. const dx0 = texelSize.x.negate().mul( radius );
  30783. const dy0 = texelSize.y.negate().mul( radius );
  30784. const dx1 = texelSize.x.mul( radius );
  30785. const dy1 = texelSize.y.mul( radius );
  30786. const dx2 = dx0.div( 2 );
  30787. const dy2 = dy0.div( 2 );
  30788. const dx3 = dx1.div( 2 );
  30789. const dy3 = dy1.div( 2 );
  30790. return add(
  30791. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  30792. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  30793. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  30794. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  30795. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  30796. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  30797. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  30798. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  30799. depthCompare( shadowCoord.xy, shadowCoord.z ),
  30800. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  30801. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  30802. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  30803. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  30804. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  30805. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  30806. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  30807. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  30808. ).mul( 1 / 17 );
  30809. } );
  30810. /**
  30811. * A shadow filtering function performing PCF soft filtering.
  30812. *
  30813. * @method
  30814. * @param {Object} inputs - The input parameter object.
  30815. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30816. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30817. * @param {LightShadow} inputs.shadow - The light shadow.
  30818. * @return {Node<float>} The filtering result.
  30819. */
  30820. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30821. const depthCompare = ( uv, compare ) => {
  30822. let depth = texture( depthTexture, uv );
  30823. if ( depthTexture.isArrayTexture ) {
  30824. depth = depth.depth( depthLayer );
  30825. }
  30826. return depth.compare( compare );
  30827. };
  30828. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30829. const texelSize = vec2( 1 ).div( mapSize );
  30830. const dx = texelSize.x;
  30831. const dy = texelSize.y;
  30832. const uv = shadowCoord.xy;
  30833. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  30834. uv.subAssign( f.mul( texelSize ) );
  30835. return add(
  30836. depthCompare( uv, shadowCoord.z ),
  30837. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  30838. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  30839. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  30840. mix(
  30841. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  30842. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  30843. f.x
  30844. ),
  30845. mix(
  30846. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  30847. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  30848. f.x
  30849. ),
  30850. mix(
  30851. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  30852. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  30853. f.y
  30854. ),
  30855. mix(
  30856. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  30857. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  30858. f.y
  30859. ),
  30860. mix(
  30861. mix(
  30862. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  30863. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  30864. f.x
  30865. ),
  30866. mix(
  30867. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  30868. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  30869. f.x
  30870. ),
  30871. f.y
  30872. )
  30873. ).mul( 1 / 9 );
  30874. } );
  30875. /**
  30876. * A shadow filtering function performing VSM filtering.
  30877. *
  30878. * @method
  30879. * @param {Object} inputs - The input parameter object.
  30880. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30881. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30882. * @return {Node<float>} The filtering result.
  30883. */
  30884. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  30885. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  30886. if ( depthTexture.isArrayTexture ) {
  30887. distribution = distribution.depth( depthLayer );
  30888. }
  30889. distribution = distribution.rg;
  30890. const mean = distribution.x;
  30891. const variance = max$1( 0.0000001, distribution.y.mul( distribution.y ) );
  30892. const hardShadow = step( shadowCoord.z, mean );
  30893. // Early return if fully lit
  30894. If( hardShadow.equal( 1.0 ), () => {
  30895. return float( 1.0 );
  30896. } );
  30897. // Distance from mean
  30898. const d = shadowCoord.z.sub( mean );
  30899. // Chebyshev's inequality for upper bound on probability
  30900. let p_max = variance.div( variance.add( d.mul( d ) ) );
  30901. // Reduce light bleeding by remapping [amount, 1] to [0, 1]
  30902. p_max = clamp( sub( p_max, 0.3 ).div( 0.65 ) );
  30903. return max$1( hardShadow, p_max );
  30904. } );
  30905. //
  30906. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  30907. let dist = positionWorld.sub( position ).length();
  30908. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  30909. dist = dist.saturate(); // clamp to [ 0, 1 ]
  30910. return dist;
  30911. } );
  30912. const linearShadowDistance = ( light ) => {
  30913. const camera = light.shadow.camera;
  30914. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  30915. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  30916. const referencePosition = objectPosition( light );
  30917. return linearDistance( referencePosition, nearDistance, farDistance );
  30918. };
  30919. /**
  30920. * Retrieves or creates a shadow material for the given light source.
  30921. *
  30922. * This function checks if a shadow material already exists for the provided light.
  30923. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  30924. * in the `shadowMaterialLib` for future use.
  30925. *
  30926. * @tsl
  30927. * @function
  30928. * @param {Light} light - The light source for which the shadow material is needed.
  30929. * If the light is a point light, a depth node is calculated
  30930. * using the linear shadow distance.
  30931. * @returns {NodeMaterial} The shadow material associated with the given light.
  30932. */
  30933. const getShadowMaterial = ( light ) => {
  30934. let material = shadowMaterialLib.get( light );
  30935. if ( material === undefined ) {
  30936. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  30937. material = new NodeMaterial();
  30938. material.colorNode = vec4( 0, 0, 0, 1 );
  30939. material.depthNode = depthNode;
  30940. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  30941. material.name = 'ShadowMaterial';
  30942. material.fog = false;
  30943. shadowMaterialLib.set( light, material );
  30944. }
  30945. return material;
  30946. };
  30947. //
  30948. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  30949. const _shadowRenderObjectKeys = [];
  30950. /**
  30951. * Creates a function to render shadow objects in a scene.
  30952. *
  30953. * @tsl
  30954. * @function
  30955. * @param {Renderer} renderer - The renderer.
  30956. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  30957. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  30958. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  30959. * @return {shadowRenderObjectFunction} A function that renders shadow objects.
  30960. */
  30961. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  30962. _shadowRenderObjectKeys[ 0 ] = renderer;
  30963. _shadowRenderObjectKeys[ 1 ] = shadow;
  30964. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  30965. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  30966. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  30967. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  30968. if ( useVelocity ) {
  30969. getDataFromObject( object ).useVelocity = true;
  30970. }
  30971. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  30972. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  30973. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  30974. }
  30975. };
  30976. renderObjectFunction.shadowType = shadowType;
  30977. renderObjectFunction.useVelocity = useVelocity;
  30978. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  30979. }
  30980. _shadowRenderObjectKeys[ 0 ] = null;
  30981. _shadowRenderObjectKeys[ 1 ] = null;
  30982. return renderObjectFunction;
  30983. };
  30984. /**
  30985. * Represents the shader code for the first VSM render pass.
  30986. *
  30987. * @private
  30988. * @method
  30989. * @param {Object} inputs - The input parameter object.
  30990. * @param {Node<float>} inputs.samples - The number of samples
  30991. * @param {Node<float>} inputs.radius - The radius.
  30992. * @param {Node<float>} inputs.size - The size.
  30993. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  30994. * @return {Node<vec2>} The VSM output.
  30995. */
  30996. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  30997. const mean = float( 0 ).toVar( 'meanVertical' );
  30998. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  30999. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31000. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31001. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31002. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31003. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  31004. if ( shadowPass.value.isArrayTexture ) {
  31005. depth = depth.depth( depthLayer );
  31006. }
  31007. depth = depth.x;
  31008. mean.addAssign( depth );
  31009. squaredMean.addAssign( depth.mul( depth ) );
  31010. } );
  31011. mean.divAssign( samples );
  31012. squaredMean.divAssign( samples );
  31013. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31014. return vec2( mean, std_dev );
  31015. } );
  31016. /**
  31017. * Represents the shader code for the second VSM render pass.
  31018. *
  31019. * @private
  31020. * @method
  31021. * @param {Object} inputs - The input parameter object.
  31022. * @param {Node<float>} inputs.samples - The number of samples
  31023. * @param {Node<float>} inputs.radius - The radius.
  31024. * @param {Node<float>} inputs.size - The size.
  31025. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  31026. * @return {Node<vec2>} The VSM output.
  31027. */
  31028. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31029. const mean = float( 0 ).toVar( 'meanHorizontal' );
  31030. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  31031. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31032. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31033. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31034. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31035. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  31036. if ( shadowPass.value.isArrayTexture ) {
  31037. distribution = distribution.depth( depthLayer );
  31038. }
  31039. mean.addAssign( distribution.x );
  31040. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  31041. } );
  31042. mean.divAssign( samples );
  31043. squaredMean.divAssign( samples );
  31044. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31045. return vec2( mean, std_dev );
  31046. } );
  31047. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  31048. //
  31049. let _rendererState;
  31050. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  31051. /**
  31052. * Represents the default shadow implementation for lighting nodes.
  31053. *
  31054. * @augments ShadowBaseNode
  31055. */
  31056. class ShadowNode extends ShadowBaseNode {
  31057. static get type() {
  31058. return 'ShadowNode';
  31059. }
  31060. /**
  31061. * Constructs a new shadow node.
  31062. *
  31063. * @param {Light} light - The shadow casting light.
  31064. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  31065. */
  31066. constructor( light, shadow = null ) {
  31067. super( light );
  31068. /**
  31069. * The light shadow which defines the properties light's
  31070. * shadow.
  31071. *
  31072. * @type {?LightShadow}
  31073. * @default null
  31074. */
  31075. this.shadow = shadow || light.shadow;
  31076. /**
  31077. * A reference to the shadow map which is a render target.
  31078. *
  31079. * @type {?RenderTarget}
  31080. * @default null
  31081. */
  31082. this.shadowMap = null;
  31083. /**
  31084. * Only relevant for VSM shadows. Render target for the
  31085. * first VSM render pass.
  31086. *
  31087. * @type {?RenderTarget}
  31088. * @default null
  31089. */
  31090. this.vsmShadowMapVertical = null;
  31091. /**
  31092. * Only relevant for VSM shadows. Render target for the
  31093. * second VSM render pass.
  31094. *
  31095. * @type {?RenderTarget}
  31096. * @default null
  31097. */
  31098. this.vsmShadowMapHorizontal = null;
  31099. /**
  31100. * Only relevant for VSM shadows. Node material which
  31101. * is used to render the first VSM pass.
  31102. *
  31103. * @type {?NodeMaterial}
  31104. * @default null
  31105. */
  31106. this.vsmMaterialVertical = null;
  31107. /**
  31108. * Only relevant for VSM shadows. Node material which
  31109. * is used to render the second VSM pass.
  31110. *
  31111. * @type {?NodeMaterial}
  31112. * @default null
  31113. */
  31114. this.vsmMaterialHorizontal = null;
  31115. /**
  31116. * A reference to the output node which defines the
  31117. * final result of this shadow node.
  31118. *
  31119. * @type {?Node}
  31120. * @private
  31121. * @default null
  31122. */
  31123. this._node = null;
  31124. /**
  31125. * The current shadow map type of this shadow node.
  31126. *
  31127. * @type {?number}
  31128. * @private
  31129. * @default null
  31130. */
  31131. this._currentShadowType = null;
  31132. /**
  31133. * A Weak Map holding the current frame ID per camera. Used
  31134. * to control the update of shadow maps.
  31135. *
  31136. * @type {WeakMap<Camera,number>}
  31137. * @private
  31138. */
  31139. this._cameraFrameId = new WeakMap();
  31140. /**
  31141. * This flag can be used for type testing.
  31142. *
  31143. * @type {boolean}
  31144. * @readonly
  31145. * @default true
  31146. */
  31147. this.isShadowNode = true;
  31148. /**
  31149. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  31150. *
  31151. * @type {number}
  31152. * @readonly
  31153. * @default true
  31154. */
  31155. this.depthLayer = 0;
  31156. }
  31157. /**
  31158. * Setups the shadow filtering.
  31159. *
  31160. * @param {NodeBuilder} builder - A reference to the current node builder.
  31161. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31162. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31163. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31164. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31165. * @param {LightShadow} inputs.shadow - The light shadow.
  31166. * @return {Node<float>} The result node of the shadow filtering.
  31167. */
  31168. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  31169. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  31170. .and( shadowCoord.x.lessThanEqual( 1 ) )
  31171. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  31172. .and( shadowCoord.y.lessThanEqual( 1 ) )
  31173. .and( shadowCoord.z.lessThanEqual( 1 ) );
  31174. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  31175. return frustumTest.select( shadowNode, float( 1 ) );
  31176. }
  31177. /**
  31178. * Setups the shadow coordinates.
  31179. *
  31180. * @param {NodeBuilder} builder - A reference to the current node builder.
  31181. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31182. * @return {Node<vec3>} The shadow coordinates.
  31183. */
  31184. setupShadowCoord( builder, shadowPosition ) {
  31185. const { shadow } = this;
  31186. const { renderer } = builder;
  31187. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31188. let shadowCoord = shadowPosition;
  31189. let coordZ;
  31190. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  31191. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  31192. coordZ = shadowCoord.z;
  31193. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  31194. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  31195. }
  31196. } else {
  31197. const w = shadowCoord.w;
  31198. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  31199. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  31200. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  31201. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  31202. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  31203. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  31204. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  31205. }
  31206. shadowCoord = vec3(
  31207. shadowCoord.x,
  31208. shadowCoord.y.oneMinus(), // follow webgpu standards
  31209. coordZ.add( bias )
  31210. );
  31211. return shadowCoord;
  31212. }
  31213. /**
  31214. * Returns the shadow filtering function for the given shadow type.
  31215. *
  31216. * @param {number} type - The shadow type.
  31217. * @return {Function} The filtering function.
  31218. */
  31219. getShadowFilterFn( type ) {
  31220. return _shadowFilterLib[ type ];
  31221. }
  31222. setupRenderTarget( shadow, builder ) {
  31223. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  31224. depthTexture.name = 'ShadowDepthTexture';
  31225. depthTexture.compareFunction = LessCompare;
  31226. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  31227. shadowMap.texture.name = 'ShadowMap';
  31228. shadowMap.texture.type = shadow.mapType;
  31229. shadowMap.depthTexture = depthTexture;
  31230. return { shadowMap, depthTexture };
  31231. }
  31232. /**
  31233. * Setups the shadow output node.
  31234. *
  31235. * @param {NodeBuilder} builder - A reference to the current node builder.
  31236. * @return {Node<vec3>} The shadow output node.
  31237. */
  31238. setupShadow( builder ) {
  31239. const { renderer, camera } = builder;
  31240. const { light, shadow } = this;
  31241. const shadowMapType = renderer.shadowMap.type;
  31242. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  31243. shadow.camera.coordinateSystem = camera.coordinateSystem;
  31244. shadow.camera.updateProjectionMatrix();
  31245. // VSM
  31246. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31247. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  31248. if ( shadowMap.depth > 1 ) {
  31249. if ( ! shadowMap._vsmShadowMapVertical ) {
  31250. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31251. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  31252. }
  31253. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  31254. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  31255. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31256. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  31257. }
  31258. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  31259. } else {
  31260. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31261. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31262. }
  31263. let shadowPassVertical = texture( depthTexture );
  31264. if ( depthTexture.isArrayTexture ) {
  31265. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  31266. }
  31267. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  31268. if ( depthTexture.isArrayTexture ) {
  31269. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  31270. }
  31271. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  31272. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31273. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31274. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  31275. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31276. material.name = 'VSMVertical';
  31277. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  31278. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31279. material.name = 'VSMHorizontal';
  31280. }
  31281. //
  31282. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  31283. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  31284. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  31285. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  31286. //
  31287. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  31288. if ( filterFn === null ) {
  31289. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  31290. }
  31291. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  31292. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  31293. let shadowColor = texture( shadowMap.texture, shadowCoord );
  31294. if ( depthTexture.isArrayTexture ) {
  31295. shadowColor = shadowColor.depth( this.depthLayer );
  31296. }
  31297. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  31298. this.shadowMap = shadowMap;
  31299. this.shadow.map = shadowMap;
  31300. // Shadow Output + Inspector
  31301. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  31302. return shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  31303. return texture( this.shadowMap.texture );
  31304. } ).toInspector( `${ inspectName } / Depth`, () => {
  31305. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).x.oneMinus();
  31306. } );
  31307. }
  31308. /**
  31309. * The implementation performs the setup of the output node. An output is only
  31310. * produces if shadow mapping is globally enabled in the renderer.
  31311. *
  31312. * @param {NodeBuilder} builder - A reference to the current node builder.
  31313. * @return {ShaderCallNodeInternal} The output node.
  31314. */
  31315. setup( builder ) {
  31316. if ( builder.renderer.shadowMap.enabled === false ) return;
  31317. return Fn( () => {
  31318. const currentShadowType = builder.renderer.shadowMap.type;
  31319. if ( this._currentShadowType !== currentShadowType ) {
  31320. this._reset();
  31321. this._node = null;
  31322. }
  31323. let node = this._node;
  31324. this.setupShadowPosition( builder );
  31325. if ( node === null ) {
  31326. this._node = node = this.setupShadow( builder );
  31327. this._currentShadowType = currentShadowType;
  31328. }
  31329. if ( builder.material.shadowNode ) { // @deprecated, r171
  31330. warn( 'NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  31331. }
  31332. if ( builder.material.receivedShadowNode ) {
  31333. node = builder.material.receivedShadowNode( node );
  31334. }
  31335. return node;
  31336. } )();
  31337. }
  31338. /**
  31339. * Renders the shadow. The logic of this function could be included
  31340. * into {@link ShadowNode#updateShadow} however more specialized shadow
  31341. * nodes might require a custom shadow map rendering. By having a
  31342. * dedicated method, it's easier to overwrite the default behavior.
  31343. *
  31344. * @param {NodeFrame} frame - A reference to the current node frame.
  31345. */
  31346. renderShadow( frame ) {
  31347. const { shadow, shadowMap, light } = this;
  31348. const { renderer, scene } = frame;
  31349. shadow.updateMatrices( light );
  31350. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  31351. const currentSceneName = scene.name;
  31352. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  31353. renderer.render( scene, shadow.camera );
  31354. scene.name = currentSceneName;
  31355. }
  31356. /**
  31357. * Updates the shadow.
  31358. *
  31359. * @param {NodeFrame} frame - A reference to the current node frame.
  31360. */
  31361. updateShadow( frame ) {
  31362. const { shadowMap, light, shadow } = this;
  31363. const { renderer, scene, camera } = frame;
  31364. const shadowType = renderer.shadowMap.type;
  31365. const depthVersion = shadowMap.depthTexture.version;
  31366. this._depthVersionCached = depthVersion;
  31367. const _shadowCameraLayer = shadow.camera.layers.mask;
  31368. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  31369. shadow.camera.layers.mask = camera.layers.mask;
  31370. }
  31371. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  31372. const currentMRT = renderer.getMRT();
  31373. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  31374. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  31375. scene.overrideMaterial = getShadowMaterial( light );
  31376. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  31377. renderer.setClearColor( 0x000000, 0 );
  31378. renderer.setRenderTarget( shadowMap );
  31379. this.renderShadow( frame );
  31380. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  31381. // vsm blur pass
  31382. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31383. this.vsmPass( renderer );
  31384. }
  31385. shadow.camera.layers.mask = _shadowCameraLayer;
  31386. restoreRendererAndSceneState( renderer, scene, _rendererState );
  31387. }
  31388. /**
  31389. * For VSM additional render passes are required.
  31390. *
  31391. * @param {Renderer} renderer - A reference to the current renderer.
  31392. */
  31393. vsmPass( renderer ) {
  31394. const { shadow } = this;
  31395. const depth = this.shadowMap.depth;
  31396. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31397. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31398. renderer.setRenderTarget( this.vsmShadowMapVertical );
  31399. _quadMesh.material = this.vsmMaterialVertical;
  31400. _quadMesh.render( renderer );
  31401. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  31402. _quadMesh.material = this.vsmMaterialHorizontal;
  31403. _quadMesh.render( renderer );
  31404. }
  31405. /**
  31406. * Frees the internal resources of this shadow node.
  31407. */
  31408. dispose() {
  31409. this._reset();
  31410. super.dispose();
  31411. }
  31412. /**
  31413. * Resets the resouce state of this shadow node.
  31414. *
  31415. * @private
  31416. */
  31417. _reset() {
  31418. this._currentShadowType = null;
  31419. if ( this.shadowMap ) {
  31420. this.shadowMap.dispose();
  31421. this.shadowMap = null;
  31422. }
  31423. if ( this.vsmShadowMapVertical !== null ) {
  31424. this.vsmShadowMapVertical.dispose();
  31425. this.vsmShadowMapVertical = null;
  31426. this.vsmMaterialVertical.dispose();
  31427. this.vsmMaterialVertical = null;
  31428. }
  31429. if ( this.vsmShadowMapHorizontal !== null ) {
  31430. this.vsmShadowMapHorizontal.dispose();
  31431. this.vsmShadowMapHorizontal = null;
  31432. this.vsmMaterialHorizontal.dispose();
  31433. this.vsmMaterialHorizontal = null;
  31434. }
  31435. }
  31436. /**
  31437. * The implementation performs the update of the shadow map if necessary.
  31438. *
  31439. * @param {NodeFrame} frame - A reference to the current node frame.
  31440. */
  31441. updateBefore( frame ) {
  31442. const { shadow } = this;
  31443. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  31444. if ( needsUpdate ) {
  31445. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  31446. needsUpdate = false;
  31447. }
  31448. this._cameraFrameId[ frame.camera ] = frame.frameId;
  31449. }
  31450. if ( needsUpdate ) {
  31451. this.updateShadow( frame );
  31452. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  31453. shadow.needsUpdate = false;
  31454. }
  31455. }
  31456. }
  31457. }
  31458. /**
  31459. * Shadow Render Object Function.
  31460. *
  31461. * @function shadowRenderObjectFunction
  31462. * @param {Object3D} object - The 3D object to render.
  31463. * @param {Scene} scene - The scene containing the object.
  31464. * @param {Camera} _camera - The camera used for rendering.
  31465. * @param {BufferGeometry} geometry - The geometry of the object.
  31466. * @param {Material} material - The material of the object.
  31467. * @param {Group} group - The group the object belongs to.
  31468. * @param {...any} params - Additional parameters for rendering.
  31469. */
  31470. /**
  31471. * TSL function for creating an instance of `ShadowNode`.
  31472. *
  31473. * @tsl
  31474. * @function
  31475. * @param {Light} light - The shadow casting light.
  31476. * @param {?LightShadow} [shadow] - The light shadow.
  31477. * @return {ShadowNode} The created shadow node.
  31478. */
  31479. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  31480. const _clearColor$1 = /*@__PURE__*/ new Color();
  31481. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  31482. // vector suitable for 2D texture mapping. This code uses the following layout for the
  31483. // 2D texture:
  31484. //
  31485. // xzXZ
  31486. // y Y
  31487. //
  31488. // Y - Positive y direction
  31489. // y - Negative y direction
  31490. // X - Positive x direction
  31491. // x - Negative x direction
  31492. // Z - Positive z direction
  31493. // z - Negative z direction
  31494. //
  31495. // Source and test bed:
  31496. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  31497. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  31498. const v = pos.toVar();
  31499. // Number of texels to avoid at the edge of each square
  31500. const absV = abs( v );
  31501. // Intersect unit cube
  31502. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  31503. absV.mulAssign( scaleToCube );
  31504. // Apply scale to avoid seams
  31505. // two texels less per square (one texel will do for NEAREST)
  31506. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  31507. // Unwrap
  31508. // space: -1 ... 1 range for each square
  31509. //
  31510. // #X## dim := ( 4 , 2 )
  31511. // # # center := ( 1 , 1 )
  31512. const planar = vec2( v.xy ).toVar();
  31513. const almostATexel = texelSizeY.mul( 1.5 );
  31514. const almostOne = almostATexel.oneMinus();
  31515. If( absV.z.greaterThanEqual( almostOne ), () => {
  31516. If( v.z.greaterThan( 0.0 ), () => {
  31517. planar.x.assign( sub( 4.0, v.x ) );
  31518. } );
  31519. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  31520. const signX = sign( v.x );
  31521. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  31522. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  31523. const signY = sign( v.y );
  31524. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  31525. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  31526. } );
  31527. // Transform to UV space
  31528. // scale := 0.5 / dim
  31529. // translate := ( center + 0.5 ) / dim
  31530. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  31531. } ).setLayout( {
  31532. name: 'cubeToUV',
  31533. type: 'vec2',
  31534. inputs: [
  31535. { name: 'pos', type: 'vec3' },
  31536. { name: 'texelSizeY', type: 'float' }
  31537. ]
  31538. } );
  31539. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  31540. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  31541. } );
  31542. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  31543. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31544. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  31545. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  31546. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  31547. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  31548. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  31549. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  31550. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  31551. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  31552. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  31553. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  31554. .mul( 1.0 / 9.0 );
  31555. } );
  31556. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  31557. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  31558. // the vector from the light to the world-space position of the fragment.
  31559. const lightToPosition = shadowCoord.xyz.toVar();
  31560. const lightToPositionLength = lightToPosition.length();
  31561. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  31562. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  31563. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31564. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  31565. const result = float( 1.0 ).toVar();
  31566. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  31567. // dp = normalized distance from light to fragment position
  31568. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  31569. dp.addAssign( bias );
  31570. // bd3D = base direction 3D
  31571. const bd3D = lightToPosition.normalize();
  31572. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  31573. // percentage-closer filtering
  31574. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  31575. } );
  31576. return result;
  31577. } );
  31578. const _viewport = /*@__PURE__*/ new Vector4();
  31579. const _viewportSize = /*@__PURE__*/ new Vector2();
  31580. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  31581. /**
  31582. * Represents the shadow implementation for point light nodes.
  31583. *
  31584. * @augments ShadowNode
  31585. */
  31586. class PointShadowNode extends ShadowNode {
  31587. static get type() {
  31588. return 'PointShadowNode';
  31589. }
  31590. /**
  31591. * Constructs a new point shadow node.
  31592. *
  31593. * @param {PointLight} light - The shadow casting point light.
  31594. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31595. */
  31596. constructor( light, shadow = null ) {
  31597. super( light, shadow );
  31598. }
  31599. /**
  31600. * Overwrites the default implementation to return point light shadow specific
  31601. * filtering functions.
  31602. *
  31603. * @param {number} type - The shadow type.
  31604. * @return {Function} The filtering function.
  31605. */
  31606. getShadowFilterFn( type ) {
  31607. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  31608. }
  31609. /**
  31610. * Overwrites the default implementation so the unaltered shadow position is used.
  31611. *
  31612. * @param {NodeBuilder} builder - A reference to the current node builder.
  31613. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31614. * @return {Node<vec3>} The shadow coordinates.
  31615. */
  31616. setupShadowCoord( builder, shadowPosition ) {
  31617. return shadowPosition;
  31618. }
  31619. /**
  31620. * Overwrites the default implementation to only use point light specific
  31621. * shadow filter functions.
  31622. *
  31623. * @param {NodeBuilder} builder - A reference to the current node builder.
  31624. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31625. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31626. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  31627. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31628. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31629. * @param {LightShadow} inputs.shadow - The light shadow.
  31630. * @return {Node<float>} The result node of the shadow filtering.
  31631. */
  31632. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  31633. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  31634. }
  31635. /**
  31636. * Overwrites the default implementation with point light specific
  31637. * rendering code.
  31638. *
  31639. * @param {NodeFrame} frame - A reference to the current node frame.
  31640. */
  31641. renderShadow( frame ) {
  31642. const { shadow, shadowMap, light } = this;
  31643. const { renderer, scene } = frame;
  31644. const shadowFrameExtents = shadow.getFrameExtents();
  31645. _shadowMapSize.copy( shadow.mapSize );
  31646. _shadowMapSize.multiply( shadowFrameExtents );
  31647. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  31648. _viewportSize.copy( shadow.mapSize );
  31649. //
  31650. const previousAutoClear = renderer.autoClear;
  31651. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  31652. const previousClearAlpha = renderer.getClearAlpha();
  31653. renderer.autoClear = false;
  31654. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  31655. renderer.clear();
  31656. const viewportCount = shadow.getViewportCount();
  31657. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  31658. const viewport = shadow.getViewport( vp );
  31659. const x = _viewportSize.x * viewport.x;
  31660. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  31661. _viewport.set(
  31662. x,
  31663. y,
  31664. _viewportSize.x * viewport.z,
  31665. _viewportSize.y * viewport.w
  31666. );
  31667. shadowMap.viewport.copy( _viewport );
  31668. shadow.updateMatrices( light, vp );
  31669. const currentSceneName = scene.name;
  31670. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ vp + 1 }`;
  31671. renderer.render( scene, shadow.camera );
  31672. scene.name = currentSceneName;
  31673. }
  31674. //
  31675. renderer.autoClear = previousAutoClear;
  31676. renderer.setClearColor( previousClearColor, previousClearAlpha );
  31677. }
  31678. }
  31679. /**
  31680. * TSL function for creating an instance of `PointShadowNode`.
  31681. *
  31682. * @tsl
  31683. * @function
  31684. * @param {PointLight} light - The shadow casting point light.
  31685. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31686. * @return {PointShadowNode} The created point shadow node.
  31687. */
  31688. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  31689. /**
  31690. * Base class for analytic light nodes.
  31691. *
  31692. * @augments LightingNode
  31693. */
  31694. class AnalyticLightNode extends LightingNode {
  31695. static get type() {
  31696. return 'AnalyticLightNode';
  31697. }
  31698. /**
  31699. * Constructs a new analytic light node.
  31700. *
  31701. * @param {?Light} [light=null] - The light source.
  31702. */
  31703. constructor( light = null ) {
  31704. super();
  31705. /**
  31706. * The light source.
  31707. *
  31708. * @type {?Light}
  31709. * @default null
  31710. */
  31711. this.light = light;
  31712. /**
  31713. * The light's color value.
  31714. *
  31715. * @type {Color}
  31716. */
  31717. this.color = new Color();
  31718. /**
  31719. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  31720. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  31721. *
  31722. * @type {Node}
  31723. */
  31724. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  31725. /**
  31726. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  31727. * The final color node is represented by a different node when using shadows.
  31728. *
  31729. * @type {?Node}
  31730. * @default null
  31731. */
  31732. this.baseColorNode = null;
  31733. /**
  31734. * Represents the light's shadow.
  31735. *
  31736. * @type {?ShadowNode}
  31737. * @default null
  31738. */
  31739. this.shadowNode = null;
  31740. /**
  31741. * Represents the light's shadow color.
  31742. *
  31743. * @type {?Node}
  31744. * @default null
  31745. */
  31746. this.shadowColorNode = null;
  31747. /**
  31748. * This flag can be used for type testing.
  31749. *
  31750. * @type {boolean}
  31751. * @readonly
  31752. * @default true
  31753. */
  31754. this.isAnalyticLightNode = true;
  31755. /**
  31756. * Overwritten since analytic light nodes are updated
  31757. * once per frame.
  31758. *
  31759. * @type {string}
  31760. * @default 'frame'
  31761. */
  31762. this.updateType = NodeUpdateType.FRAME;
  31763. }
  31764. getHash() {
  31765. return this.light.uuid;
  31766. }
  31767. /**
  31768. * Returns a node representing a direction vector which points from the current
  31769. * position in view space to the light's position in view space.
  31770. *
  31771. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31772. * @return {Node<vec3>} The light vector node.
  31773. */
  31774. getLightVector( builder ) {
  31775. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  31776. }
  31777. /**
  31778. * Sets up the direct lighting for the analytic light node.
  31779. *
  31780. * @abstract
  31781. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31782. * @return {Object|undefined} The direct light data (color and direction).
  31783. */
  31784. setupDirect( /*builder*/ ) { }
  31785. /**
  31786. * Sets up the direct rect area lighting for the analytic light node.
  31787. *
  31788. * @abstract
  31789. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31790. * @return {Object|undefined} The direct rect area light data.
  31791. */
  31792. setupDirectRectArea( /*builder*/ ) { }
  31793. /**
  31794. * Setups the shadow node for this light. The method exists so concrete light classes
  31795. * can setup different types of shadow nodes.
  31796. *
  31797. * @return {ShadowNode} The created shadow node.
  31798. */
  31799. setupShadowNode() {
  31800. return shadow( this.light );
  31801. }
  31802. /**
  31803. * Setups the shadow for this light. This method is only executed if the light
  31804. * cast shadows and the current build object receives shadows. It incorporates
  31805. * shadows into the lighting computation.
  31806. *
  31807. * @param {NodeBuilder} builder - The current node builder.
  31808. */
  31809. setupShadow( builder ) {
  31810. const { renderer } = builder;
  31811. if ( renderer.shadowMap.enabled === false ) return;
  31812. let shadowColorNode = this.shadowColorNode;
  31813. if ( shadowColorNode === null ) {
  31814. const customShadowNode = this.light.shadow.shadowNode;
  31815. let shadowNode;
  31816. if ( customShadowNode !== undefined ) {
  31817. shadowNode = nodeObject( customShadowNode );
  31818. } else {
  31819. shadowNode = this.setupShadowNode();
  31820. }
  31821. this.shadowNode = shadowNode;
  31822. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  31823. this.baseColorNode = this.colorNode;
  31824. }
  31825. //
  31826. if ( builder.context.getShadow ) {
  31827. const shadow = builder.context.getShadow( this.light, builder );
  31828. if ( shadow ) {
  31829. shadowColorNode = shadowColorNode.mul( shadow );
  31830. }
  31831. }
  31832. this.colorNode = shadowColorNode;
  31833. }
  31834. /**
  31835. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  31836. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  31837. * invocate the respective interface methods.
  31838. *
  31839. * @param {NodeBuilder} builder - The current node builder.
  31840. */
  31841. setup( builder ) {
  31842. this.colorNode = this.baseColorNode || this.colorNode;
  31843. if ( this.light.castShadow ) {
  31844. if ( builder.object.receiveShadow ) {
  31845. this.setupShadow( builder );
  31846. }
  31847. } else if ( this.shadowNode !== null ) {
  31848. this.shadowNode.dispose();
  31849. this.shadowNode = null;
  31850. this.shadowColorNode = null;
  31851. }
  31852. const directLightData = this.setupDirect( builder );
  31853. const directRectAreaLightData = this.setupDirectRectArea( builder );
  31854. if ( directLightData ) {
  31855. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  31856. }
  31857. if ( directRectAreaLightData ) {
  31858. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  31859. }
  31860. }
  31861. /**
  31862. * The update method is used to update light uniforms per frame.
  31863. * Potentially overwritten in concrete light nodes to update light
  31864. * specific uniforms.
  31865. *
  31866. * @param {NodeFrame} frame - A reference to the current node frame.
  31867. */
  31868. update( /*frame*/ ) {
  31869. const { light } = this;
  31870. this.color.copy( light.color ).multiplyScalar( light.intensity );
  31871. }
  31872. }
  31873. /**
  31874. * Represents a `discard` shader operation in TSL.
  31875. *
  31876. * @method
  31877. * @param {Object} inputs - The input parameter object.
  31878. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  31879. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  31880. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  31881. * @return {Node<float>} The distance falloff.
  31882. */
  31883. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  31884. // based upon Frostbite 3 Moving to Physically-based Rendering
  31885. // page 32, equation 26: E[window1]
  31886. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  31887. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  31888. return cutoffDistance.greaterThan( 0 ).select(
  31889. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  31890. distanceFalloff
  31891. );
  31892. } ); // validated
  31893. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  31894. const lightDirection = lightVector.normalize();
  31895. const lightDistance = lightVector.length();
  31896. const attenuation = getDistanceAttenuation( {
  31897. lightDistance,
  31898. cutoffDistance,
  31899. decayExponent
  31900. } );
  31901. const lightColor = color.mul( attenuation );
  31902. return { lightDirection, lightColor };
  31903. };
  31904. /**
  31905. * Module for representing point lights as nodes.
  31906. *
  31907. * @augments AnalyticLightNode
  31908. */
  31909. class PointLightNode extends AnalyticLightNode {
  31910. static get type() {
  31911. return 'PointLightNode';
  31912. }
  31913. /**
  31914. * Constructs a new point light node.
  31915. *
  31916. * @param {?PointLight} [light=null] - The point light source.
  31917. */
  31918. constructor( light = null ) {
  31919. super( light );
  31920. /**
  31921. * Uniform node representing the cutoff distance.
  31922. *
  31923. * @type {UniformNode<float>}
  31924. */
  31925. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  31926. /**
  31927. * Uniform node representing the decay exponent.
  31928. *
  31929. * @type {UniformNode<float>}
  31930. */
  31931. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  31932. }
  31933. /**
  31934. * Overwritten to updated point light specific uniforms.
  31935. *
  31936. * @param {NodeFrame} frame - A reference to the current node frame.
  31937. */
  31938. update( frame ) {
  31939. const { light } = this;
  31940. super.update( frame );
  31941. this.cutoffDistanceNode.value = light.distance;
  31942. this.decayExponentNode.value = light.decay;
  31943. }
  31944. /**
  31945. * Overwritten to setup point light specific shadow.
  31946. *
  31947. * @return {PointShadowNode}
  31948. */
  31949. setupShadowNode() {
  31950. return pointShadow( this.light );
  31951. }
  31952. setupDirect( builder ) {
  31953. return directPointLight( {
  31954. color: this.colorNode,
  31955. lightVector: this.getLightVector( builder ),
  31956. cutoffDistance: this.cutoffDistanceNode,
  31957. decayExponent: this.decayExponentNode
  31958. } );
  31959. }
  31960. }
  31961. /**
  31962. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  31963. *
  31964. * @tsl
  31965. * @function
  31966. * @param {Node<vec2>} coord - The uv coordinates.
  31967. * @return {Node<float>} The result data.
  31968. */
  31969. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  31970. const uv = coord.mul( 2.0 );
  31971. const cx = uv.x.floor();
  31972. const cy = uv.y.floor();
  31973. const result = cx.add( cy ).mod( 2.0 );
  31974. return result.sign();
  31975. } );
  31976. /**
  31977. * Generates a circle based on the uv coordinates.
  31978. *
  31979. * @tsl
  31980. * @function
  31981. * @param {Node<vec2>} coord - The uv to generate the circle.
  31982. * @return {Node<float>} The circle shape.
  31983. */
  31984. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  31985. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  31986. let alpha;
  31987. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  31988. const dlen = float( len2.fwidth() ).toVar();
  31989. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  31990. } else {
  31991. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  31992. }
  31993. return alpha;
  31994. } );
  31995. // Three.js Transpiler
  31996. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  31997. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  31998. const f = float( f_immutable ).toVar();
  31999. const t = float( t_immutable ).toVar();
  32000. const b = bool( b_immutable ).toVar();
  32001. return select( b, t, f );
  32002. } ).setLayout( {
  32003. name: 'mx_select',
  32004. type: 'float',
  32005. inputs: [
  32006. { name: 'b', type: 'bool' },
  32007. { name: 't', type: 'float' },
  32008. { name: 'f', type: 'float' }
  32009. ]
  32010. } );
  32011. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  32012. const b = bool( b_immutable ).toVar();
  32013. const val = float( val_immutable ).toVar();
  32014. return select( b, val.negate(), val );
  32015. } ).setLayout( {
  32016. name: 'mx_negate_if',
  32017. type: 'float',
  32018. inputs: [
  32019. { name: 'val', type: 'float' },
  32020. { name: 'b', type: 'bool' }
  32021. ]
  32022. } );
  32023. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32024. const x = float( x_immutable ).toVar();
  32025. return int( floor( x ) );
  32026. } ).setLayout( {
  32027. name: 'mx_floor',
  32028. type: 'int',
  32029. inputs: [
  32030. { name: 'x', type: 'float' }
  32031. ]
  32032. } );
  32033. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  32034. const x = float( x_immutable ).toVar();
  32035. i.assign( mx_floor( x ) );
  32036. return x.sub( float( i ) );
  32037. } );
  32038. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32039. const t = float( t_immutable ).toVar();
  32040. const s = float( s_immutable ).toVar();
  32041. const v3 = float( v3_immutable ).toVar();
  32042. const v2 = float( v2_immutable ).toVar();
  32043. const v1 = float( v1_immutable ).toVar();
  32044. const v0 = float( v0_immutable ).toVar();
  32045. const s1 = float( sub( 1.0, s ) ).toVar();
  32046. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32047. } ).setLayout( {
  32048. name: 'mx_bilerp_0',
  32049. type: 'float',
  32050. inputs: [
  32051. { name: 'v0', type: 'float' },
  32052. { name: 'v1', type: 'float' },
  32053. { name: 'v2', type: 'float' },
  32054. { name: 'v3', type: 'float' },
  32055. { name: 's', type: 'float' },
  32056. { name: 't', type: 'float' }
  32057. ]
  32058. } );
  32059. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32060. const t = float( t_immutable ).toVar();
  32061. const s = float( s_immutable ).toVar();
  32062. const v3 = vec3( v3_immutable ).toVar();
  32063. const v2 = vec3( v2_immutable ).toVar();
  32064. const v1 = vec3( v1_immutable ).toVar();
  32065. const v0 = vec3( v0_immutable ).toVar();
  32066. const s1 = float( sub( 1.0, s ) ).toVar();
  32067. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32068. } ).setLayout( {
  32069. name: 'mx_bilerp_1',
  32070. type: 'vec3',
  32071. inputs: [
  32072. { name: 'v0', type: 'vec3' },
  32073. { name: 'v1', type: 'vec3' },
  32074. { name: 'v2', type: 'vec3' },
  32075. { name: 'v3', type: 'vec3' },
  32076. { name: 's', type: 'float' },
  32077. { name: 't', type: 'float' }
  32078. ]
  32079. } );
  32080. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  32081. 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 ] ) => {
  32082. const r = float( r_immutable ).toVar();
  32083. const t = float( t_immutable ).toVar();
  32084. const s = float( s_immutable ).toVar();
  32085. const v7 = float( v7_immutable ).toVar();
  32086. const v6 = float( v6_immutable ).toVar();
  32087. const v5 = float( v5_immutable ).toVar();
  32088. const v4 = float( v4_immutable ).toVar();
  32089. const v3 = float( v3_immutable ).toVar();
  32090. const v2 = float( v2_immutable ).toVar();
  32091. const v1 = float( v1_immutable ).toVar();
  32092. const v0 = float( v0_immutable ).toVar();
  32093. const s1 = float( sub( 1.0, s ) ).toVar();
  32094. const t1 = float( sub( 1.0, t ) ).toVar();
  32095. const r1 = float( sub( 1.0, r ) ).toVar();
  32096. 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 ) ) ) ) ) );
  32097. } ).setLayout( {
  32098. name: 'mx_trilerp_0',
  32099. type: 'float',
  32100. inputs: [
  32101. { name: 'v0', type: 'float' },
  32102. { name: 'v1', type: 'float' },
  32103. { name: 'v2', type: 'float' },
  32104. { name: 'v3', type: 'float' },
  32105. { name: 'v4', type: 'float' },
  32106. { name: 'v5', type: 'float' },
  32107. { name: 'v6', type: 'float' },
  32108. { name: 'v7', type: 'float' },
  32109. { name: 's', type: 'float' },
  32110. { name: 't', type: 'float' },
  32111. { name: 'r', type: 'float' }
  32112. ]
  32113. } );
  32114. 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 ] ) => {
  32115. const r = float( r_immutable ).toVar();
  32116. const t = float( t_immutable ).toVar();
  32117. const s = float( s_immutable ).toVar();
  32118. const v7 = vec3( v7_immutable ).toVar();
  32119. const v6 = vec3( v6_immutable ).toVar();
  32120. const v5 = vec3( v5_immutable ).toVar();
  32121. const v4 = vec3( v4_immutable ).toVar();
  32122. const v3 = vec3( v3_immutable ).toVar();
  32123. const v2 = vec3( v2_immutable ).toVar();
  32124. const v1 = vec3( v1_immutable ).toVar();
  32125. const v0 = vec3( v0_immutable ).toVar();
  32126. const s1 = float( sub( 1.0, s ) ).toVar();
  32127. const t1 = float( sub( 1.0, t ) ).toVar();
  32128. const r1 = float( sub( 1.0, r ) ).toVar();
  32129. 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 ) ) ) ) ) );
  32130. } ).setLayout( {
  32131. name: 'mx_trilerp_1',
  32132. type: 'vec3',
  32133. inputs: [
  32134. { name: 'v0', type: 'vec3' },
  32135. { name: 'v1', type: 'vec3' },
  32136. { name: 'v2', type: 'vec3' },
  32137. { name: 'v3', type: 'vec3' },
  32138. { name: 'v4', type: 'vec3' },
  32139. { name: 'v5', type: 'vec3' },
  32140. { name: 'v6', type: 'vec3' },
  32141. { name: 'v7', type: 'vec3' },
  32142. { name: 's', type: 'float' },
  32143. { name: 't', type: 'float' },
  32144. { name: 'r', type: 'float' }
  32145. ]
  32146. } );
  32147. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  32148. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32149. const y = float( y_immutable ).toVar();
  32150. const x = float( x_immutable ).toVar();
  32151. const hash = uint( hash_immutable ).toVar();
  32152. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  32153. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  32154. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  32155. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32156. } ).setLayout( {
  32157. name: 'mx_gradient_float_0',
  32158. type: 'float',
  32159. inputs: [
  32160. { name: 'hash', type: 'uint' },
  32161. { name: 'x', type: 'float' },
  32162. { name: 'y', type: 'float' }
  32163. ]
  32164. } );
  32165. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32166. const z = float( z_immutable ).toVar();
  32167. const y = float( y_immutable ).toVar();
  32168. const x = float( x_immutable ).toVar();
  32169. const hash = uint( hash_immutable ).toVar();
  32170. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  32171. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  32172. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  32173. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32174. } ).setLayout( {
  32175. name: 'mx_gradient_float_1',
  32176. type: 'float',
  32177. inputs: [
  32178. { name: 'hash', type: 'uint' },
  32179. { name: 'x', type: 'float' },
  32180. { name: 'y', type: 'float' },
  32181. { name: 'z', type: 'float' }
  32182. ]
  32183. } );
  32184. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  32185. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32186. const y = float( y_immutable ).toVar();
  32187. const x = float( x_immutable ).toVar();
  32188. const hash = uvec3( hash_immutable ).toVar();
  32189. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  32190. } ).setLayout( {
  32191. name: 'mx_gradient_vec3_0',
  32192. type: 'vec3',
  32193. inputs: [
  32194. { name: 'hash', type: 'uvec3' },
  32195. { name: 'x', type: 'float' },
  32196. { name: 'y', type: 'float' }
  32197. ]
  32198. } );
  32199. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32200. const z = float( z_immutable ).toVar();
  32201. const y = float( y_immutable ).toVar();
  32202. const x = float( x_immutable ).toVar();
  32203. const hash = uvec3( hash_immutable ).toVar();
  32204. 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 ) );
  32205. } ).setLayout( {
  32206. name: 'mx_gradient_vec3_1',
  32207. type: 'vec3',
  32208. inputs: [
  32209. { name: 'hash', type: 'uvec3' },
  32210. { name: 'x', type: 'float' },
  32211. { name: 'y', type: 'float' },
  32212. { name: 'z', type: 'float' }
  32213. ]
  32214. } );
  32215. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  32216. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32217. const v = float( v_immutable ).toVar();
  32218. return mul( 0.6616, v );
  32219. } ).setLayout( {
  32220. name: 'mx_gradient_scale2d_0',
  32221. type: 'float',
  32222. inputs: [
  32223. { name: 'v', type: 'float' }
  32224. ]
  32225. } );
  32226. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32227. const v = float( v_immutable ).toVar();
  32228. return mul( 0.9820, v );
  32229. } ).setLayout( {
  32230. name: 'mx_gradient_scale3d_0',
  32231. type: 'float',
  32232. inputs: [
  32233. { name: 'v', type: 'float' }
  32234. ]
  32235. } );
  32236. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32237. const v = vec3( v_immutable ).toVar();
  32238. return mul( 0.6616, v );
  32239. } ).setLayout( {
  32240. name: 'mx_gradient_scale2d_1',
  32241. type: 'vec3',
  32242. inputs: [
  32243. { name: 'v', type: 'vec3' }
  32244. ]
  32245. } );
  32246. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  32247. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32248. const v = vec3( v_immutable ).toVar();
  32249. return mul( 0.9820, v );
  32250. } ).setLayout( {
  32251. name: 'mx_gradient_scale3d_1',
  32252. type: 'vec3',
  32253. inputs: [
  32254. { name: 'v', type: 'vec3' }
  32255. ]
  32256. } );
  32257. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  32258. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  32259. const k = int( k_immutable ).toVar();
  32260. const x = uint( x_immutable ).toVar();
  32261. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  32262. } ).setLayout( {
  32263. name: 'mx_rotl32',
  32264. type: 'uint',
  32265. inputs: [
  32266. { name: 'x', type: 'uint' },
  32267. { name: 'k', type: 'int' }
  32268. ]
  32269. } );
  32270. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  32271. a.subAssign( c );
  32272. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  32273. c.addAssign( b );
  32274. b.subAssign( a );
  32275. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  32276. a.addAssign( c );
  32277. c.subAssign( b );
  32278. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  32279. b.addAssign( a );
  32280. a.subAssign( c );
  32281. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  32282. c.addAssign( b );
  32283. b.subAssign( a );
  32284. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  32285. a.addAssign( c );
  32286. c.subAssign( b );
  32287. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  32288. b.addAssign( a );
  32289. } );
  32290. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  32291. const c = uint( c_immutable ).toVar();
  32292. const b = uint( b_immutable ).toVar();
  32293. const a = uint( a_immutable ).toVar();
  32294. c.bitXorAssign( b );
  32295. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  32296. a.bitXorAssign( c );
  32297. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  32298. b.bitXorAssign( a );
  32299. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  32300. c.bitXorAssign( b );
  32301. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  32302. a.bitXorAssign( c );
  32303. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  32304. b.bitXorAssign( a );
  32305. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  32306. c.bitXorAssign( b );
  32307. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  32308. return c;
  32309. } ).setLayout( {
  32310. name: 'mx_bjfinal',
  32311. type: 'uint',
  32312. inputs: [
  32313. { name: 'a', type: 'uint' },
  32314. { name: 'b', type: 'uint' },
  32315. { name: 'c', type: 'uint' }
  32316. ]
  32317. } );
  32318. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  32319. const bits = uint( bits_immutable ).toVar();
  32320. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  32321. } ).setLayout( {
  32322. name: 'mx_bits_to_01',
  32323. type: 'float',
  32324. inputs: [
  32325. { name: 'bits', type: 'uint' }
  32326. ]
  32327. } );
  32328. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  32329. const t = float( t_immutable ).toVar();
  32330. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  32331. } ).setLayout( {
  32332. name: 'mx_fade',
  32333. type: 'float',
  32334. inputs: [
  32335. { name: 't', type: 'float' }
  32336. ]
  32337. } );
  32338. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32339. const x = int( x_immutable ).toVar();
  32340. const len = uint( uint( 1 ) ).toVar();
  32341. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  32342. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  32343. } ).setLayout( {
  32344. name: 'mx_hash_int_0',
  32345. type: 'uint',
  32346. inputs: [
  32347. { name: 'x', type: 'int' }
  32348. ]
  32349. } );
  32350. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32351. const y = int( y_immutable ).toVar();
  32352. const x = int( x_immutable ).toVar();
  32353. const len = uint( uint( 2 ) ).toVar();
  32354. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32355. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32356. a.addAssign( uint( x ) );
  32357. b.addAssign( uint( y ) );
  32358. return mx_bjfinal( a, b, c );
  32359. } ).setLayout( {
  32360. name: 'mx_hash_int_1',
  32361. type: 'uint',
  32362. inputs: [
  32363. { name: 'x', type: 'int' },
  32364. { name: 'y', type: 'int' }
  32365. ]
  32366. } );
  32367. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32368. const z = int( z_immutable ).toVar();
  32369. const y = int( y_immutable ).toVar();
  32370. const x = int( x_immutable ).toVar();
  32371. const len = uint( uint( 3 ) ).toVar();
  32372. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32373. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32374. a.addAssign( uint( x ) );
  32375. b.addAssign( uint( y ) );
  32376. c.addAssign( uint( z ) );
  32377. return mx_bjfinal( a, b, c );
  32378. } ).setLayout( {
  32379. name: 'mx_hash_int_2',
  32380. type: 'uint',
  32381. inputs: [
  32382. { name: 'x', type: 'int' },
  32383. { name: 'y', type: 'int' },
  32384. { name: 'z', type: 'int' }
  32385. ]
  32386. } );
  32387. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  32388. const xx = int( xx_immutable ).toVar();
  32389. const z = int( z_immutable ).toVar();
  32390. const y = int( y_immutable ).toVar();
  32391. const x = int( x_immutable ).toVar();
  32392. const len = uint( uint( 4 ) ).toVar();
  32393. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32394. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32395. a.addAssign( uint( x ) );
  32396. b.addAssign( uint( y ) );
  32397. c.addAssign( uint( z ) );
  32398. mx_bjmix( a, b, c );
  32399. a.addAssign( uint( xx ) );
  32400. return mx_bjfinal( a, b, c );
  32401. } ).setLayout( {
  32402. name: 'mx_hash_int_3',
  32403. type: 'uint',
  32404. inputs: [
  32405. { name: 'x', type: 'int' },
  32406. { name: 'y', type: 'int' },
  32407. { name: 'z', type: 'int' },
  32408. { name: 'xx', type: 'int' }
  32409. ]
  32410. } );
  32411. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  32412. const yy = int( yy_immutable ).toVar();
  32413. const xx = int( xx_immutable ).toVar();
  32414. const z = int( z_immutable ).toVar();
  32415. const y = int( y_immutable ).toVar();
  32416. const x = int( x_immutable ).toVar();
  32417. const len = uint( uint( 5 ) ).toVar();
  32418. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32419. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32420. a.addAssign( uint( x ) );
  32421. b.addAssign( uint( y ) );
  32422. c.addAssign( uint( z ) );
  32423. mx_bjmix( a, b, c );
  32424. a.addAssign( uint( xx ) );
  32425. b.addAssign( uint( yy ) );
  32426. return mx_bjfinal( a, b, c );
  32427. } ).setLayout( {
  32428. name: 'mx_hash_int_4',
  32429. type: 'uint',
  32430. inputs: [
  32431. { name: 'x', type: 'int' },
  32432. { name: 'y', type: 'int' },
  32433. { name: 'z', type: 'int' },
  32434. { name: 'xx', type: 'int' },
  32435. { name: 'yy', type: 'int' }
  32436. ]
  32437. } );
  32438. 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 ] );
  32439. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32440. const y = int( y_immutable ).toVar();
  32441. const x = int( x_immutable ).toVar();
  32442. const h = uint( mx_hash_int( x, y ) ).toVar();
  32443. const result = uvec3().toVar();
  32444. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32445. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32446. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32447. return result;
  32448. } ).setLayout( {
  32449. name: 'mx_hash_vec3_0',
  32450. type: 'uvec3',
  32451. inputs: [
  32452. { name: 'x', type: 'int' },
  32453. { name: 'y', type: 'int' }
  32454. ]
  32455. } );
  32456. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32457. const z = int( z_immutable ).toVar();
  32458. const y = int( y_immutable ).toVar();
  32459. const x = int( x_immutable ).toVar();
  32460. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  32461. const result = uvec3().toVar();
  32462. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32463. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32464. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32465. return result;
  32466. } ).setLayout( {
  32467. name: 'mx_hash_vec3_1',
  32468. type: 'uvec3',
  32469. inputs: [
  32470. { name: 'x', type: 'int' },
  32471. { name: 'y', type: 'int' },
  32472. { name: 'z', type: 'int' }
  32473. ]
  32474. } );
  32475. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  32476. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32477. const p = vec2( p_immutable ).toVar();
  32478. const X = int().toVar(), Y = int().toVar();
  32479. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32480. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32481. const u = float( mx_fade( fx ) ).toVar();
  32482. const v = float( mx_fade( fy ) ).toVar();
  32483. 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();
  32484. return mx_gradient_scale2d( result );
  32485. } ).setLayout( {
  32486. name: 'mx_perlin_noise_float_0',
  32487. type: 'float',
  32488. inputs: [
  32489. { name: 'p', type: 'vec2' }
  32490. ]
  32491. } );
  32492. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32493. const p = vec3( p_immutable ).toVar();
  32494. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32495. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32496. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32497. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32498. const u = float( mx_fade( fx ) ).toVar();
  32499. const v = float( mx_fade( fy ) ).toVar();
  32500. const w = float( mx_fade( fz ) ).toVar();
  32501. 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();
  32502. return mx_gradient_scale3d( result );
  32503. } ).setLayout( {
  32504. name: 'mx_perlin_noise_float_1',
  32505. type: 'float',
  32506. inputs: [
  32507. { name: 'p', type: 'vec3' }
  32508. ]
  32509. } );
  32510. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  32511. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32512. const p = vec2( p_immutable ).toVar();
  32513. const X = int().toVar(), Y = int().toVar();
  32514. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32515. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32516. const u = float( mx_fade( fx ) ).toVar();
  32517. const v = float( mx_fade( fy ) ).toVar();
  32518. 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();
  32519. return mx_gradient_scale2d( result );
  32520. } ).setLayout( {
  32521. name: 'mx_perlin_noise_vec3_0',
  32522. type: 'vec3',
  32523. inputs: [
  32524. { name: 'p', type: 'vec2' }
  32525. ]
  32526. } );
  32527. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32528. const p = vec3( p_immutable ).toVar();
  32529. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32530. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32531. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32532. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32533. const u = float( mx_fade( fx ) ).toVar();
  32534. const v = float( mx_fade( fy ) ).toVar();
  32535. const w = float( mx_fade( fz ) ).toVar();
  32536. 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();
  32537. return mx_gradient_scale3d( result );
  32538. } ).setLayout( {
  32539. name: 'mx_perlin_noise_vec3_1',
  32540. type: 'vec3',
  32541. inputs: [
  32542. { name: 'p', type: 'vec3' }
  32543. ]
  32544. } );
  32545. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  32546. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32547. const p = float( p_immutable ).toVar();
  32548. const ix = int( mx_floor( p ) ).toVar();
  32549. return mx_bits_to_01( mx_hash_int( ix ) );
  32550. } ).setLayout( {
  32551. name: 'mx_cell_noise_float_0',
  32552. type: 'float',
  32553. inputs: [
  32554. { name: 'p', type: 'float' }
  32555. ]
  32556. } );
  32557. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32558. const p = vec2( p_immutable ).toVar();
  32559. const ix = int( mx_floor( p.x ) ).toVar();
  32560. const iy = int( mx_floor( p.y ) ).toVar();
  32561. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  32562. } ).setLayout( {
  32563. name: 'mx_cell_noise_float_1',
  32564. type: 'float',
  32565. inputs: [
  32566. { name: 'p', type: 'vec2' }
  32567. ]
  32568. } );
  32569. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32570. const p = vec3( p_immutable ).toVar();
  32571. const ix = int( mx_floor( p.x ) ).toVar();
  32572. const iy = int( mx_floor( p.y ) ).toVar();
  32573. const iz = int( mx_floor( p.z ) ).toVar();
  32574. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  32575. } ).setLayout( {
  32576. name: 'mx_cell_noise_float_2',
  32577. type: 'float',
  32578. inputs: [
  32579. { name: 'p', type: 'vec3' }
  32580. ]
  32581. } );
  32582. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32583. const p = vec4( p_immutable ).toVar();
  32584. const ix = int( mx_floor( p.x ) ).toVar();
  32585. const iy = int( mx_floor( p.y ) ).toVar();
  32586. const iz = int( mx_floor( p.z ) ).toVar();
  32587. const iw = int( mx_floor( p.w ) ).toVar();
  32588. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  32589. } ).setLayout( {
  32590. name: 'mx_cell_noise_float_3',
  32591. type: 'float',
  32592. inputs: [
  32593. { name: 'p', type: 'vec4' }
  32594. ]
  32595. } );
  32596. 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 ] );
  32597. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32598. const p = float( p_immutable ).toVar();
  32599. const ix = int( mx_floor( p ) ).toVar();
  32600. 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 ) ) ) );
  32601. } ).setLayout( {
  32602. name: 'mx_cell_noise_vec3_0',
  32603. type: 'vec3',
  32604. inputs: [
  32605. { name: 'p', type: 'float' }
  32606. ]
  32607. } );
  32608. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32609. const p = vec2( p_immutable ).toVar();
  32610. const ix = int( mx_floor( p.x ) ).toVar();
  32611. const iy = int( mx_floor( p.y ) ).toVar();
  32612. 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 ) ) ) );
  32613. } ).setLayout( {
  32614. name: 'mx_cell_noise_vec3_1',
  32615. type: 'vec3',
  32616. inputs: [
  32617. { name: 'p', type: 'vec2' }
  32618. ]
  32619. } );
  32620. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32621. const p = vec3( p_immutable ).toVar();
  32622. const ix = int( mx_floor( p.x ) ).toVar();
  32623. const iy = int( mx_floor( p.y ) ).toVar();
  32624. const iz = int( mx_floor( p.z ) ).toVar();
  32625. 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 ) ) ) );
  32626. } ).setLayout( {
  32627. name: 'mx_cell_noise_vec3_2',
  32628. type: 'vec3',
  32629. inputs: [
  32630. { name: 'p', type: 'vec3' }
  32631. ]
  32632. } );
  32633. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32634. const p = vec4( p_immutable ).toVar();
  32635. const ix = int( mx_floor( p.x ) ).toVar();
  32636. const iy = int( mx_floor( p.y ) ).toVar();
  32637. const iz = int( mx_floor( p.z ) ).toVar();
  32638. const iw = int( mx_floor( p.w ) ).toVar();
  32639. 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 ) ) ) );
  32640. } ).setLayout( {
  32641. name: 'mx_cell_noise_vec3_3',
  32642. type: 'vec3',
  32643. inputs: [
  32644. { name: 'p', type: 'vec4' }
  32645. ]
  32646. } );
  32647. 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 ] );
  32648. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32649. const diminish = float( diminish_immutable ).toVar();
  32650. const lacunarity = float( lacunarity_immutable ).toVar();
  32651. const octaves = int( octaves_immutable ).toVar();
  32652. const p = vec3( p_immutable ).toVar();
  32653. const result = float( 0.0 ).toVar();
  32654. const amplitude = float( 1.0 ).toVar();
  32655. Loop( octaves, () => {
  32656. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  32657. amplitude.mulAssign( diminish );
  32658. p.mulAssign( lacunarity );
  32659. } );
  32660. return result;
  32661. } ).setLayout( {
  32662. name: 'mx_fractal_noise_float',
  32663. type: 'float',
  32664. inputs: [
  32665. { name: 'p', type: 'vec3' },
  32666. { name: 'octaves', type: 'int' },
  32667. { name: 'lacunarity', type: 'float' },
  32668. { name: 'diminish', type: 'float' }
  32669. ]
  32670. } );
  32671. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32672. const diminish = float( diminish_immutable ).toVar();
  32673. const lacunarity = float( lacunarity_immutable ).toVar();
  32674. const octaves = int( octaves_immutable ).toVar();
  32675. const p = vec3( p_immutable ).toVar();
  32676. const result = vec3( 0.0 ).toVar();
  32677. const amplitude = float( 1.0 ).toVar();
  32678. Loop( octaves, () => {
  32679. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  32680. amplitude.mulAssign( diminish );
  32681. p.mulAssign( lacunarity );
  32682. } );
  32683. return result;
  32684. } ).setLayout( {
  32685. name: 'mx_fractal_noise_vec3',
  32686. type: 'vec3',
  32687. inputs: [
  32688. { name: 'p', type: 'vec3' },
  32689. { name: 'octaves', type: 'int' },
  32690. { name: 'lacunarity', type: 'float' },
  32691. { name: 'diminish', type: 'float' }
  32692. ]
  32693. } );
  32694. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32695. const diminish = float( diminish_immutable ).toVar();
  32696. const lacunarity = float( lacunarity_immutable ).toVar();
  32697. const octaves = int( octaves_immutable ).toVar();
  32698. const p = vec3( p_immutable ).toVar();
  32699. 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 ) );
  32700. } ).setLayout( {
  32701. name: 'mx_fractal_noise_vec2',
  32702. type: 'vec2',
  32703. inputs: [
  32704. { name: 'p', type: 'vec3' },
  32705. { name: 'octaves', type: 'int' },
  32706. { name: 'lacunarity', type: 'float' },
  32707. { name: 'diminish', type: 'float' }
  32708. ]
  32709. } );
  32710. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32711. const diminish = float( diminish_immutable ).toVar();
  32712. const lacunarity = float( lacunarity_immutable ).toVar();
  32713. const octaves = int( octaves_immutable ).toVar();
  32714. const p = vec3( p_immutable ).toVar();
  32715. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  32716. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  32717. return vec4( c, f );
  32718. } ).setLayout( {
  32719. name: 'mx_fractal_noise_vec4',
  32720. type: 'vec4',
  32721. inputs: [
  32722. { name: 'p', type: 'vec3' },
  32723. { name: 'octaves', type: 'int' },
  32724. { name: 'lacunarity', type: 'float' },
  32725. { name: 'diminish', type: 'float' }
  32726. ]
  32727. } );
  32728. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  32729. const metric = int( metric_immutable ).toVar();
  32730. const jitter = float( jitter_immutable ).toVar();
  32731. const yoff = int( yoff_immutable ).toVar();
  32732. const xoff = int( xoff_immutable ).toVar();
  32733. const y = int( y_immutable ).toVar();
  32734. const x = int( x_immutable ).toVar();
  32735. const p = vec2( p_immutable ).toVar();
  32736. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  32737. const off = vec2( tmp.x, tmp.y ).toVar();
  32738. off.subAssign( 0.5 );
  32739. off.mulAssign( jitter );
  32740. off.addAssign( 0.5 );
  32741. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  32742. const diff = vec2( cellpos.sub( p ) ).toVar();
  32743. If( metric.equal( int( 2 ) ), () => {
  32744. return abs( diff.x ).add( abs( diff.y ) );
  32745. } );
  32746. If( metric.equal( int( 3 ) ), () => {
  32747. return max$1( abs( diff.x ), abs( diff.y ) );
  32748. } );
  32749. return dot( diff, diff );
  32750. } ).setLayout( {
  32751. name: 'mx_worley_distance_0',
  32752. type: 'float',
  32753. inputs: [
  32754. { name: 'p', type: 'vec2' },
  32755. { name: 'x', type: 'int' },
  32756. { name: 'y', type: 'int' },
  32757. { name: 'xoff', type: 'int' },
  32758. { name: 'yoff', type: 'int' },
  32759. { name: 'jitter', type: 'float' },
  32760. { name: 'metric', type: 'int' }
  32761. ]
  32762. } );
  32763. 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 ] ) => {
  32764. const metric = int( metric_immutable ).toVar();
  32765. const jitter = float( jitter_immutable ).toVar();
  32766. const zoff = int( zoff_immutable ).toVar();
  32767. const yoff = int( yoff_immutable ).toVar();
  32768. const xoff = int( xoff_immutable ).toVar();
  32769. const z = int( z_immutable ).toVar();
  32770. const y = int( y_immutable ).toVar();
  32771. const x = int( x_immutable ).toVar();
  32772. const p = vec3( p_immutable ).toVar();
  32773. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  32774. off.subAssign( 0.5 );
  32775. off.mulAssign( jitter );
  32776. off.addAssign( 0.5 );
  32777. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  32778. const diff = vec3( cellpos.sub( p ) ).toVar();
  32779. If( metric.equal( int( 2 ) ), () => {
  32780. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  32781. } );
  32782. If( metric.equal( int( 3 ) ), () => {
  32783. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  32784. } );
  32785. return dot( diff, diff );
  32786. } ).setLayout( {
  32787. name: 'mx_worley_distance_1',
  32788. type: 'float',
  32789. inputs: [
  32790. { name: 'p', type: 'vec3' },
  32791. { name: 'x', type: 'int' },
  32792. { name: 'y', type: 'int' },
  32793. { name: 'z', type: 'int' },
  32794. { name: 'xoff', type: 'int' },
  32795. { name: 'yoff', type: 'int' },
  32796. { name: 'zoff', type: 'int' },
  32797. { name: 'jitter', type: 'float' },
  32798. { name: 'metric', type: 'int' }
  32799. ]
  32800. } );
  32801. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  32802. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32803. const metric = int( metric_immutable ).toVar();
  32804. const jitter = float( jitter_immutable ).toVar();
  32805. const p = vec2( p_immutable ).toVar();
  32806. const X = int().toVar(), Y = int().toVar();
  32807. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32808. const sqdist = float( 1e6 ).toVar();
  32809. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32810. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32811. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32812. sqdist.assign( min$1( sqdist, dist ) );
  32813. } );
  32814. } );
  32815. If( metric.equal( int( 0 ) ), () => {
  32816. sqdist.assign( sqrt( sqdist ) );
  32817. } );
  32818. return sqdist;
  32819. } ).setLayout( {
  32820. name: 'mx_worley_noise_float_0',
  32821. type: 'float',
  32822. inputs: [
  32823. { name: 'p', type: 'vec2' },
  32824. { name: 'jitter', type: 'float' },
  32825. { name: 'metric', type: 'int' }
  32826. ]
  32827. } );
  32828. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32829. const metric = int( metric_immutable ).toVar();
  32830. const jitter = float( jitter_immutable ).toVar();
  32831. const p = vec2( p_immutable ).toVar();
  32832. const X = int().toVar(), Y = int().toVar();
  32833. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32834. const sqdist = vec2( 1e6, 1e6 ).toVar();
  32835. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32836. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32837. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32838. If( dist.lessThan( sqdist.x ), () => {
  32839. sqdist.y.assign( sqdist.x );
  32840. sqdist.x.assign( dist );
  32841. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32842. sqdist.y.assign( dist );
  32843. } );
  32844. } );
  32845. } );
  32846. If( metric.equal( int( 0 ) ), () => {
  32847. sqdist.assign( sqrt( sqdist ) );
  32848. } );
  32849. return sqdist;
  32850. } ).setLayout( {
  32851. name: 'mx_worley_noise_vec2_0',
  32852. type: 'vec2',
  32853. inputs: [
  32854. { name: 'p', type: 'vec2' },
  32855. { name: 'jitter', type: 'float' },
  32856. { name: 'metric', type: 'int' }
  32857. ]
  32858. } );
  32859. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32860. const metric = int( metric_immutable ).toVar();
  32861. const jitter = float( jitter_immutable ).toVar();
  32862. const p = vec2( p_immutable ).toVar();
  32863. const X = int().toVar(), Y = int().toVar();
  32864. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32865. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  32866. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32867. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32868. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32869. If( dist.lessThan( sqdist.x ), () => {
  32870. sqdist.z.assign( sqdist.y );
  32871. sqdist.y.assign( sqdist.x );
  32872. sqdist.x.assign( dist );
  32873. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32874. sqdist.z.assign( sqdist.y );
  32875. sqdist.y.assign( dist );
  32876. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  32877. sqdist.z.assign( dist );
  32878. } );
  32879. } );
  32880. } );
  32881. If( metric.equal( int( 0 ) ), () => {
  32882. sqdist.assign( sqrt( sqdist ) );
  32883. } );
  32884. return sqdist;
  32885. } ).setLayout( {
  32886. name: 'mx_worley_noise_vec3_0',
  32887. type: 'vec3',
  32888. inputs: [
  32889. { name: 'p', type: 'vec2' },
  32890. { name: 'jitter', type: 'float' },
  32891. { name: 'metric', type: 'int' }
  32892. ]
  32893. } );
  32894. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32895. const metric = int( metric_immutable ).toVar();
  32896. const jitter = float( jitter_immutable ).toVar();
  32897. const p = vec3( p_immutable ).toVar();
  32898. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32899. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  32900. const sqdist = float( 1e6 ).toVar();
  32901. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32902. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32903. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  32904. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  32905. sqdist.assign( min$1( sqdist, dist ) );
  32906. } );
  32907. } );
  32908. } );
  32909. If( metric.equal( int( 0 ) ), () => {
  32910. sqdist.assign( sqrt( sqdist ) );
  32911. } );
  32912. return sqdist;
  32913. } ).setLayout( {
  32914. name: 'mx_worley_noise_float_1',
  32915. type: 'float',
  32916. inputs: [
  32917. { name: 'p', type: 'vec3' },
  32918. { name: 'jitter', type: 'float' },
  32919. { name: 'metric', type: 'int' }
  32920. ]
  32921. } );
  32922. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  32923. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32924. const metric = int( metric_immutable ).toVar();
  32925. const jitter = float( jitter_immutable ).toVar();
  32926. const p = vec3( p_immutable ).toVar();
  32927. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32928. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  32929. const sqdist = vec2( 1e6, 1e6 ).toVar();
  32930. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32931. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32932. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  32933. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  32934. If( dist.lessThan( sqdist.x ), () => {
  32935. sqdist.y.assign( sqdist.x );
  32936. sqdist.x.assign( dist );
  32937. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32938. sqdist.y.assign( dist );
  32939. } );
  32940. } );
  32941. } );
  32942. } );
  32943. If( metric.equal( int( 0 ) ), () => {
  32944. sqdist.assign( sqrt( sqdist ) );
  32945. } );
  32946. return sqdist;
  32947. } ).setLayout( {
  32948. name: 'mx_worley_noise_vec2_1',
  32949. type: 'vec2',
  32950. inputs: [
  32951. { name: 'p', type: 'vec3' },
  32952. { name: 'jitter', type: 'float' },
  32953. { name: 'metric', type: 'int' }
  32954. ]
  32955. } );
  32956. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  32957. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32958. const metric = int( metric_immutable ).toVar();
  32959. const jitter = float( jitter_immutable ).toVar();
  32960. const p = vec3( p_immutable ).toVar();
  32961. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32962. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  32963. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  32964. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32965. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32966. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  32967. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  32968. If( dist.lessThan( sqdist.x ), () => {
  32969. sqdist.z.assign( sqdist.y );
  32970. sqdist.y.assign( sqdist.x );
  32971. sqdist.x.assign( dist );
  32972. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32973. sqdist.z.assign( sqdist.y );
  32974. sqdist.y.assign( dist );
  32975. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  32976. sqdist.z.assign( dist );
  32977. } );
  32978. } );
  32979. } );
  32980. } );
  32981. If( metric.equal( int( 0 ) ), () => {
  32982. sqdist.assign( sqrt( sqdist ) );
  32983. } );
  32984. return sqdist;
  32985. } ).setLayout( {
  32986. name: 'mx_worley_noise_vec3_1',
  32987. type: 'vec3',
  32988. inputs: [
  32989. { name: 'p', type: 'vec3' },
  32990. { name: 'jitter', type: 'float' },
  32991. { name: 'metric', type: 'int' }
  32992. ]
  32993. } );
  32994. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  32995. // Unified Noise 2D
  32996. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  32997. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  32998. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  32999. octaves_immutable, lacunarity_immutable, diminish_immutable
  33000. ] ) => {
  33001. const noiseType = int( noiseType_immutable ).toVar();
  33002. const texcoord = vec2( texcoord_immutable ).toVar();
  33003. const freq = vec2( freq_immutable ).toVar();
  33004. const offset = vec2( offset_immutable ).toVar();
  33005. const jitter = float( jitter_immutable ).toVar();
  33006. const outmin = float( outmin_immutable ).toVar();
  33007. const outmax = float( outmax_immutable ).toVar();
  33008. const clampoutput = bool( clampoutput_immutable ).toVar();
  33009. const octaves = int( octaves_immutable ).toVar();
  33010. const lacunarity = float( lacunarity_immutable ).toVar();
  33011. const diminish = float( diminish_immutable ).toVar();
  33012. // Compute input position
  33013. const p = texcoord.mul( freq ).add( offset );
  33014. const result = float( 0.0 ).toVar();
  33015. // Perlin
  33016. If( noiseType.equal( int( 0 ) ), () => {
  33017. result.assign( mx_perlin_noise_vec3( p ) );
  33018. } );
  33019. // Cell
  33020. If( noiseType.equal( int( 1 ) ), () => {
  33021. result.assign( mx_cell_noise_vec3( p ) );
  33022. } );
  33023. // Worley (metric=0 = euclidean)
  33024. If( noiseType.equal( int( 2 ) ), () => {
  33025. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33026. } );
  33027. // Fractal (use vec3(p, 0.0) for 2D input)
  33028. If( noiseType.equal( int( 3 ) ), () => {
  33029. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  33030. } );
  33031. // Remap output to [outmin, outmax]
  33032. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33033. // Clamp if requested
  33034. If( clampoutput, () => {
  33035. result.assign( clamp( result, outmin, outmax ) );
  33036. } );
  33037. return result;
  33038. } ).setLayout( {
  33039. name: 'mx_unifiednoise2d',
  33040. type: 'float',
  33041. inputs: [
  33042. { name: 'noiseType', type: 'int' },
  33043. { name: 'texcoord', type: 'vec2' },
  33044. { name: 'freq', type: 'vec2' },
  33045. { name: 'offset', type: 'vec2' },
  33046. { name: 'jitter', type: 'float' },
  33047. { name: 'outmin', type: 'float' },
  33048. { name: 'outmax', type: 'float' },
  33049. { name: 'clampoutput', type: 'bool' },
  33050. { name: 'octaves', type: 'int' },
  33051. { name: 'lacunarity', type: 'float' },
  33052. { name: 'diminish', type: 'float' }
  33053. ]
  33054. } );
  33055. // Unified Noise 3D
  33056. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  33057. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  33058. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33059. octaves_immutable, lacunarity_immutable, diminish_immutable
  33060. ] ) => {
  33061. const noiseType = int( noiseType_immutable ).toVar();
  33062. const position = vec3( position_immutable ).toVar();
  33063. const freq = vec3( freq_immutable ).toVar();
  33064. const offset = vec3( offset_immutable ).toVar();
  33065. const jitter = float( jitter_immutable ).toVar();
  33066. const outmin = float( outmin_immutable ).toVar();
  33067. const outmax = float( outmax_immutable ).toVar();
  33068. const clampoutput = bool( clampoutput_immutable ).toVar();
  33069. const octaves = int( octaves_immutable ).toVar();
  33070. const lacunarity = float( lacunarity_immutable ).toVar();
  33071. const diminish = float( diminish_immutable ).toVar();
  33072. // Compute input position
  33073. const p = position.mul( freq ).add( offset );
  33074. const result = float( 0.0 ).toVar();
  33075. // Perlin
  33076. If( noiseType.equal( int( 0 ) ), () => {
  33077. result.assign( mx_perlin_noise_vec3( p ) );
  33078. } );
  33079. // Cell
  33080. If( noiseType.equal( int( 1 ) ), () => {
  33081. result.assign( mx_cell_noise_vec3( p ) );
  33082. } );
  33083. // Worley (metric=0 = euclidean)
  33084. If( noiseType.equal( int( 2 ) ), () => {
  33085. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33086. } );
  33087. // Fractal
  33088. If( noiseType.equal( int( 3 ) ), () => {
  33089. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  33090. } );
  33091. // Remap output to [outmin, outmax]
  33092. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33093. // Clamp if requested
  33094. If( clampoutput, () => {
  33095. result.assign( clamp( result, outmin, outmax ) );
  33096. } );
  33097. return result;
  33098. } ).setLayout( {
  33099. name: 'mx_unifiednoise3d',
  33100. type: 'float',
  33101. inputs: [
  33102. { name: 'noiseType', type: 'int' },
  33103. { name: 'position', type: 'vec3' },
  33104. { name: 'freq', type: 'vec3' },
  33105. { name: 'offset', type: 'vec3' },
  33106. { name: 'jitter', type: 'float' },
  33107. { name: 'outmin', type: 'float' },
  33108. { name: 'outmax', type: 'float' },
  33109. { name: 'clampoutput', type: 'bool' },
  33110. { name: 'octaves', type: 'int' },
  33111. { name: 'lacunarity', type: 'float' },
  33112. { name: 'diminish', type: 'float' }
  33113. ]
  33114. } );
  33115. // Three.js Transpiler
  33116. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  33117. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  33118. const s = hsv.y;
  33119. const v = hsv.z;
  33120. const result = vec3().toVar();
  33121. If( s.lessThan( 0.0001 ), () => {
  33122. result.assign( vec3( v, v, v ) );
  33123. } ).Else( () => {
  33124. let h = hsv.x;
  33125. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  33126. const hi = int( trunc( h ) );
  33127. const f = h.sub( float( hi ) );
  33128. const p = v.mul( s.oneMinus() );
  33129. const q = v.mul( s.mul( f ).oneMinus() );
  33130. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  33131. If( hi.equal( int( 0 ) ), () => {
  33132. result.assign( vec3( v, t, p ) );
  33133. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  33134. result.assign( vec3( q, v, p ) );
  33135. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  33136. result.assign( vec3( p, v, t ) );
  33137. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  33138. result.assign( vec3( p, q, v ) );
  33139. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  33140. result.assign( vec3( t, p, v ) );
  33141. } ).Else( () => {
  33142. result.assign( vec3( v, p, q ) );
  33143. } );
  33144. } );
  33145. return result;
  33146. } ).setLayout( {
  33147. name: 'mx_hsvtorgb',
  33148. type: 'vec3',
  33149. inputs: [
  33150. { name: 'hsv', type: 'vec3' }
  33151. ]
  33152. } );
  33153. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  33154. const c = vec3( c_immutable ).toVar();
  33155. const r = float( c.x ).toVar();
  33156. const g = float( c.y ).toVar();
  33157. const b = float( c.z ).toVar();
  33158. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  33159. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  33160. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  33161. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  33162. v.assign( maxcomp );
  33163. If( maxcomp.greaterThan( 0.0 ), () => {
  33164. s.assign( delta.div( maxcomp ) );
  33165. } ).Else( () => {
  33166. s.assign( 0.0 );
  33167. } );
  33168. If( s.lessThanEqual( 0.0 ), () => {
  33169. h.assign( 0.0 );
  33170. } ).Else( () => {
  33171. If( r.greaterThanEqual( maxcomp ), () => {
  33172. h.assign( g.sub( b ).div( delta ) );
  33173. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  33174. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  33175. } ).Else( () => {
  33176. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  33177. } );
  33178. h.mulAssign( 1.0 / 6.0 );
  33179. If( h.lessThan( 0.0 ), () => {
  33180. h.addAssign( 1.0 );
  33181. } );
  33182. } );
  33183. return vec3( h, s, v );
  33184. } ).setLayout( {
  33185. name: 'mx_rgbtohsv',
  33186. type: 'vec3',
  33187. inputs: [
  33188. { name: 'c', type: 'vec3' }
  33189. ]
  33190. } );
  33191. // Three.js Transpiler
  33192. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  33193. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  33194. const color = vec3( color_immutable ).toVar();
  33195. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  33196. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  33197. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  33198. return mix( linSeg, powSeg, isAbove );
  33199. } ).setLayout( {
  33200. name: 'mx_srgb_texture_to_lin_rec709',
  33201. type: 'vec3',
  33202. inputs: [
  33203. { name: 'color', type: 'vec3' }
  33204. ]
  33205. } );
  33206. const mx_aastep = ( threshold, value ) => {
  33207. threshold = float( threshold );
  33208. value = float( value );
  33209. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  33210. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  33211. };
  33212. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  33213. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  33214. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  33215. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  33216. const mx_ramp4 = (
  33217. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  33218. ) => {
  33219. const u = texcoord.x.clamp();
  33220. const v = texcoord.y.clamp();
  33221. const top = mix( valuetl, valuetr, u );
  33222. const bottom = mix( valuebl, valuebr, u );
  33223. return mix( top, bottom, v );
  33224. };
  33225. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  33226. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  33227. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  33228. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  33229. const mx_safepower = ( in1, in2 = 1 ) => {
  33230. in1 = float( in1 );
  33231. return in1.abs().pow( in2 ).mul( in1.sign() );
  33232. };
  33233. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  33234. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33235. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33236. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33237. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  33238. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  33239. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  33240. return noise_vec4.mul( amplitude ).add( pivot );
  33241. };
  33242. 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 );
  33243. 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 );
  33244. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33245. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33246. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33247. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  33248. 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 );
  33249. 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 );
  33250. 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 );
  33251. 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 );
  33252. // === Moved from MaterialXLoader.js ===
  33253. // Math ops
  33254. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  33255. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  33256. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  33257. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  33258. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  33259. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  33260. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  33261. const mx_timer = () => time;
  33262. const mx_frame = () => frameId;
  33263. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  33264. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  33265. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  33266. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  33267. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  33268. const mx_separate = ( in1, channelOrOut = null ) => {
  33269. if ( typeof channelOrOut === 'string' ) {
  33270. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33271. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  33272. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  33273. }
  33274. if ( typeof channelOrOut === 'number' ) {
  33275. return in1.element( channelOrOut );
  33276. }
  33277. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  33278. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33279. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  33280. }
  33281. return in1;
  33282. };
  33283. const mx_place2d = (
  33284. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  33285. ) => {
  33286. let uv = texcoord;
  33287. if ( pivot ) uv = uv.sub( pivot );
  33288. if ( scale ) uv = uv.mul( scale );
  33289. if ( rotate ) {
  33290. const rad = rotate.mul( Math.PI / 180.0 );
  33291. const cosR = rad.cos();
  33292. const sinR = rad.sin();
  33293. uv = vec2(
  33294. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  33295. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  33296. );
  33297. }
  33298. if ( pivot ) uv = uv.add( pivot );
  33299. if ( offset ) uv = uv.add( offset );
  33300. return uv;
  33301. };
  33302. const mx_rotate2d = ( input, amount ) => {
  33303. input = vec2( input );
  33304. amount = float( amount );
  33305. const radians = amount.mul( Math.PI / 180.0 );
  33306. return rotate( input, radians );
  33307. };
  33308. const mx_rotate3d = ( input, amount, axis ) => {
  33309. input = vec3( input );
  33310. amount = float( amount );
  33311. axis = vec3( axis );
  33312. const radians = amount.mul( Math.PI / 180.0 );
  33313. const nAxis = axis.normalize();
  33314. const cosA = radians.cos();
  33315. const sinA = radians.sin();
  33316. const oneMinusCosA = float( 1 ).sub( cosA );
  33317. const rot =
  33318. input.mul( cosA )
  33319. .add( nAxis.cross( input ).mul( sinA ) )
  33320. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  33321. return rot;
  33322. };
  33323. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  33324. input = vec3( input );
  33325. scale = float( scale );
  33326. return bumpMap( input, scale );
  33327. };
  33328. /**
  33329. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  33330. *
  33331. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  33332. *
  33333. * ```js
  33334. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  33335. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  33336. * ```
  33337. *
  33338. * @tsl
  33339. * @function
  33340. * @param {Node<vec3>} normal - The normal to correct.
  33341. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  33342. * @param {Node<vec3>} cubePos - The cube position.
  33343. * @return {Node<vec3>} The parallax corrected normal.
  33344. */
  33345. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  33346. const nDir = normalize( normal ).toVar();
  33347. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33348. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33349. const rbminmax = vec3().toVar();
  33350. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  33351. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  33352. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  33353. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  33354. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  33355. return boxIntersection.sub( cubePos );
  33356. } );
  33357. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  33358. // normal is assumed to have unit length
  33359. const x = normal.x, y = normal.y, z = normal.z;
  33360. // band 0
  33361. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  33362. // band 1
  33363. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  33364. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  33365. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  33366. // band 2
  33367. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  33368. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  33369. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  33370. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  33371. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  33372. return result;
  33373. } );
  33374. // constants
  33375. var TSL = /*#__PURE__*/Object.freeze({
  33376. __proto__: null,
  33377. BRDF_GGX: BRDF_GGX,
  33378. BRDF_Lambert: BRDF_Lambert,
  33379. BasicPointShadowFilter: BasicPointShadowFilter,
  33380. BasicShadowFilter: BasicShadowFilter,
  33381. Break: Break,
  33382. Const: Const,
  33383. Continue: Continue,
  33384. DFGApprox: DFGApprox,
  33385. D_GGX: D_GGX,
  33386. Discard: Discard,
  33387. EPSILON: EPSILON,
  33388. F_Schlick: F_Schlick,
  33389. Fn: Fn,
  33390. HALF_PI: HALF_PI,
  33391. INFINITY: INFINITY,
  33392. If: If,
  33393. Loop: Loop,
  33394. NodeAccess: NodeAccess,
  33395. NodeShaderStage: NodeShaderStage,
  33396. NodeType: NodeType,
  33397. NodeUpdateType: NodeUpdateType,
  33398. OnBeforeMaterialUpdate: OnBeforeMaterialUpdate,
  33399. OnBeforeObjectUpdate: OnBeforeObjectUpdate,
  33400. OnMaterialUpdate: OnMaterialUpdate,
  33401. OnObjectUpdate: OnObjectUpdate,
  33402. PCFShadowFilter: PCFShadowFilter,
  33403. PCFSoftShadowFilter: PCFSoftShadowFilter,
  33404. PI: PI,
  33405. PI2: PI2,
  33406. PointShadowFilter: PointShadowFilter,
  33407. Return: Return,
  33408. Schlick_to_F0: Schlick_to_F0,
  33409. ScriptableNodeResources: ScriptableNodeResources,
  33410. ShaderNode: ShaderNode,
  33411. Stack: Stack,
  33412. Switch: Switch,
  33413. TBNViewMatrix: TBNViewMatrix,
  33414. TWO_PI: TWO_PI,
  33415. VSMShadowFilter: VSMShadowFilter,
  33416. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  33417. Var: Var,
  33418. VarIntent: VarIntent,
  33419. abs: abs,
  33420. acesFilmicToneMapping: acesFilmicToneMapping,
  33421. acos: acos,
  33422. add: add,
  33423. addMethodChaining: addMethodChaining,
  33424. addNodeElement: addNodeElement,
  33425. agxToneMapping: agxToneMapping,
  33426. all: all,
  33427. alphaT: alphaT,
  33428. and: and,
  33429. anisotropy: anisotropy,
  33430. anisotropyB: anisotropyB,
  33431. anisotropyT: anisotropyT,
  33432. any: any,
  33433. append: append,
  33434. array: array,
  33435. arrayBuffer: arrayBuffer,
  33436. asin: asin,
  33437. assign: assign,
  33438. atan: atan,
  33439. atan2: atan2,
  33440. atomicAdd: atomicAdd,
  33441. atomicAnd: atomicAnd,
  33442. atomicFunc: atomicFunc,
  33443. atomicLoad: atomicLoad,
  33444. atomicMax: atomicMax,
  33445. atomicMin: atomicMin,
  33446. atomicOr: atomicOr,
  33447. atomicStore: atomicStore,
  33448. atomicSub: atomicSub,
  33449. atomicXor: atomicXor,
  33450. attenuationColor: attenuationColor,
  33451. attenuationDistance: attenuationDistance,
  33452. attribute: attribute,
  33453. attributeArray: attributeArray,
  33454. backgroundBlurriness: backgroundBlurriness,
  33455. backgroundIntensity: backgroundIntensity,
  33456. backgroundRotation: backgroundRotation,
  33457. batch: batch,
  33458. bentNormalView: bentNormalView,
  33459. billboarding: billboarding,
  33460. bitAnd: bitAnd,
  33461. bitNot: bitNot,
  33462. bitOr: bitOr,
  33463. bitXor: bitXor,
  33464. bitangentGeometry: bitangentGeometry,
  33465. bitangentLocal: bitangentLocal,
  33466. bitangentView: bitangentView,
  33467. bitangentWorld: bitangentWorld,
  33468. bitcast: bitcast,
  33469. blendBurn: blendBurn,
  33470. blendColor: blendColor,
  33471. blendDodge: blendDodge,
  33472. blendOverlay: blendOverlay,
  33473. blendScreen: blendScreen,
  33474. blur: blur,
  33475. bool: bool,
  33476. buffer: buffer,
  33477. bufferAttribute: bufferAttribute,
  33478. builtin: builtin,
  33479. bumpMap: bumpMap,
  33480. burn: burn,
  33481. bvec2: bvec2,
  33482. bvec3: bvec3,
  33483. bvec4: bvec4,
  33484. bypass: bypass,
  33485. cache: cache,
  33486. call: call,
  33487. cameraFar: cameraFar,
  33488. cameraIndex: cameraIndex,
  33489. cameraNear: cameraNear,
  33490. cameraNormalMatrix: cameraNormalMatrix,
  33491. cameraPosition: cameraPosition,
  33492. cameraProjectionMatrix: cameraProjectionMatrix,
  33493. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  33494. cameraViewMatrix: cameraViewMatrix,
  33495. cameraViewport: cameraViewport,
  33496. cameraWorldMatrix: cameraWorldMatrix,
  33497. cbrt: cbrt,
  33498. cdl: cdl,
  33499. ceil: ceil,
  33500. checker: checker,
  33501. cineonToneMapping: cineonToneMapping,
  33502. clamp: clamp,
  33503. clearcoat: clearcoat,
  33504. clearcoatNormalView: clearcoatNormalView,
  33505. clearcoatRoughness: clearcoatRoughness,
  33506. code: code,
  33507. color: color,
  33508. colorSpaceToWorking: colorSpaceToWorking,
  33509. colorToDirection: colorToDirection,
  33510. compute: compute,
  33511. computeKernel: computeKernel,
  33512. computeSkinning: computeSkinning,
  33513. context: context,
  33514. convert: convert,
  33515. convertColorSpace: convertColorSpace,
  33516. convertToTexture: convertToTexture,
  33517. cos: cos,
  33518. countLeadingZeros: countLeadingZeros,
  33519. countOneBits: countOneBits,
  33520. countTrailingZeros: countTrailingZeros,
  33521. cross: cross,
  33522. cubeTexture: cubeTexture,
  33523. cubeTextureBase: cubeTextureBase,
  33524. cubeToUV: cubeToUV,
  33525. dFdx: dFdx,
  33526. dFdy: dFdy,
  33527. dashSize: dashSize,
  33528. debug: debug,
  33529. decrement: decrement,
  33530. decrementBefore: decrementBefore,
  33531. defaultBuildStages: defaultBuildStages,
  33532. defaultShaderStages: defaultShaderStages,
  33533. defined: defined,
  33534. degrees: degrees,
  33535. deltaTime: deltaTime,
  33536. densityFog: densityFog,
  33537. densityFogFactor: densityFogFactor,
  33538. depth: depth,
  33539. depthPass: depthPass,
  33540. determinant: determinant,
  33541. difference: difference,
  33542. diffuseColor: diffuseColor,
  33543. diffuseContribution: diffuseContribution,
  33544. directPointLight: directPointLight,
  33545. directionToColor: directionToColor,
  33546. directionToFaceDirection: directionToFaceDirection,
  33547. dispersion: dispersion,
  33548. distance: distance,
  33549. div: div,
  33550. dodge: dodge,
  33551. dot: dot,
  33552. drawIndex: drawIndex,
  33553. dynamicBufferAttribute: dynamicBufferAttribute,
  33554. element: element,
  33555. emissive: emissive,
  33556. equal: equal,
  33557. equals: equals,
  33558. equirectUV: equirectUV,
  33559. exp: exp,
  33560. exp2: exp2,
  33561. expression: expression,
  33562. faceDirection: faceDirection,
  33563. faceForward: faceForward,
  33564. faceforward: faceforward,
  33565. float: float,
  33566. floatBitsToInt: floatBitsToInt,
  33567. floatBitsToUint: floatBitsToUint,
  33568. floor: floor,
  33569. fog: fog,
  33570. fract: fract,
  33571. frameGroup: frameGroup,
  33572. frameId: frameId,
  33573. frontFacing: frontFacing,
  33574. fwidth: fwidth,
  33575. gain: gain,
  33576. gapSize: gapSize,
  33577. getConstNodeType: getConstNodeType,
  33578. getCurrentStack: getCurrentStack,
  33579. getDirection: getDirection,
  33580. getDistanceAttenuation: getDistanceAttenuation,
  33581. getGeometryRoughness: getGeometryRoughness,
  33582. getNormalFromDepth: getNormalFromDepth,
  33583. getParallaxCorrectNormal: getParallaxCorrectNormal,
  33584. getRoughness: getRoughness,
  33585. getScreenPosition: getScreenPosition,
  33586. getShIrradianceAt: getShIrradianceAt,
  33587. getShadowMaterial: getShadowMaterial,
  33588. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  33589. getTextureIndex: getTextureIndex,
  33590. getViewPosition: getViewPosition,
  33591. ggxConvolution: ggxConvolution,
  33592. globalId: globalId,
  33593. glsl: glsl,
  33594. glslFn: glslFn,
  33595. grayscale: grayscale,
  33596. greaterThan: greaterThan,
  33597. greaterThanEqual: greaterThanEqual,
  33598. hash: hash,
  33599. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  33600. highpModelViewMatrix: highpModelViewMatrix,
  33601. hue: hue,
  33602. increment: increment,
  33603. incrementBefore: incrementBefore,
  33604. inspector: inspector,
  33605. instance: instance,
  33606. instanceIndex: instanceIndex,
  33607. instancedArray: instancedArray,
  33608. instancedBufferAttribute: instancedBufferAttribute,
  33609. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  33610. instancedMesh: instancedMesh,
  33611. int: int,
  33612. intBitsToFloat: intBitsToFloat,
  33613. interleavedGradientNoise: interleavedGradientNoise,
  33614. inverse: inverse,
  33615. inverseSqrt: inverseSqrt,
  33616. inversesqrt: inversesqrt,
  33617. invocationLocalIndex: invocationLocalIndex,
  33618. invocationSubgroupIndex: invocationSubgroupIndex,
  33619. ior: ior,
  33620. iridescence: iridescence,
  33621. iridescenceIOR: iridescenceIOR,
  33622. iridescenceThickness: iridescenceThickness,
  33623. isolate: isolate,
  33624. ivec2: ivec2,
  33625. ivec3: ivec3,
  33626. ivec4: ivec4,
  33627. js: js,
  33628. label: label,
  33629. length: length,
  33630. lengthSq: lengthSq,
  33631. lessThan: lessThan,
  33632. lessThanEqual: lessThanEqual,
  33633. lightPosition: lightPosition,
  33634. lightProjectionUV: lightProjectionUV,
  33635. lightShadowMatrix: lightShadowMatrix,
  33636. lightTargetDirection: lightTargetDirection,
  33637. lightTargetPosition: lightTargetPosition,
  33638. lightViewPosition: lightViewPosition,
  33639. lightingContext: lightingContext,
  33640. lights: lights,
  33641. linearDepth: linearDepth,
  33642. linearToneMapping: linearToneMapping,
  33643. localId: localId,
  33644. log: log,
  33645. log2: log2,
  33646. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  33647. luminance: luminance,
  33648. mat2: mat2,
  33649. mat3: mat3,
  33650. mat4: mat4,
  33651. matcapUV: matcapUV,
  33652. materialAO: materialAO,
  33653. materialAlphaTest: materialAlphaTest,
  33654. materialAnisotropy: materialAnisotropy,
  33655. materialAnisotropyVector: materialAnisotropyVector,
  33656. materialAttenuationColor: materialAttenuationColor,
  33657. materialAttenuationDistance: materialAttenuationDistance,
  33658. materialClearcoat: materialClearcoat,
  33659. materialClearcoatNormal: materialClearcoatNormal,
  33660. materialClearcoatRoughness: materialClearcoatRoughness,
  33661. materialColor: materialColor,
  33662. materialDispersion: materialDispersion,
  33663. materialEmissive: materialEmissive,
  33664. materialEnvIntensity: materialEnvIntensity,
  33665. materialEnvRotation: materialEnvRotation,
  33666. materialIOR: materialIOR,
  33667. materialIridescence: materialIridescence,
  33668. materialIridescenceIOR: materialIridescenceIOR,
  33669. materialIridescenceThickness: materialIridescenceThickness,
  33670. materialLightMap: materialLightMap,
  33671. materialLineDashOffset: materialLineDashOffset,
  33672. materialLineDashSize: materialLineDashSize,
  33673. materialLineGapSize: materialLineGapSize,
  33674. materialLineScale: materialLineScale,
  33675. materialLineWidth: materialLineWidth,
  33676. materialMetalness: materialMetalness,
  33677. materialNormal: materialNormal,
  33678. materialOpacity: materialOpacity,
  33679. materialPointSize: materialPointSize,
  33680. materialReference: materialReference,
  33681. materialReflectivity: materialReflectivity,
  33682. materialRefractionRatio: materialRefractionRatio,
  33683. materialRotation: materialRotation,
  33684. materialRoughness: materialRoughness,
  33685. materialSheen: materialSheen,
  33686. materialSheenRoughness: materialSheenRoughness,
  33687. materialShininess: materialShininess,
  33688. materialSpecular: materialSpecular,
  33689. materialSpecularColor: materialSpecularColor,
  33690. materialSpecularIntensity: materialSpecularIntensity,
  33691. materialSpecularStrength: materialSpecularStrength,
  33692. materialThickness: materialThickness,
  33693. materialTransmission: materialTransmission,
  33694. max: max$1,
  33695. maxMipLevel: maxMipLevel,
  33696. mediumpModelViewMatrix: mediumpModelViewMatrix,
  33697. metalness: metalness,
  33698. min: min$1,
  33699. mix: mix,
  33700. mixElement: mixElement,
  33701. mod: mod,
  33702. modInt: modInt,
  33703. modelDirection: modelDirection,
  33704. modelNormalMatrix: modelNormalMatrix,
  33705. modelPosition: modelPosition,
  33706. modelRadius: modelRadius,
  33707. modelScale: modelScale,
  33708. modelViewMatrix: modelViewMatrix,
  33709. modelViewPosition: modelViewPosition,
  33710. modelViewProjection: modelViewProjection,
  33711. modelWorldMatrix: modelWorldMatrix,
  33712. modelWorldMatrixInverse: modelWorldMatrixInverse,
  33713. morphReference: morphReference,
  33714. mrt: mrt,
  33715. mul: mul,
  33716. mx_aastep: mx_aastep,
  33717. mx_add: mx_add,
  33718. mx_atan2: mx_atan2,
  33719. mx_cell_noise_float: mx_cell_noise_float,
  33720. mx_contrast: mx_contrast,
  33721. mx_divide: mx_divide,
  33722. mx_fractal_noise_float: mx_fractal_noise_float,
  33723. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  33724. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  33725. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  33726. mx_frame: mx_frame,
  33727. mx_heighttonormal: mx_heighttonormal,
  33728. mx_hsvtorgb: mx_hsvtorgb,
  33729. mx_ifequal: mx_ifequal,
  33730. mx_ifgreater: mx_ifgreater,
  33731. mx_ifgreatereq: mx_ifgreatereq,
  33732. mx_invert: mx_invert,
  33733. mx_modulo: mx_modulo,
  33734. mx_multiply: mx_multiply,
  33735. mx_noise_float: mx_noise_float,
  33736. mx_noise_vec3: mx_noise_vec3,
  33737. mx_noise_vec4: mx_noise_vec4,
  33738. mx_place2d: mx_place2d,
  33739. mx_power: mx_power,
  33740. mx_ramp4: mx_ramp4,
  33741. mx_ramplr: mx_ramplr,
  33742. mx_ramptb: mx_ramptb,
  33743. mx_rgbtohsv: mx_rgbtohsv,
  33744. mx_rotate2d: mx_rotate2d,
  33745. mx_rotate3d: mx_rotate3d,
  33746. mx_safepower: mx_safepower,
  33747. mx_separate: mx_separate,
  33748. mx_splitlr: mx_splitlr,
  33749. mx_splittb: mx_splittb,
  33750. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  33751. mx_subtract: mx_subtract,
  33752. mx_timer: mx_timer,
  33753. mx_transform_uv: mx_transform_uv,
  33754. mx_unifiednoise2d: mx_unifiednoise2d,
  33755. mx_unifiednoise3d: mx_unifiednoise3d,
  33756. mx_worley_noise_float: mx_worley_noise_float,
  33757. mx_worley_noise_vec2: mx_worley_noise_vec2,
  33758. mx_worley_noise_vec3: mx_worley_noise_vec3,
  33759. negate: negate,
  33760. neutralToneMapping: neutralToneMapping,
  33761. nodeArray: nodeArray,
  33762. nodeImmutable: nodeImmutable,
  33763. nodeObject: nodeObject,
  33764. nodeObjectIntent: nodeObjectIntent,
  33765. nodeObjects: nodeObjects,
  33766. nodeProxy: nodeProxy,
  33767. nodeProxyIntent: nodeProxyIntent,
  33768. normalFlat: normalFlat,
  33769. normalGeometry: normalGeometry,
  33770. normalLocal: normalLocal,
  33771. normalMap: normalMap,
  33772. normalView: normalView,
  33773. normalViewGeometry: normalViewGeometry,
  33774. normalWorld: normalWorld,
  33775. normalWorldGeometry: normalWorldGeometry,
  33776. normalize: normalize,
  33777. not: not,
  33778. notEqual: notEqual,
  33779. numWorkgroups: numWorkgroups,
  33780. objectDirection: objectDirection,
  33781. objectGroup: objectGroup,
  33782. objectPosition: objectPosition,
  33783. objectRadius: objectRadius,
  33784. objectScale: objectScale,
  33785. objectViewPosition: objectViewPosition,
  33786. objectWorldMatrix: objectWorldMatrix,
  33787. oneMinus: oneMinus,
  33788. or: or,
  33789. orthographicDepthToViewZ: orthographicDepthToViewZ,
  33790. oscSawtooth: oscSawtooth,
  33791. oscSine: oscSine,
  33792. oscSquare: oscSquare,
  33793. oscTriangle: oscTriangle,
  33794. output: output,
  33795. outputStruct: outputStruct,
  33796. overlay: overlay,
  33797. overloadingFn: overloadingFn,
  33798. packHalf2x16: packHalf2x16,
  33799. packSnorm2x16: packSnorm2x16,
  33800. packUnorm2x16: packUnorm2x16,
  33801. parabola: parabola,
  33802. parallaxDirection: parallaxDirection,
  33803. parallaxUV: parallaxUV,
  33804. parameter: parameter,
  33805. pass: pass,
  33806. passTexture: passTexture,
  33807. pcurve: pcurve,
  33808. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  33809. pmremTexture: pmremTexture,
  33810. pointShadow: pointShadow,
  33811. pointUV: pointUV,
  33812. pointWidth: pointWidth,
  33813. positionGeometry: positionGeometry,
  33814. positionLocal: positionLocal,
  33815. positionPrevious: positionPrevious,
  33816. positionView: positionView,
  33817. positionViewDirection: positionViewDirection,
  33818. positionWorld: positionWorld,
  33819. positionWorldDirection: positionWorldDirection,
  33820. posterize: posterize,
  33821. pow: pow,
  33822. pow2: pow2,
  33823. pow3: pow3,
  33824. pow4: pow4,
  33825. premultiplyAlpha: premultiplyAlpha,
  33826. property: property,
  33827. quadBroadcast: quadBroadcast,
  33828. quadSwapDiagonal: quadSwapDiagonal,
  33829. quadSwapX: quadSwapX,
  33830. quadSwapY: quadSwapY,
  33831. radians: radians,
  33832. rand: rand,
  33833. range: range,
  33834. rangeFog: rangeFog,
  33835. rangeFogFactor: rangeFogFactor,
  33836. reciprocal: reciprocal,
  33837. reference: reference,
  33838. referenceBuffer: referenceBuffer,
  33839. reflect: reflect,
  33840. reflectVector: reflectVector,
  33841. reflectView: reflectView,
  33842. reflector: reflector,
  33843. refract: refract,
  33844. refractVector: refractVector,
  33845. refractView: refractView,
  33846. reinhardToneMapping: reinhardToneMapping,
  33847. remap: remap,
  33848. remapClamp: remapClamp,
  33849. renderGroup: renderGroup,
  33850. renderOutput: renderOutput,
  33851. rendererReference: rendererReference,
  33852. replaceDefaultUV: replaceDefaultUV,
  33853. rotate: rotate,
  33854. rotateUV: rotateUV,
  33855. roughness: roughness,
  33856. round: round,
  33857. rtt: rtt,
  33858. sRGBTransferEOTF: sRGBTransferEOTF,
  33859. sRGBTransferOETF: sRGBTransferOETF,
  33860. sample: sample,
  33861. sampler: sampler,
  33862. samplerComparison: samplerComparison,
  33863. saturate: saturate,
  33864. saturation: saturation,
  33865. screen: screen,
  33866. screenCoordinate: screenCoordinate,
  33867. screenDPR: screenDPR,
  33868. screenSize: screenSize,
  33869. screenUV: screenUV,
  33870. scriptable: scriptable,
  33871. scriptableValue: scriptableValue,
  33872. select: select,
  33873. setCurrentStack: setCurrentStack,
  33874. setName: setName,
  33875. shaderStages: shaderStages,
  33876. shadow: shadow,
  33877. shadowPositionWorld: shadowPositionWorld,
  33878. shapeCircle: shapeCircle,
  33879. sharedUniformGroup: sharedUniformGroup,
  33880. sheen: sheen,
  33881. sheenRoughness: sheenRoughness,
  33882. shiftLeft: shiftLeft,
  33883. shiftRight: shiftRight,
  33884. shininess: shininess,
  33885. sign: sign,
  33886. sin: sin,
  33887. sinc: sinc,
  33888. skinning: skinning,
  33889. smoothstep: smoothstep,
  33890. smoothstepElement: smoothstepElement,
  33891. specularColor: specularColor,
  33892. specularColorBlended: specularColorBlended,
  33893. specularF90: specularF90,
  33894. spherizeUV: spherizeUV,
  33895. split: split,
  33896. spritesheetUV: spritesheetUV,
  33897. sqrt: sqrt,
  33898. stack: stack,
  33899. step: step,
  33900. stepElement: stepElement,
  33901. storage: storage,
  33902. storageBarrier: storageBarrier,
  33903. storageObject: storageObject,
  33904. storageTexture: storageTexture,
  33905. string: string,
  33906. struct: struct,
  33907. sub: sub,
  33908. subBuild: subBuild,
  33909. subgroupAdd: subgroupAdd,
  33910. subgroupAll: subgroupAll,
  33911. subgroupAnd: subgroupAnd,
  33912. subgroupAny: subgroupAny,
  33913. subgroupBallot: subgroupBallot,
  33914. subgroupBroadcast: subgroupBroadcast,
  33915. subgroupBroadcastFirst: subgroupBroadcastFirst,
  33916. subgroupElect: subgroupElect,
  33917. subgroupExclusiveAdd: subgroupExclusiveAdd,
  33918. subgroupExclusiveMul: subgroupExclusiveMul,
  33919. subgroupInclusiveAdd: subgroupInclusiveAdd,
  33920. subgroupInclusiveMul: subgroupInclusiveMul,
  33921. subgroupIndex: subgroupIndex,
  33922. subgroupMax: subgroupMax,
  33923. subgroupMin: subgroupMin,
  33924. subgroupMul: subgroupMul,
  33925. subgroupOr: subgroupOr,
  33926. subgroupShuffle: subgroupShuffle,
  33927. subgroupShuffleDown: subgroupShuffleDown,
  33928. subgroupShuffleUp: subgroupShuffleUp,
  33929. subgroupShuffleXor: subgroupShuffleXor,
  33930. subgroupSize: subgroupSize,
  33931. subgroupXor: subgroupXor,
  33932. tan: tan,
  33933. tangentGeometry: tangentGeometry,
  33934. tangentLocal: tangentLocal,
  33935. tangentView: tangentView,
  33936. tangentWorld: tangentWorld,
  33937. texture: texture,
  33938. texture3D: texture3D,
  33939. texture3DLevel: texture3DLevel,
  33940. texture3DLoad: texture3DLoad,
  33941. textureBarrier: textureBarrier,
  33942. textureBicubic: textureBicubic,
  33943. textureBicubicLevel: textureBicubicLevel,
  33944. textureCubeUV: textureCubeUV,
  33945. textureLevel: textureLevel,
  33946. textureLoad: textureLoad,
  33947. textureSize: textureSize,
  33948. textureStore: textureStore,
  33949. thickness: thickness,
  33950. time: time,
  33951. toneMapping: toneMapping,
  33952. toneMappingExposure: toneMappingExposure,
  33953. toonOutlinePass: toonOutlinePass,
  33954. transformDirection: transformDirection,
  33955. transformNormal: transformNormal,
  33956. transformNormalToView: transformNormalToView,
  33957. transformedClearcoatNormalView: transformedClearcoatNormalView,
  33958. transformedNormalView: transformedNormalView,
  33959. transformedNormalWorld: transformedNormalWorld,
  33960. transmission: transmission,
  33961. transpose: transpose,
  33962. triNoise3D: triNoise3D,
  33963. triplanarTexture: triplanarTexture,
  33964. triplanarTextures: triplanarTextures,
  33965. trunc: trunc,
  33966. uint: uint,
  33967. uintBitsToFloat: uintBitsToFloat,
  33968. uniform: uniform,
  33969. uniformArray: uniformArray,
  33970. uniformCubeTexture: uniformCubeTexture,
  33971. uniformFlow: uniformFlow,
  33972. uniformGroup: uniformGroup,
  33973. uniformTexture: uniformTexture,
  33974. unpackHalf2x16: unpackHalf2x16,
  33975. unpackNormal: unpackNormal,
  33976. unpackSnorm2x16: unpackSnorm2x16,
  33977. unpackUnorm2x16: unpackUnorm2x16,
  33978. unpremultiplyAlpha: unpremultiplyAlpha,
  33979. userData: userData,
  33980. uv: uv$1,
  33981. uvec2: uvec2,
  33982. uvec3: uvec3,
  33983. uvec4: uvec4,
  33984. varying: varying,
  33985. varyingProperty: varyingProperty,
  33986. vec2: vec2,
  33987. vec3: vec3,
  33988. vec4: vec4,
  33989. vectorComponents: vectorComponents,
  33990. velocity: velocity,
  33991. vertexColor: vertexColor,
  33992. vertexIndex: vertexIndex,
  33993. vertexStage: vertexStage,
  33994. vibrance: vibrance,
  33995. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  33996. viewZToOrthographicDepth: viewZToOrthographicDepth,
  33997. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  33998. viewport: viewport,
  33999. viewportCoordinate: viewportCoordinate,
  34000. viewportDepthTexture: viewportDepthTexture,
  34001. viewportLinearDepth: viewportLinearDepth,
  34002. viewportMipTexture: viewportMipTexture,
  34003. viewportResolution: viewportResolution,
  34004. viewportSafeUV: viewportSafeUV,
  34005. viewportSharedTexture: viewportSharedTexture,
  34006. viewportSize: viewportSize,
  34007. viewportTexture: viewportTexture,
  34008. viewportUV: viewportUV,
  34009. wgsl: wgsl,
  34010. wgslFn: wgslFn,
  34011. workgroupArray: workgroupArray,
  34012. workgroupBarrier: workgroupBarrier,
  34013. workgroupId: workgroupId,
  34014. workingToColorSpace: workingToColorSpace,
  34015. xor: xor
  34016. });
  34017. const _clearColor = /*@__PURE__*/ new Color4();
  34018. /**
  34019. * This renderer module manages the background.
  34020. *
  34021. * @private
  34022. * @augments DataMap
  34023. */
  34024. class Background extends DataMap {
  34025. /**
  34026. * Constructs a new background management component.
  34027. *
  34028. * @param {Renderer} renderer - The renderer.
  34029. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  34030. */
  34031. constructor( renderer, nodes ) {
  34032. super();
  34033. /**
  34034. * The renderer.
  34035. *
  34036. * @type {Renderer}
  34037. */
  34038. this.renderer = renderer;
  34039. /**
  34040. * Renderer component for managing nodes related logic.
  34041. *
  34042. * @type {Nodes}
  34043. */
  34044. this.nodes = nodes;
  34045. }
  34046. /**
  34047. * Updates the background for the given scene. Depending on how `Scene.background`
  34048. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  34049. * or add a mesh to the render list for rendering the background as a textured plane
  34050. * or skybox.
  34051. *
  34052. * @param {Scene} scene - The scene.
  34053. * @param {RenderList} renderList - The current render list.
  34054. * @param {RenderContext} renderContext - The current render context.
  34055. */
  34056. update( scene, renderList, renderContext ) {
  34057. const renderer = this.renderer;
  34058. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  34059. let forceClear = false;
  34060. if ( background === null ) {
  34061. // no background settings, use clear color configuration from the renderer
  34062. renderer._clearColor.getRGB( _clearColor );
  34063. _clearColor.a = renderer._clearColor.a;
  34064. } else if ( background.isColor === true ) {
  34065. // background is an opaque color
  34066. background.getRGB( _clearColor );
  34067. _clearColor.a = 1;
  34068. forceClear = true;
  34069. } else if ( background.isNode === true ) {
  34070. const sceneData = this.get( scene );
  34071. const backgroundNode = background;
  34072. _clearColor.copy( renderer._clearColor );
  34073. let backgroundMesh = sceneData.backgroundMesh;
  34074. if ( backgroundMesh === undefined ) {
  34075. const backgroundMeshNode = vec4( backgroundNode ).mul( backgroundIntensity ).context( {
  34076. // @TODO: Add Texture2D support using node context
  34077. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  34078. getTextureLevel: () => backgroundBlurriness
  34079. } );
  34080. // when using orthographic cameras, we must scale the skybox sphere
  34081. // up to exceed the dimensions of the camera's viewing box.
  34082. const isOrtho = cameraProjectionMatrix.element( 3 ).element( 3 ).equal( 1.0 );
  34083. // calculate the orthographic scale
  34084. // projectionMatrix[1][1] is (1 / top). Invert it to get the height and multiply by 3.0
  34085. // (an arbitrary safety factor) to ensure the skybox is large enough to cover the corners
  34086. // of the rectangular screen
  34087. const orthoScale = div( 1.0, cameraProjectionMatrix.element( 1 ).element( 1 ) ).mul( 3.0 );
  34088. // compute vertex position
  34089. const modifiedPosition = isOrtho.select( positionLocal.mul( orthoScale ), positionLocal );
  34090. let viewProj = cameraProjectionMatrix.mul( modelViewMatrix.mul( vec4( modifiedPosition, 1.0 ) ) );
  34091. // force background to far plane so it does not occlude objects
  34092. viewProj = viewProj.setZ( viewProj.w );
  34093. const nodeMaterial = new NodeMaterial();
  34094. nodeMaterial.name = 'Background.material';
  34095. nodeMaterial.side = BackSide;
  34096. nodeMaterial.depthTest = false;
  34097. nodeMaterial.depthWrite = false;
  34098. nodeMaterial.allowOverride = false;
  34099. nodeMaterial.fog = false;
  34100. nodeMaterial.lights = false;
  34101. nodeMaterial.vertexNode = viewProj;
  34102. nodeMaterial.colorNode = backgroundMeshNode;
  34103. sceneData.backgroundMeshNode = backgroundMeshNode;
  34104. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  34105. backgroundMesh.frustumCulled = false;
  34106. backgroundMesh.name = 'Background.mesh';
  34107. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  34108. this.matrixWorld.copyPosition( camera.matrixWorld );
  34109. };
  34110. function onBackgroundDispose() {
  34111. background.removeEventListener( 'dispose', onBackgroundDispose );
  34112. backgroundMesh.material.dispose();
  34113. backgroundMesh.geometry.dispose();
  34114. }
  34115. background.addEventListener( 'dispose', onBackgroundDispose );
  34116. }
  34117. const backgroundCacheKey = backgroundNode.getCacheKey();
  34118. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  34119. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  34120. sceneData.backgroundMeshNode.needsUpdate = true;
  34121. backgroundMesh.material.needsUpdate = true;
  34122. sceneData.backgroundCacheKey = backgroundCacheKey;
  34123. }
  34124. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  34125. } else {
  34126. error( 'Renderer: Unsupported background configuration.', background );
  34127. }
  34128. //
  34129. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  34130. if ( environmentBlendMode === 'additive' ) {
  34131. _clearColor.set( 0, 0, 0, 1 );
  34132. } else if ( environmentBlendMode === 'alpha-blend' ) {
  34133. _clearColor.set( 0, 0, 0, 0 );
  34134. }
  34135. //
  34136. if ( renderer.autoClear === true || forceClear === true ) {
  34137. const clearColorValue = renderContext.clearColorValue;
  34138. clearColorValue.r = _clearColor.r;
  34139. clearColorValue.g = _clearColor.g;
  34140. clearColorValue.b = _clearColor.b;
  34141. clearColorValue.a = _clearColor.a;
  34142. // premultiply alpha
  34143. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  34144. clearColorValue.r *= clearColorValue.a;
  34145. clearColorValue.g *= clearColorValue.a;
  34146. clearColorValue.b *= clearColorValue.a;
  34147. }
  34148. //
  34149. renderContext.depthClearValue = renderer._clearDepth;
  34150. renderContext.stencilClearValue = renderer._clearStencil;
  34151. renderContext.clearColor = renderer.autoClearColor === true;
  34152. renderContext.clearDepth = renderer.autoClearDepth === true;
  34153. renderContext.clearStencil = renderer.autoClearStencil === true;
  34154. } else {
  34155. renderContext.clearColor = false;
  34156. renderContext.clearDepth = false;
  34157. renderContext.clearStencil = false;
  34158. }
  34159. }
  34160. }
  34161. let _id$7 = 0;
  34162. /**
  34163. * A bind group represents a collection of bindings and thus a collection
  34164. * or resources. Bind groups are assigned to pipelines to provide them
  34165. * with the required resources (like uniform buffers or textures).
  34166. *
  34167. * @private
  34168. */
  34169. class BindGroup {
  34170. /**
  34171. * Constructs a new bind group.
  34172. *
  34173. * @param {string} name - The bind group's name.
  34174. * @param {Array<Binding>} bindings - An array of bindings.
  34175. * @param {number} index - The group index.
  34176. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  34177. */
  34178. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  34179. /**
  34180. * The bind group's name.
  34181. *
  34182. * @type {string}
  34183. */
  34184. this.name = name;
  34185. /**
  34186. * An array of bindings.
  34187. *
  34188. * @type {Array<Binding>}
  34189. */
  34190. this.bindings = bindings;
  34191. /**
  34192. * The group index.
  34193. *
  34194. * @type {number}
  34195. */
  34196. this.index = index;
  34197. /**
  34198. * An array of reference bindings.
  34199. *
  34200. * @type {Array<Binding>}
  34201. */
  34202. this.bindingsReference = bindingsReference;
  34203. /**
  34204. * The group's ID.
  34205. *
  34206. * @type {number}
  34207. */
  34208. this.id = _id$7 ++;
  34209. }
  34210. }
  34211. /**
  34212. * This module represents the state of a node builder after it was
  34213. * used to build the nodes for a render object. The state holds the
  34214. * results of the build for further processing in the renderer.
  34215. *
  34216. * Render objects with identical cache keys share the same node builder state.
  34217. *
  34218. * @private
  34219. */
  34220. class NodeBuilderState {
  34221. /**
  34222. * Constructs a new node builder state.
  34223. *
  34224. * @param {string} vertexShader - The native vertex shader code.
  34225. * @param {string} fragmentShader - The native fragment shader code.
  34226. * @param {string} computeShader - The native compute shader code.
  34227. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  34228. * @param {Array<BindGroup>} bindings - An array of bind groups.
  34229. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  34230. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  34231. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  34232. * @param {NodeMaterialObserver} observer - A node material observer.
  34233. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  34234. */
  34235. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  34236. /**
  34237. * The native vertex shader code.
  34238. *
  34239. * @type {string}
  34240. */
  34241. this.vertexShader = vertexShader;
  34242. /**
  34243. * The native fragment shader code.
  34244. *
  34245. * @type {string}
  34246. */
  34247. this.fragmentShader = fragmentShader;
  34248. /**
  34249. * The native compute shader code.
  34250. *
  34251. * @type {string}
  34252. */
  34253. this.computeShader = computeShader;
  34254. /**
  34255. * An array with transform attribute objects.
  34256. * Only relevant when using compute shaders with WebGL 2.
  34257. *
  34258. * @type {Array<Object>}
  34259. */
  34260. this.transforms = transforms;
  34261. /**
  34262. * An array of node attributes representing
  34263. * the attributes of the shaders.
  34264. *
  34265. * @type {Array<NodeAttribute>}
  34266. */
  34267. this.nodeAttributes = nodeAttributes;
  34268. /**
  34269. * An array of bind groups representing the uniform or storage
  34270. * buffers, texture or samplers of the shader.
  34271. *
  34272. * @type {Array<BindGroup>}
  34273. */
  34274. this.bindings = bindings;
  34275. /**
  34276. * An array of nodes that implement their `update()` method.
  34277. *
  34278. * @type {Array<Node>}
  34279. */
  34280. this.updateNodes = updateNodes;
  34281. /**
  34282. * An array of nodes that implement their `updateBefore()` method.
  34283. *
  34284. * @type {Array<Node>}
  34285. */
  34286. this.updateBeforeNodes = updateBeforeNodes;
  34287. /**
  34288. * An array of nodes that implement their `updateAfter()` method.
  34289. *
  34290. * @type {Array<Node>}
  34291. */
  34292. this.updateAfterNodes = updateAfterNodes;
  34293. /**
  34294. * A node material observer.
  34295. *
  34296. * @type {NodeMaterialObserver}
  34297. */
  34298. this.observer = observer;
  34299. /**
  34300. * How often this state is used by render objects.
  34301. *
  34302. * @type {number}
  34303. */
  34304. this.usedTimes = 0;
  34305. }
  34306. /**
  34307. * This method is used to create a array of bind groups based
  34308. * on the existing bind groups of this state. Shared groups are
  34309. * not cloned.
  34310. *
  34311. * @return {Array<BindGroup>} A array of bind groups.
  34312. */
  34313. createBindings() {
  34314. const bindings = [];
  34315. for ( const instanceGroup of this.bindings ) {
  34316. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  34317. if ( shared !== true ) {
  34318. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup.bindingsReference );
  34319. bindings.push( bindingsGroup );
  34320. for ( const instanceBinding of instanceGroup.bindings ) {
  34321. bindingsGroup.bindings.push( instanceBinding.clone() );
  34322. }
  34323. } else {
  34324. bindings.push( instanceGroup );
  34325. }
  34326. }
  34327. return bindings;
  34328. }
  34329. }
  34330. /**
  34331. * {@link NodeBuilder} is going to create instances of this class during the build process
  34332. * of nodes. They represent the final shader attributes that are going to be generated
  34333. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  34334. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  34335. */
  34336. class NodeAttribute {
  34337. /**
  34338. * Constructs a new node attribute.
  34339. *
  34340. * @param {string} name - The name of the attribute.
  34341. * @param {string} type - The type of the attribute.
  34342. * @param {?Node} node - An optional reference to the node.
  34343. */
  34344. constructor( name, type, node = null ) {
  34345. /**
  34346. * This flag can be used for type testing.
  34347. *
  34348. * @type {boolean}
  34349. * @readonly
  34350. * @default true
  34351. */
  34352. this.isNodeAttribute = true;
  34353. /**
  34354. * The name of the attribute.
  34355. *
  34356. * @type {string}
  34357. */
  34358. this.name = name;
  34359. /**
  34360. * The type of the attribute.
  34361. *
  34362. * @type {string}
  34363. */
  34364. this.type = type;
  34365. /**
  34366. * An optional reference to the node.
  34367. *
  34368. * @type {?Node}
  34369. * @default null
  34370. */
  34371. this.node = node;
  34372. }
  34373. }
  34374. /**
  34375. * {@link NodeBuilder} is going to create instances of this class during the build process
  34376. * of nodes. They represent the final shader uniforms that are going to be generated
  34377. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  34378. * for this purpose.
  34379. */
  34380. class NodeUniform {
  34381. /**
  34382. * Constructs a new node uniform.
  34383. *
  34384. * @param {string} name - The name of the uniform.
  34385. * @param {string} type - The type of the uniform.
  34386. * @param {UniformNode} node - An reference to the node.
  34387. */
  34388. constructor( name, type, node ) {
  34389. /**
  34390. * This flag can be used for type testing.
  34391. *
  34392. * @type {boolean}
  34393. * @readonly
  34394. * @default true
  34395. */
  34396. this.isNodeUniform = true;
  34397. /**
  34398. * The name of the uniform.
  34399. *
  34400. * @type {string}
  34401. */
  34402. this.name = name;
  34403. /**
  34404. * The type of the uniform.
  34405. *
  34406. * @type {string}
  34407. */
  34408. this.type = type;
  34409. /**
  34410. * An reference to the node.
  34411. *
  34412. * @type {UniformNode}
  34413. */
  34414. this.node = node;
  34415. }
  34416. /**
  34417. * The value of the uniform node.
  34418. *
  34419. * @type {any}
  34420. */
  34421. get value() {
  34422. return this.node.value;
  34423. }
  34424. set value( val ) {
  34425. this.node.value = val;
  34426. }
  34427. /**
  34428. * The id of the uniform node.
  34429. *
  34430. * @type {number}
  34431. */
  34432. get id() {
  34433. return this.node.id;
  34434. }
  34435. /**
  34436. * The uniform node's group.
  34437. *
  34438. * @type {UniformGroupNode}
  34439. */
  34440. get groupNode() {
  34441. return this.node.groupNode;
  34442. }
  34443. }
  34444. /**
  34445. * {@link NodeBuilder} is going to create instances of this class during the build process
  34446. * of nodes. They represent the final shader variables that are going to be generated
  34447. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  34448. * this purpose.
  34449. */
  34450. class NodeVar {
  34451. /**
  34452. * Constructs a new node variable.
  34453. *
  34454. * @param {string} name - The name of the variable.
  34455. * @param {string} type - The type of the variable.
  34456. * @param {boolean} [readOnly=false] - The read-only flag.
  34457. * @param {?number} [count=null] - The size.
  34458. */
  34459. constructor( name, type, readOnly = false, count = null ) {
  34460. /**
  34461. * This flag can be used for type testing.
  34462. *
  34463. * @type {boolean}
  34464. * @readonly
  34465. * @default true
  34466. */
  34467. this.isNodeVar = true;
  34468. /**
  34469. * The name of the variable.
  34470. *
  34471. * @type {string}
  34472. */
  34473. this.name = name;
  34474. /**
  34475. * The type of the variable.
  34476. *
  34477. * @type {string}
  34478. */
  34479. this.type = type;
  34480. /**
  34481. * The read-only flag.
  34482. *
  34483. * @type {boolean}
  34484. */
  34485. this.readOnly = readOnly;
  34486. /**
  34487. * The size.
  34488. *
  34489. * @type {?number}
  34490. */
  34491. this.count = count;
  34492. }
  34493. }
  34494. /**
  34495. * {@link NodeBuilder} is going to create instances of this class during the build process
  34496. * of nodes. They represent the final shader varyings that are going to be generated
  34497. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  34498. * this purpose.
  34499. *
  34500. * @augments NodeVar
  34501. */
  34502. class NodeVarying extends NodeVar {
  34503. /**
  34504. * Constructs a new node varying.
  34505. *
  34506. * @param {string} name - The name of the varying.
  34507. * @param {string} type - The type of the varying.
  34508. * @param {?string} interpolationType - The interpolation type of the varying.
  34509. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  34510. */
  34511. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  34512. super( name, type );
  34513. /**
  34514. * Whether this varying requires interpolation or not. This property can be used
  34515. * to check if the varying can be optimized for a variable.
  34516. *
  34517. * @type {boolean}
  34518. * @default false
  34519. */
  34520. this.needsInterpolation = false;
  34521. /**
  34522. * This flag can be used for type testing.
  34523. *
  34524. * @type {boolean}
  34525. * @readonly
  34526. * @default true
  34527. */
  34528. this.isNodeVarying = true;
  34529. /**
  34530. * The interpolation type of the varying data.
  34531. *
  34532. * @type {?string}
  34533. * @default null
  34534. */
  34535. this.interpolationType = interpolationType;
  34536. /**
  34537. * The interpolation sampling type of varying data.
  34538. *
  34539. * @type {?string}
  34540. * @default null
  34541. */
  34542. this.interpolationSampling = interpolationSampling;
  34543. }
  34544. }
  34545. /**
  34546. * {@link NodeBuilder} is going to create instances of this class during the build process
  34547. * of nodes. They represent user-defined, native shader code portions that are going to be
  34548. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  34549. * for this purpose.
  34550. */
  34551. class NodeCode {
  34552. /**
  34553. * Constructs a new code node.
  34554. *
  34555. * @param {string} name - The name of the code.
  34556. * @param {string} type - The node type.
  34557. * @param {string} [code=''] - The native shader code.
  34558. */
  34559. constructor( name, type, code = '' ) {
  34560. /**
  34561. * The name of the code.
  34562. *
  34563. * @type {string}
  34564. */
  34565. this.name = name;
  34566. /**
  34567. * The node type.
  34568. *
  34569. * @type {string}
  34570. */
  34571. this.type = type;
  34572. /**
  34573. * The native shader code.
  34574. *
  34575. * @type {string}
  34576. * @default ''
  34577. */
  34578. this.code = code;
  34579. Object.defineProperty( this, 'isNodeCode', { value: true } );
  34580. }
  34581. }
  34582. let _id$6 = 0;
  34583. /**
  34584. * This utility class is used in {@link NodeBuilder} as an internal
  34585. * cache data structure for node data.
  34586. */
  34587. class NodeCache {
  34588. /**
  34589. * Constructs a new node cache.
  34590. *
  34591. * @param {?NodeCache} parent - A reference to a parent cache.
  34592. */
  34593. constructor( parent = null ) {
  34594. /**
  34595. * The id of the cache.
  34596. *
  34597. * @type {number}
  34598. * @readonly
  34599. */
  34600. this.id = _id$6 ++;
  34601. /**
  34602. * A weak map for managing node data.
  34603. *
  34604. * @type {WeakMap<Node, Object>}
  34605. */
  34606. this.nodesData = new WeakMap();
  34607. /**
  34608. * Reference to a parent node cache.
  34609. *
  34610. * @type {?NodeCache}
  34611. * @default null
  34612. */
  34613. this.parent = parent;
  34614. }
  34615. /**
  34616. * Returns the data for the given node.
  34617. *
  34618. * @param {Node} node - The node.
  34619. * @return {?Object} The data for the node.
  34620. */
  34621. getData( node ) {
  34622. let data = this.nodesData.get( node );
  34623. if ( data === undefined && this.parent !== null ) {
  34624. data = this.parent.getData( node );
  34625. }
  34626. return data;
  34627. }
  34628. /**
  34629. * Sets the data for a given node.
  34630. *
  34631. * @param {Node} node - The node.
  34632. * @param {Object} data - The data that should be cached.
  34633. */
  34634. setData( node, data ) {
  34635. this.nodesData.set( node, data );
  34636. }
  34637. }
  34638. class StructType {
  34639. constructor( name, members ) {
  34640. this.name = name;
  34641. this.members = members;
  34642. this.output = false;
  34643. }
  34644. }
  34645. /**
  34646. * Abstract base class for uniforms.
  34647. *
  34648. * @abstract
  34649. * @private
  34650. */
  34651. class Uniform {
  34652. /**
  34653. * Constructs a new uniform.
  34654. *
  34655. * @param {string} name - The uniform's name.
  34656. * @param {any} value - The uniform's value.
  34657. */
  34658. constructor( name, value ) {
  34659. /**
  34660. * The uniform's name.
  34661. *
  34662. * @type {string}
  34663. */
  34664. this.name = name;
  34665. /**
  34666. * The uniform's value.
  34667. *
  34668. * @type {any}
  34669. */
  34670. this.value = value;
  34671. /**
  34672. * Used to build the uniform buffer according to the STD140 layout.
  34673. * Derived uniforms will set this property to a data type specific
  34674. * value.
  34675. *
  34676. * @type {number}
  34677. */
  34678. this.boundary = 0;
  34679. /**
  34680. * The item size. Derived uniforms will set this property to a data
  34681. * type specific value.
  34682. *
  34683. * @type {number}
  34684. */
  34685. this.itemSize = 0;
  34686. /**
  34687. * This property is set by {@link UniformsGroup} and marks
  34688. * the start position in the uniform buffer.
  34689. *
  34690. * @type {number}
  34691. */
  34692. this.offset = 0;
  34693. }
  34694. /**
  34695. * Sets the uniform's value.
  34696. *
  34697. * @param {any} value - The value to set.
  34698. */
  34699. setValue( value ) {
  34700. this.value = value;
  34701. }
  34702. /**
  34703. * Returns the uniform's value.
  34704. *
  34705. * @return {any} The value.
  34706. */
  34707. getValue() {
  34708. return this.value;
  34709. }
  34710. }
  34711. /**
  34712. * Represents a Number uniform.
  34713. *
  34714. * @private
  34715. * @augments Uniform
  34716. */
  34717. class NumberUniform extends Uniform {
  34718. /**
  34719. * Constructs a new Number uniform.
  34720. *
  34721. * @param {string} name - The uniform's name.
  34722. * @param {number} value - The uniform's value.
  34723. */
  34724. constructor( name, value = 0 ) {
  34725. super( name, value );
  34726. /**
  34727. * This flag can be used for type testing.
  34728. *
  34729. * @type {boolean}
  34730. * @readonly
  34731. * @default true
  34732. */
  34733. this.isNumberUniform = true;
  34734. this.boundary = 4;
  34735. this.itemSize = 1;
  34736. }
  34737. }
  34738. /**
  34739. * Represents a Vector2 uniform.
  34740. *
  34741. * @private
  34742. * @augments Uniform
  34743. */
  34744. class Vector2Uniform extends Uniform {
  34745. /**
  34746. * Constructs a new Number uniform.
  34747. *
  34748. * @param {string} name - The uniform's name.
  34749. * @param {Vector2} value - The uniform's value.
  34750. */
  34751. constructor( name, value = new Vector2() ) {
  34752. super( name, value );
  34753. /**
  34754. * This flag can be used for type testing.
  34755. *
  34756. * @type {boolean}
  34757. * @readonly
  34758. * @default true
  34759. */
  34760. this.isVector2Uniform = true;
  34761. this.boundary = 8;
  34762. this.itemSize = 2;
  34763. }
  34764. }
  34765. /**
  34766. * Represents a Vector3 uniform.
  34767. *
  34768. * @private
  34769. * @augments Uniform
  34770. */
  34771. class Vector3Uniform extends Uniform {
  34772. /**
  34773. * Constructs a new Number uniform.
  34774. *
  34775. * @param {string} name - The uniform's name.
  34776. * @param {Vector3} value - The uniform's value.
  34777. */
  34778. constructor( name, value = new Vector3() ) {
  34779. super( name, value );
  34780. /**
  34781. * This flag can be used for type testing.
  34782. *
  34783. * @type {boolean}
  34784. * @readonly
  34785. * @default true
  34786. */
  34787. this.isVector3Uniform = true;
  34788. this.boundary = 16;
  34789. this.itemSize = 3;
  34790. }
  34791. }
  34792. /**
  34793. * Represents a Vector4 uniform.
  34794. *
  34795. * @private
  34796. * @augments Uniform
  34797. */
  34798. class Vector4Uniform extends Uniform {
  34799. /**
  34800. * Constructs a new Number uniform.
  34801. *
  34802. * @param {string} name - The uniform's name.
  34803. * @param {Vector4} value - The uniform's value.
  34804. */
  34805. constructor( name, value = new Vector4() ) {
  34806. super( name, value );
  34807. /**
  34808. * This flag can be used for type testing.
  34809. *
  34810. * @type {boolean}
  34811. * @readonly
  34812. * @default true
  34813. */
  34814. this.isVector4Uniform = true;
  34815. this.boundary = 16;
  34816. this.itemSize = 4;
  34817. }
  34818. }
  34819. /**
  34820. * Represents a Color uniform.
  34821. *
  34822. * @private
  34823. * @augments Uniform
  34824. */
  34825. class ColorUniform extends Uniform {
  34826. /**
  34827. * Constructs a new Number uniform.
  34828. *
  34829. * @param {string} name - The uniform's name.
  34830. * @param {Color} value - The uniform's value.
  34831. */
  34832. constructor( name, value = new Color() ) {
  34833. super( name, value );
  34834. /**
  34835. * This flag can be used for type testing.
  34836. *
  34837. * @type {boolean}
  34838. * @readonly
  34839. * @default true
  34840. */
  34841. this.isColorUniform = true;
  34842. this.boundary = 16;
  34843. this.itemSize = 3;
  34844. }
  34845. }
  34846. /**
  34847. * Represents a Matrix2 uniform.
  34848. *
  34849. * @private
  34850. * @augments Uniform
  34851. */
  34852. class Matrix2Uniform extends Uniform {
  34853. /**
  34854. * Constructs a new Number uniform.
  34855. *
  34856. * @param {string} name - The uniform's name.
  34857. * @param {Matrix2} value - The uniform's value.
  34858. */
  34859. constructor( name, value = new Matrix2() ) {
  34860. super( name, value );
  34861. /**
  34862. * This flag can be used for type testing.
  34863. *
  34864. * @type {boolean}
  34865. * @readonly
  34866. * @default true
  34867. */
  34868. this.isMatrix2Uniform = true;
  34869. this.boundary = 8;
  34870. this.itemSize = 4;
  34871. }
  34872. }
  34873. /**
  34874. * Represents a Matrix3 uniform.
  34875. *
  34876. * @private
  34877. * @augments Uniform
  34878. */
  34879. class Matrix3Uniform extends Uniform {
  34880. /**
  34881. * Constructs a new Number uniform.
  34882. *
  34883. * @param {string} name - The uniform's name.
  34884. * @param {Matrix3} value - The uniform's value.
  34885. */
  34886. constructor( name, value = new Matrix3() ) {
  34887. super( name, value );
  34888. /**
  34889. * This flag can be used for type testing.
  34890. *
  34891. * @type {boolean}
  34892. * @readonly
  34893. * @default true
  34894. */
  34895. this.isMatrix3Uniform = true;
  34896. this.boundary = 48;
  34897. this.itemSize = 12;
  34898. }
  34899. }
  34900. /**
  34901. * Represents a Matrix4 uniform.
  34902. *
  34903. * @private
  34904. * @augments Uniform
  34905. */
  34906. class Matrix4Uniform extends Uniform {
  34907. /**
  34908. * Constructs a new Number uniform.
  34909. *
  34910. * @param {string} name - The uniform's name.
  34911. * @param {Matrix4} value - The uniform's value.
  34912. */
  34913. constructor( name, value = new Matrix4() ) {
  34914. super( name, value );
  34915. /**
  34916. * This flag can be used for type testing.
  34917. *
  34918. * @type {boolean}
  34919. * @readonly
  34920. * @default true
  34921. */
  34922. this.isMatrix4Uniform = true;
  34923. this.boundary = 64;
  34924. this.itemSize = 16;
  34925. }
  34926. }
  34927. /**
  34928. * A special form of Number uniform binding type.
  34929. * It's value is managed by a node object.
  34930. *
  34931. * @private
  34932. * @augments NumberUniform
  34933. */
  34934. class NumberNodeUniform extends NumberUniform {
  34935. /**
  34936. * Constructs a new node-based Number uniform.
  34937. *
  34938. * @param {NodeUniform} nodeUniform - The node uniform.
  34939. */
  34940. constructor( nodeUniform ) {
  34941. super( nodeUniform.name, nodeUniform.value );
  34942. /**
  34943. * The node uniform.
  34944. *
  34945. * @type {NodeUniform}
  34946. */
  34947. this.nodeUniform = nodeUniform;
  34948. }
  34949. /**
  34950. * Overwritten to return the value of the node uniform.
  34951. *
  34952. * @return {number} The value.
  34953. */
  34954. getValue() {
  34955. return this.nodeUniform.value;
  34956. }
  34957. /**
  34958. * Returns the node uniform data type.
  34959. *
  34960. * @return {string} The data type.
  34961. */
  34962. getType() {
  34963. return this.nodeUniform.type;
  34964. }
  34965. }
  34966. /**
  34967. * A special form of Vector2 uniform binding type.
  34968. * It's value is managed by a node object.
  34969. *
  34970. * @private
  34971. * @augments Vector2Uniform
  34972. */
  34973. class Vector2NodeUniform extends Vector2Uniform {
  34974. /**
  34975. * Constructs a new node-based Vector2 uniform.
  34976. *
  34977. * @param {NodeUniform} nodeUniform - The node uniform.
  34978. */
  34979. constructor( nodeUniform ) {
  34980. super( nodeUniform.name, nodeUniform.value );
  34981. /**
  34982. * The node uniform.
  34983. *
  34984. * @type {NodeUniform}
  34985. */
  34986. this.nodeUniform = nodeUniform;
  34987. }
  34988. /**
  34989. * Overwritten to return the value of the node uniform.
  34990. *
  34991. * @return {Vector2} The value.
  34992. */
  34993. getValue() {
  34994. return this.nodeUniform.value;
  34995. }
  34996. /**
  34997. * Returns the node uniform data type.
  34998. *
  34999. * @return {string} The data type.
  35000. */
  35001. getType() {
  35002. return this.nodeUniform.type;
  35003. }
  35004. }
  35005. /**
  35006. * A special form of Vector3 uniform binding type.
  35007. * It's value is managed by a node object.
  35008. *
  35009. * @private
  35010. * @augments Vector3Uniform
  35011. */
  35012. class Vector3NodeUniform extends Vector3Uniform {
  35013. /**
  35014. * Constructs a new node-based Vector3 uniform.
  35015. *
  35016. * @param {NodeUniform} nodeUniform - The node uniform.
  35017. */
  35018. constructor( nodeUniform ) {
  35019. super( nodeUniform.name, nodeUniform.value );
  35020. /**
  35021. * The node uniform.
  35022. *
  35023. * @type {NodeUniform}
  35024. */
  35025. this.nodeUniform = nodeUniform;
  35026. }
  35027. /**
  35028. * Overwritten to return the value of the node uniform.
  35029. *
  35030. * @return {Vector3} The value.
  35031. */
  35032. getValue() {
  35033. return this.nodeUniform.value;
  35034. }
  35035. /**
  35036. * Returns the node uniform data type.
  35037. *
  35038. * @return {string} The data type.
  35039. */
  35040. getType() {
  35041. return this.nodeUniform.type;
  35042. }
  35043. }
  35044. /**
  35045. * A special form of Vector4 uniform binding type.
  35046. * It's value is managed by a node object.
  35047. *
  35048. * @private
  35049. * @augments Vector4Uniform
  35050. */
  35051. class Vector4NodeUniform extends Vector4Uniform {
  35052. /**
  35053. * Constructs a new node-based Vector4 uniform.
  35054. *
  35055. * @param {NodeUniform} nodeUniform - The node uniform.
  35056. */
  35057. constructor( nodeUniform ) {
  35058. super( nodeUniform.name, nodeUniform.value );
  35059. /**
  35060. * The node uniform.
  35061. *
  35062. * @type {NodeUniform}
  35063. */
  35064. this.nodeUniform = nodeUniform;
  35065. }
  35066. /**
  35067. * Overwritten to return the value of the node uniform.
  35068. *
  35069. * @return {Vector4} The value.
  35070. */
  35071. getValue() {
  35072. return this.nodeUniform.value;
  35073. }
  35074. /**
  35075. * Returns the node uniform data type.
  35076. *
  35077. * @return {string} The data type.
  35078. */
  35079. getType() {
  35080. return this.nodeUniform.type;
  35081. }
  35082. }
  35083. /**
  35084. * A special form of Color uniform binding type.
  35085. * It's value is managed by a node object.
  35086. *
  35087. * @private
  35088. * @augments ColorUniform
  35089. */
  35090. class ColorNodeUniform extends ColorUniform {
  35091. /**
  35092. * Constructs a new node-based Color uniform.
  35093. *
  35094. * @param {NodeUniform} nodeUniform - The node uniform.
  35095. */
  35096. constructor( nodeUniform ) {
  35097. super( nodeUniform.name, nodeUniform.value );
  35098. /**
  35099. * The node uniform.
  35100. *
  35101. * @type {NodeUniform}
  35102. */
  35103. this.nodeUniform = nodeUniform;
  35104. }
  35105. /**
  35106. * Overwritten to return the value of the node uniform.
  35107. *
  35108. * @return {Color} The value.
  35109. */
  35110. getValue() {
  35111. return this.nodeUniform.value;
  35112. }
  35113. /**
  35114. * Returns the node uniform data type.
  35115. *
  35116. * @return {string} The data type.
  35117. */
  35118. getType() {
  35119. return this.nodeUniform.type;
  35120. }
  35121. }
  35122. /**
  35123. * A special form of Matrix2 uniform binding type.
  35124. * It's value is managed by a node object.
  35125. *
  35126. * @private
  35127. * @augments Matrix2Uniform
  35128. */
  35129. class Matrix2NodeUniform extends Matrix2Uniform {
  35130. /**
  35131. * Constructs a new node-based Matrix2 uniform.
  35132. *
  35133. * @param {NodeUniform} nodeUniform - The node uniform.
  35134. */
  35135. constructor( nodeUniform ) {
  35136. super( nodeUniform.name, nodeUniform.value );
  35137. /**
  35138. * The node uniform.
  35139. *
  35140. * @type {NodeUniform}
  35141. */
  35142. this.nodeUniform = nodeUniform;
  35143. }
  35144. /**
  35145. * Overwritten to return the value of the node uniform.
  35146. *
  35147. * @return {Matrix2} The value.
  35148. */
  35149. getValue() {
  35150. return this.nodeUniform.value;
  35151. }
  35152. /**
  35153. * Returns the node uniform data type.
  35154. *
  35155. * @return {string} The data type.
  35156. */
  35157. getType() {
  35158. return this.nodeUniform.type;
  35159. }
  35160. }
  35161. /**
  35162. * A special form of Matrix3 uniform binding type.
  35163. * It's value is managed by a node object.
  35164. *
  35165. * @private
  35166. * @augments Matrix3Uniform
  35167. */
  35168. class Matrix3NodeUniform extends Matrix3Uniform {
  35169. /**
  35170. * Constructs a new node-based Matrix3 uniform.
  35171. *
  35172. * @param {NodeUniform} nodeUniform - The node uniform.
  35173. */
  35174. constructor( nodeUniform ) {
  35175. super( nodeUniform.name, nodeUniform.value );
  35176. /**
  35177. * The node uniform.
  35178. *
  35179. * @type {NodeUniform}
  35180. */
  35181. this.nodeUniform = nodeUniform;
  35182. }
  35183. /**
  35184. * Overwritten to return the value of the node uniform.
  35185. *
  35186. * @return {Matrix3} The value.
  35187. */
  35188. getValue() {
  35189. return this.nodeUniform.value;
  35190. }
  35191. /**
  35192. * Returns the node uniform data type.
  35193. *
  35194. * @return {string} The data type.
  35195. */
  35196. getType() {
  35197. return this.nodeUniform.type;
  35198. }
  35199. }
  35200. /**
  35201. * A special form of Matrix4 uniform binding type.
  35202. * It's value is managed by a node object.
  35203. *
  35204. * @private
  35205. * @augments Matrix4Uniform
  35206. */
  35207. class Matrix4NodeUniform extends Matrix4Uniform {
  35208. /**
  35209. * Constructs a new node-based Matrix4 uniform.
  35210. *
  35211. * @param {NodeUniform} nodeUniform - The node uniform.
  35212. */
  35213. constructor( nodeUniform ) {
  35214. super( nodeUniform.name, nodeUniform.value );
  35215. /**
  35216. * The node uniform.
  35217. *
  35218. * @type {NodeUniform}
  35219. */
  35220. this.nodeUniform = nodeUniform;
  35221. }
  35222. /**
  35223. * Overwritten to return the value of the node uniform.
  35224. *
  35225. * @return {Matrix4} The value.
  35226. */
  35227. getValue() {
  35228. return this.nodeUniform.value;
  35229. }
  35230. /**
  35231. * Returns the node uniform data type.
  35232. *
  35233. * @return {string} The data type.
  35234. */
  35235. getType() {
  35236. return this.nodeUniform.type;
  35237. }
  35238. }
  35239. let _id$5 = 0;
  35240. const sharedNodeData = new WeakMap();
  35241. const rendererCache = new WeakMap();
  35242. const typeFromArray = new Map( [
  35243. [ Int8Array, 'int' ],
  35244. [ Int16Array, 'int' ],
  35245. [ Int32Array, 'int' ],
  35246. [ Uint8Array, 'uint' ],
  35247. [ Uint16Array, 'uint' ],
  35248. [ Uint32Array, 'uint' ],
  35249. [ Float32Array, 'float' ]
  35250. ] );
  35251. const toFloat = ( value ) => {
  35252. if ( /e/g.test( value ) ) {
  35253. return String( value ).replace( /\+/g, '' );
  35254. } else {
  35255. value = Number( value );
  35256. return value + ( value % 1 ? '' : '.0' );
  35257. }
  35258. };
  35259. /**
  35260. * Base class for builders which generate a shader program based
  35261. * on a 3D object and its node material definition.
  35262. */
  35263. class NodeBuilder {
  35264. /**
  35265. * Constructs a new node builder.
  35266. *
  35267. * @param {Object3D} object - The 3D object.
  35268. * @param {Renderer} renderer - The current renderer.
  35269. * @param {NodeParser} parser - A reference to a node parser.
  35270. */
  35271. constructor( object, renderer, parser ) {
  35272. /**
  35273. * The 3D object.
  35274. *
  35275. * @type {Object3D}
  35276. */
  35277. this.object = object;
  35278. /**
  35279. * The material of the 3D object.
  35280. *
  35281. * @type {?Material}
  35282. */
  35283. this.material = ( object && object.material ) || null;
  35284. /**
  35285. * The geometry of the 3D object.
  35286. *
  35287. * @type {?BufferGeometry}
  35288. */
  35289. this.geometry = ( object && object.geometry ) || null;
  35290. /**
  35291. * The current renderer.
  35292. *
  35293. * @type {Renderer}
  35294. */
  35295. this.renderer = renderer;
  35296. /**
  35297. * A reference to a node parser.
  35298. *
  35299. * @type {NodeParser}
  35300. */
  35301. this.parser = parser;
  35302. /**
  35303. * The scene the 3D object belongs to.
  35304. *
  35305. * @type {?Scene}
  35306. * @default null
  35307. */
  35308. this.scene = null;
  35309. /**
  35310. * The camera the 3D object is rendered with.
  35311. *
  35312. * @type {?Camera}
  35313. * @default null
  35314. */
  35315. this.camera = null;
  35316. /**
  35317. * A list of all nodes the builder is processing
  35318. * for this 3D object.
  35319. *
  35320. * @type {Array<Node>}
  35321. */
  35322. this.nodes = [];
  35323. /**
  35324. * A list of all sequential nodes.
  35325. *
  35326. * @type {Array<Node>}
  35327. */
  35328. this.sequentialNodes = [];
  35329. /**
  35330. * A list of all nodes which {@link Node#update} method should be executed.
  35331. *
  35332. * @type {Array<Node>}
  35333. */
  35334. this.updateNodes = [];
  35335. /**
  35336. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  35337. *
  35338. * @type {Array<Node>}
  35339. */
  35340. this.updateBeforeNodes = [];
  35341. /**
  35342. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  35343. *
  35344. * @type {Array<Node>}
  35345. */
  35346. this.updateAfterNodes = [];
  35347. /**
  35348. * A dictionary that assigns each node to a unique hash.
  35349. *
  35350. * @type {Object<number,Node>}
  35351. */
  35352. this.hashNodes = {};
  35353. /**
  35354. * A reference to a node material observer.
  35355. *
  35356. * @type {?NodeMaterialObserver}
  35357. * @default null
  35358. */
  35359. this.observer = null;
  35360. /**
  35361. * A reference to the current lights node.
  35362. *
  35363. * @type {?LightsNode}
  35364. * @default null
  35365. */
  35366. this.lightsNode = null;
  35367. /**
  35368. * A reference to the current environment node.
  35369. *
  35370. * @type {?Node}
  35371. * @default null
  35372. */
  35373. this.environmentNode = null;
  35374. /**
  35375. * A reference to the current fog node.
  35376. *
  35377. * @type {?Node}
  35378. * @default null
  35379. */
  35380. this.fogNode = null;
  35381. /**
  35382. * The current clipping context.
  35383. *
  35384. * @type {?ClippingContext}
  35385. */
  35386. this.clippingContext = null;
  35387. /**
  35388. * The generated vertex shader.
  35389. *
  35390. * @type {?string}
  35391. */
  35392. this.vertexShader = null;
  35393. /**
  35394. * The generated fragment shader.
  35395. *
  35396. * @type {?string}
  35397. */
  35398. this.fragmentShader = null;
  35399. /**
  35400. * The generated compute shader.
  35401. *
  35402. * @type {?string}
  35403. */
  35404. this.computeShader = null;
  35405. /**
  35406. * Nodes used in the primary flow of code generation.
  35407. *
  35408. * @type {Object<string,Array<Node>>}
  35409. */
  35410. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  35411. /**
  35412. * Nodes code from `.flowNodes`.
  35413. *
  35414. * @type {Object<string,string>}
  35415. */
  35416. this.flowCode = { vertex: '', fragment: '', compute: '' };
  35417. /**
  35418. * This dictionary holds the node uniforms of the builder.
  35419. * The uniforms are maintained in an array for each shader stage.
  35420. *
  35421. * @type {Object}
  35422. */
  35423. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  35424. /**
  35425. * This dictionary holds the output structs of the builder.
  35426. * The structs are maintained in an array for each shader stage.
  35427. *
  35428. * @type {Object}
  35429. */
  35430. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  35431. /**
  35432. * This dictionary holds the types of the builder.
  35433. *
  35434. * @type {Object}
  35435. */
  35436. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  35437. /**
  35438. * This dictionary holds the bindings for each shader stage.
  35439. *
  35440. * @type {Object}
  35441. */
  35442. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  35443. /**
  35444. * This dictionary maintains the binding indices per bind group.
  35445. *
  35446. * @type {Object}
  35447. */
  35448. this.bindingsIndexes = {};
  35449. /**
  35450. * Reference to the array of bind groups.
  35451. *
  35452. * @type {?Array<BindGroup>}
  35453. */
  35454. this.bindGroups = null;
  35455. /**
  35456. * This array holds the node attributes of this builder
  35457. * created via {@link AttributeNode}.
  35458. *
  35459. * @type {Array<NodeAttribute>}
  35460. */
  35461. this.attributes = [];
  35462. /**
  35463. * This array holds the node attributes of this builder
  35464. * created via {@link BufferAttributeNode}.
  35465. *
  35466. * @type {Array<NodeAttribute>}
  35467. */
  35468. this.bufferAttributes = [];
  35469. /**
  35470. * This array holds the node varyings of this builder.
  35471. *
  35472. * @type {Array<NodeVarying>}
  35473. */
  35474. this.varyings = [];
  35475. /**
  35476. * This dictionary holds the (native) node codes of this builder.
  35477. * The codes are maintained in an array for each shader stage.
  35478. *
  35479. * @type {Object<string,Array<NodeCode>>}
  35480. */
  35481. this.codes = {};
  35482. /**
  35483. * This dictionary holds the node variables of this builder.
  35484. * The variables are maintained in an array for each shader stage.
  35485. * This dictionary is also used to count the number of variables
  35486. * according to their type (const, vars).
  35487. *
  35488. * @type {Object<string,Array<NodeVar>|number>}
  35489. */
  35490. this.vars = {};
  35491. /**
  35492. * This dictionary holds the declarations for each shader stage.
  35493. *
  35494. * @type {Object}
  35495. */
  35496. this.declarations = {};
  35497. /**
  35498. * Current code flow.
  35499. * All code generated in this stack will be stored in `.flow`.
  35500. *
  35501. * @type {{code: string}}
  35502. */
  35503. this.flow = { code: '' };
  35504. /**
  35505. * A chain of nodes.
  35506. * Used to check recursive calls in node-graph.
  35507. *
  35508. * @type {Array<Node>}
  35509. */
  35510. this.chaining = [];
  35511. /**
  35512. * The current stack.
  35513. * This reflects the current process in the code block hierarchy,
  35514. * it is useful to know if the current process is inside a conditional for example.
  35515. *
  35516. * @type {StackNode}
  35517. */
  35518. this.stack = stack();
  35519. /**
  35520. * List of stack nodes.
  35521. * The current stack hierarchy is stored in an array.
  35522. *
  35523. * @type {Array<StackNode>}
  35524. */
  35525. this.stacks = [];
  35526. /**
  35527. * A tab value. Used for shader string generation.
  35528. *
  35529. * @type {string}
  35530. * @default '\t'
  35531. */
  35532. this.tab = '\t';
  35533. /**
  35534. * Reference to the current function node.
  35535. *
  35536. * @type {?FunctionNode}
  35537. * @default null
  35538. */
  35539. this.currentFunctionNode = null;
  35540. /**
  35541. * The builder's context.
  35542. *
  35543. * @type {Object}
  35544. */
  35545. this.context = {
  35546. material: this.material
  35547. };
  35548. /**
  35549. * The builder's cache.
  35550. *
  35551. * @type {NodeCache}
  35552. */
  35553. this.cache = new NodeCache();
  35554. /**
  35555. * Since the {@link NodeBuilder#cache} might be temporarily
  35556. * overwritten by other caches, this member retains the reference
  35557. * to the builder's own cache.
  35558. *
  35559. * @type {NodeCache}
  35560. * @default this.cache
  35561. */
  35562. this.globalCache = this.cache;
  35563. this.flowsData = new WeakMap();
  35564. /**
  35565. * The current shader stage.
  35566. *
  35567. * @type {?('vertex'|'fragment'|'compute'|'any')}
  35568. */
  35569. this.shaderStage = null;
  35570. /**
  35571. * The current build stage.
  35572. *
  35573. * @type {?('setup'|'analyze'|'generate')}
  35574. */
  35575. this.buildStage = null;
  35576. /**
  35577. * The sub-build layers.
  35578. *
  35579. * @type {Array<SubBuildNode>}
  35580. * @default []
  35581. */
  35582. this.subBuildLayers = [];
  35583. /**
  35584. * The active stack nodes.
  35585. *
  35586. * @type {Array<StackNode>}
  35587. */
  35588. this.activeStacks = [];
  35589. /**
  35590. * The current sub-build TSL function(Fn).
  35591. *
  35592. * @type {?string}
  35593. * @default null
  35594. */
  35595. this.subBuildFn = null;
  35596. /**
  35597. * The current TSL function(Fn) call node.
  35598. *
  35599. * @type {?Node}
  35600. * @default null
  35601. */
  35602. this.fnCall = null;
  35603. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  35604. }
  35605. /**
  35606. * Whether the material is opaque or not.
  35607. *
  35608. * @return {boolean} Whether the material is opaque or not.
  35609. */
  35610. isOpaque() {
  35611. const material = this.material;
  35612. return material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false;
  35613. }
  35614. /**
  35615. * Returns the bind groups of the current renderer.
  35616. *
  35617. * @return {ChainMap} The cache.
  35618. */
  35619. getBindGroupsCache() {
  35620. let bindGroupsCache = rendererCache.get( this.renderer );
  35621. if ( bindGroupsCache === undefined ) {
  35622. bindGroupsCache = new ChainMap();
  35623. rendererCache.set( this.renderer, bindGroupsCache );
  35624. }
  35625. return bindGroupsCache;
  35626. }
  35627. /**
  35628. * Factory method for creating an instance of {@link RenderTarget} with the given
  35629. * dimensions and options.
  35630. *
  35631. * @param {number} width - The width of the render target.
  35632. * @param {number} height - The height of the render target.
  35633. * @param {Object} options - The options of the render target.
  35634. * @return {RenderTarget} The render target.
  35635. */
  35636. createRenderTarget( width, height, options ) {
  35637. return new RenderTarget( width, height, options );
  35638. }
  35639. /**
  35640. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  35641. * dimensions and options.
  35642. *
  35643. * @param {number} size - The size of the cube render target.
  35644. * @param {Object} options - The options of the cube render target.
  35645. * @return {CubeRenderTarget} The cube render target.
  35646. */
  35647. createCubeRenderTarget( size, options ) {
  35648. return new CubeRenderTarget( size, options );
  35649. }
  35650. /**
  35651. * Whether the given node is included in the internal array of nodes or not.
  35652. *
  35653. * @param {Node} node - The node to test.
  35654. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  35655. */
  35656. includes( node ) {
  35657. return this.nodes.includes( node );
  35658. }
  35659. /**
  35660. * Returns the output struct name which is required by
  35661. * {@link OutputStructNode}.
  35662. *
  35663. * @abstract
  35664. * @return {string} The name of the output struct.
  35665. */
  35666. getOutputStructName() {}
  35667. /**
  35668. * Returns a bind group for the given group name and binding.
  35669. *
  35670. * @private
  35671. * @param {string} groupName - The group name.
  35672. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  35673. * @return {BindGroup} The bind group
  35674. */
  35675. _getBindGroup( groupName, bindings ) {
  35676. const bindGroupsCache = this.getBindGroupsCache();
  35677. //
  35678. const bindingsArray = [];
  35679. let sharedGroup = true;
  35680. for ( const binding of bindings ) {
  35681. bindingsArray.push( binding );
  35682. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  35683. }
  35684. //
  35685. let bindGroup;
  35686. if ( sharedGroup ) {
  35687. bindGroup = bindGroupsCache.get( bindingsArray );
  35688. if ( bindGroup === undefined ) {
  35689. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35690. bindGroupsCache.set( bindingsArray, bindGroup );
  35691. }
  35692. } else {
  35693. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35694. }
  35695. return bindGroup;
  35696. }
  35697. /**
  35698. * Returns an array of node uniform groups for the given group name and shader stage.
  35699. *
  35700. * @param {string} groupName - The group name.
  35701. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35702. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  35703. */
  35704. getBindGroupArray( groupName, shaderStage ) {
  35705. const bindings = this.bindings[ shaderStage ];
  35706. let bindGroup = bindings[ groupName ];
  35707. if ( bindGroup === undefined ) {
  35708. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  35709. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  35710. }
  35711. bindings[ groupName ] = bindGroup = [];
  35712. }
  35713. return bindGroup;
  35714. }
  35715. /**
  35716. * Returns a list bindings of all shader stages separated by groups.
  35717. *
  35718. * @return {Array<BindGroup>} The list of bindings.
  35719. */
  35720. getBindings() {
  35721. let bindingsGroups = this.bindGroups;
  35722. if ( bindingsGroups === null ) {
  35723. const groups = {};
  35724. const bindings = this.bindings;
  35725. for ( const shaderStage of shaderStages ) {
  35726. for ( const groupName in bindings[ shaderStage ] ) {
  35727. const uniforms = bindings[ shaderStage ][ groupName ];
  35728. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  35729. groupUniforms.push( ...uniforms );
  35730. }
  35731. }
  35732. bindingsGroups = [];
  35733. for ( const groupName in groups ) {
  35734. const group = groups[ groupName ];
  35735. const bindingsGroup = this._getBindGroup( groupName, group );
  35736. bindingsGroups.push( bindingsGroup );
  35737. }
  35738. this.bindGroups = bindingsGroups;
  35739. }
  35740. return bindingsGroups;
  35741. }
  35742. /**
  35743. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  35744. */
  35745. sortBindingGroups() {
  35746. const bindingsGroups = this.getBindings();
  35747. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  35748. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  35749. const bindingGroup = bindingsGroups[ i ];
  35750. this.bindingsIndexes[ bindingGroup.name ].group = i;
  35751. bindingGroup.index = i;
  35752. }
  35753. }
  35754. /**
  35755. * The builder maintains each node in a hash-based dictionary.
  35756. * This method sets the given node (value) with the given hash (key) into this dictionary.
  35757. *
  35758. * @param {Node} node - The node to add.
  35759. * @param {number} hash - The hash of the node.
  35760. */
  35761. setHashNode( node, hash ) {
  35762. this.hashNodes[ hash ] = node;
  35763. }
  35764. /**
  35765. * Adds a node to this builder.
  35766. *
  35767. * @param {Node} node - The node to add.
  35768. */
  35769. addNode( node ) {
  35770. if ( this.nodes.includes( node ) === false ) {
  35771. this.nodes.push( node );
  35772. this.setHashNode( node, node.getHash( this ) );
  35773. }
  35774. }
  35775. /**
  35776. * It is used to add Nodes that will be used as FRAME and RENDER events,
  35777. * and need to follow a certain sequence in the calls to work correctly.
  35778. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  35779. *
  35780. * @param {Node} node - The node to add.
  35781. */
  35782. addSequentialNode( node ) {
  35783. if ( this.sequentialNodes.includes( node ) === false ) {
  35784. this.sequentialNodes.push( node );
  35785. }
  35786. }
  35787. /**
  35788. * Checks the update types of nodes
  35789. */
  35790. buildUpdateNodes() {
  35791. for ( const node of this.nodes ) {
  35792. const updateType = node.getUpdateType();
  35793. if ( updateType !== NodeUpdateType.NONE ) {
  35794. this.updateNodes.push( node );
  35795. }
  35796. }
  35797. for ( const node of this.sequentialNodes ) {
  35798. const updateBeforeType = node.getUpdateBeforeType();
  35799. const updateAfterType = node.getUpdateAfterType();
  35800. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  35801. this.updateBeforeNodes.push( node );
  35802. }
  35803. if ( updateAfterType !== NodeUpdateType.NONE ) {
  35804. this.updateAfterNodes.push( node );
  35805. }
  35806. }
  35807. }
  35808. /**
  35809. * A reference the current node which is the
  35810. * last node in the chain of nodes.
  35811. *
  35812. * @type {Node}
  35813. */
  35814. get currentNode() {
  35815. return this.chaining[ this.chaining.length - 1 ];
  35816. }
  35817. /**
  35818. * Whether the given texture is filtered or not.
  35819. *
  35820. * @param {Texture} texture - The texture to check.
  35821. * @return {boolean} Whether the given texture is filtered or not.
  35822. */
  35823. isFilteredTexture( texture ) {
  35824. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  35825. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  35826. }
  35827. /**
  35828. * Adds the given node to the internal node chain.
  35829. * This is used to check recursive calls in node-graph.
  35830. *
  35831. * @param {Node} node - The node to add.
  35832. */
  35833. addChain( node ) {
  35834. /*
  35835. if ( this.chaining.indexOf( node ) !== - 1 ) {
  35836. warn( 'Recursive node: ', node );
  35837. }
  35838. */
  35839. this.chaining.push( node );
  35840. }
  35841. /**
  35842. * Removes the given node from the internal node chain.
  35843. *
  35844. * @param {Node} node - The node to remove.
  35845. */
  35846. removeChain( node ) {
  35847. const lastChain = this.chaining.pop();
  35848. if ( lastChain !== node ) {
  35849. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  35850. }
  35851. }
  35852. /**
  35853. * Returns the native shader method name for a given generic name. E.g.
  35854. * the method name `textureDimensions` matches the WGSL name but must be
  35855. * resolved to `textureSize` in GLSL.
  35856. *
  35857. * @abstract
  35858. * @param {string} method - The method name to resolve.
  35859. * @return {string} The resolved method name.
  35860. */
  35861. getMethod( method ) {
  35862. return method;
  35863. }
  35864. /**
  35865. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  35866. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  35867. *
  35868. * @abstract
  35869. * @param {string} condSnippet - The condition determining which expression gets resolved.
  35870. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  35871. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  35872. * @return {string} The resolved method name.
  35873. */
  35874. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  35875. return null;
  35876. }
  35877. /**
  35878. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  35879. *
  35880. * @param {number} hash - The hash of the node.
  35881. * @return {Node} The found node.
  35882. */
  35883. getNodeFromHash( hash ) {
  35884. return this.hashNodes[ hash ];
  35885. }
  35886. /**
  35887. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  35888. *
  35889. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  35890. * @param {Node} node - The node to add.
  35891. * @return {Node} The node.
  35892. */
  35893. addFlow( shaderStage, node ) {
  35894. this.flowNodes[ shaderStage ].push( node );
  35895. return node;
  35896. }
  35897. /**
  35898. * Sets builder's context.
  35899. *
  35900. * @param {Object} context - The context to set.
  35901. */
  35902. setContext( context ) {
  35903. this.context = context;
  35904. }
  35905. /**
  35906. * Returns the builder's current context.
  35907. *
  35908. * @return {Object} The builder's current context.
  35909. */
  35910. getContext() {
  35911. return this.context;
  35912. }
  35913. /**
  35914. * Adds context data to the builder's current context.
  35915. *
  35916. * @param {Object} context - The context to add.
  35917. * @return {Object} The previous context.
  35918. */
  35919. addContext( context ) {
  35920. const previousContext = this.getContext();
  35921. this.setContext( { ...this.context, ...context } );
  35922. return previousContext;
  35923. }
  35924. /**
  35925. * Gets a context used in shader construction that can be shared across different materials.
  35926. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  35927. *
  35928. * @return {Object} The builder's current context without material.
  35929. */
  35930. getSharedContext() {
  35931. ({ ...this.context });
  35932. return this.context;
  35933. }
  35934. /**
  35935. * Sets builder's cache.
  35936. *
  35937. * @param {NodeCache} cache - The cache to set.
  35938. */
  35939. setCache( cache ) {
  35940. this.cache = cache;
  35941. }
  35942. /**
  35943. * Returns the builder's current cache.
  35944. *
  35945. * @return {NodeCache} The builder's current cache.
  35946. */
  35947. getCache() {
  35948. return this.cache;
  35949. }
  35950. /**
  35951. * Returns a cache for the given node.
  35952. *
  35953. * @param {Node} node - The node.
  35954. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  35955. * @return {NodeCache} The cache.
  35956. */
  35957. getCacheFromNode( node, parent = true ) {
  35958. const data = this.getDataFromNode( node );
  35959. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  35960. return data.cache;
  35961. }
  35962. /**
  35963. * Whether the requested feature is available or not.
  35964. *
  35965. * @abstract
  35966. * @param {string} name - The requested feature.
  35967. * @return {boolean} Whether the requested feature is supported or not.
  35968. */
  35969. isAvailable( /*name*/ ) {
  35970. return false;
  35971. }
  35972. /**
  35973. * Returns the vertexIndex input variable as a native shader string.
  35974. *
  35975. * @abstract
  35976. * @return {string} The instanceIndex shader string.
  35977. */
  35978. getVertexIndex() {
  35979. warn( 'Abstract function.' );
  35980. }
  35981. /**
  35982. * Contextually returns either the vertex stage instance index builtin
  35983. * or the linearized index of an compute invocation within a grid of workgroups.
  35984. *
  35985. * @abstract
  35986. * @return {string} The instanceIndex shader string.
  35987. */
  35988. getInstanceIndex() {
  35989. warn( 'Abstract function.' );
  35990. }
  35991. /**
  35992. * Returns the drawIndex input variable as a native shader string.
  35993. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  35994. *
  35995. * @abstract
  35996. * @return {?string} The drawIndex shader string.
  35997. */
  35998. getDrawIndex() {
  35999. warn( 'Abstract function.' );
  36000. }
  36001. /**
  36002. * Returns the frontFacing input variable as a native shader string.
  36003. *
  36004. * @abstract
  36005. * @return {string} The frontFacing shader string.
  36006. */
  36007. getFrontFacing() {
  36008. warn( 'Abstract function.' );
  36009. }
  36010. /**
  36011. * Returns the fragCoord input variable as a native shader string.
  36012. *
  36013. * @abstract
  36014. * @return {string} The fragCoord shader string.
  36015. */
  36016. getFragCoord() {
  36017. warn( 'Abstract function.' );
  36018. }
  36019. /**
  36020. * Whether to flip texture data along its vertical axis or not. WebGL needs
  36021. * this method evaluate to `true`, WebGPU to `false`.
  36022. *
  36023. * @abstract
  36024. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  36025. */
  36026. isFlipY() {
  36027. return false;
  36028. }
  36029. /**
  36030. * Calling this method increases the usage count for the given node by one.
  36031. *
  36032. * @param {Node} node - The node to increase the usage count for.
  36033. * @return {number} The updated usage count.
  36034. */
  36035. increaseUsage( node ) {
  36036. const nodeData = this.getDataFromNode( node );
  36037. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  36038. return nodeData.usageCount;
  36039. }
  36040. /**
  36041. * Generates a texture sample shader string for the given texture data.
  36042. *
  36043. * @abstract
  36044. * @param {Texture} texture - The texture.
  36045. * @param {string} textureProperty - The texture property name.
  36046. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  36047. * @return {string} The generated shader string.
  36048. */
  36049. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  36050. warn( 'Abstract function.' );
  36051. }
  36052. /**
  36053. * Generates a texture LOD shader string for the given texture data.
  36054. *
  36055. * @abstract
  36056. * @param {Texture} texture - The texture.
  36057. * @param {string} textureProperty - The texture property name.
  36058. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  36059. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  36060. * @param {string} levelSnippet - Snippet defining the mip level.
  36061. * @return {string} The generated shader string.
  36062. */
  36063. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  36064. warn( 'Abstract function.' );
  36065. }
  36066. /**
  36067. * Generates the array declaration string.
  36068. *
  36069. * @param {string} type - The type.
  36070. * @param {?number} [count] - The count.
  36071. * @return {string} The generated value as a shader string.
  36072. */
  36073. generateArrayDeclaration( type, count ) {
  36074. return this.getType( type ) + '[ ' + count + ' ]';
  36075. }
  36076. /**
  36077. * Generates the array shader string for the given type and value.
  36078. *
  36079. * @param {string} type - The type.
  36080. * @param {?number} [count] - The count.
  36081. * @param {?Array<Node>} [values=null] - The default values.
  36082. * @return {string} The generated value as a shader string.
  36083. */
  36084. generateArray( type, count, values = null ) {
  36085. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  36086. for ( let i = 0; i < count; i ++ ) {
  36087. const value = values ? values[ i ] : null;
  36088. if ( value !== null ) {
  36089. snippet += value.build( this, type );
  36090. } else {
  36091. snippet += this.generateConst( type );
  36092. }
  36093. if ( i < count - 1 ) snippet += ', ';
  36094. }
  36095. snippet += ' )';
  36096. return snippet;
  36097. }
  36098. /**
  36099. * Generates the struct shader string.
  36100. *
  36101. * @param {string} type - The type.
  36102. * @param {Array<Object>} [membersLayout] - The count.
  36103. * @param {?Array<Node>} [values=null] - The default values.
  36104. * @return {string} The generated value as a shader string.
  36105. */
  36106. generateStruct( type, membersLayout, values = null ) {
  36107. const snippets = [];
  36108. for ( const member of membersLayout ) {
  36109. const { name, type } = member;
  36110. if ( values && values[ name ] && values[ name ].isNode ) {
  36111. snippets.push( values[ name ].build( this, type ) );
  36112. } else {
  36113. snippets.push( this.generateConst( type ) );
  36114. }
  36115. }
  36116. return type + '( ' + snippets.join( ', ' ) + ' )';
  36117. }
  36118. /**
  36119. * Generates the shader string for the given type and value.
  36120. *
  36121. * @param {string} type - The type.
  36122. * @param {?any} [value=null] - The value.
  36123. * @return {string} The generated value as a shader string.
  36124. */
  36125. generateConst( type, value = null ) {
  36126. if ( value === null ) {
  36127. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  36128. else if ( type === 'bool' ) value = false;
  36129. else if ( type === 'color' ) value = new Color();
  36130. else if ( type === 'vec2' || type === 'uvec2' || type === 'ivec2' ) value = new Vector2();
  36131. else if ( type === 'vec3' || type === 'uvec3' || type === 'ivec3' ) value = new Vector3();
  36132. else if ( type === 'vec4' || type === 'uvec4' || type === 'ivec4' ) value = new Vector4();
  36133. }
  36134. if ( type === 'float' ) return toFloat( value );
  36135. if ( type === 'int' ) return `${ Math.round( value ) }`;
  36136. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  36137. if ( type === 'bool' ) return value ? 'true' : 'false';
  36138. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  36139. const typeLength = this.getTypeLength( type );
  36140. const componentType = this.getComponentType( type );
  36141. const generateConst = value => this.generateConst( componentType, value );
  36142. if ( typeLength === 2 ) {
  36143. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  36144. } else if ( typeLength === 3 ) {
  36145. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  36146. } else if ( typeLength === 4 && type !== 'mat2' ) {
  36147. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  36148. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  36149. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  36150. } else if ( typeLength > 4 ) {
  36151. return `${ this.getType( type ) }()`;
  36152. }
  36153. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  36154. }
  36155. /**
  36156. * It might be necessary to convert certain data types to different ones
  36157. * so this method can be used to hide the conversion.
  36158. *
  36159. * @param {string} type - The type.
  36160. * @return {string} The updated type.
  36161. */
  36162. getType( type ) {
  36163. if ( type === 'color' ) return 'vec3';
  36164. return type;
  36165. }
  36166. /**
  36167. * Whether the given attribute name is defined in the geometry or not.
  36168. *
  36169. * @param {string} name - The attribute name.
  36170. * @return {boolean} Whether the given attribute name is defined in the geometry.
  36171. */
  36172. hasGeometryAttribute( name ) {
  36173. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  36174. }
  36175. /**
  36176. * Returns a node attribute for the given name and type.
  36177. *
  36178. * @param {string} name - The attribute's name.
  36179. * @param {string} type - The attribute's type.
  36180. * @return {NodeAttribute} The node attribute.
  36181. */
  36182. getAttribute( name, type ) {
  36183. const attributes = this.attributes;
  36184. // find attribute
  36185. for ( const attribute of attributes ) {
  36186. if ( attribute.name === name ) {
  36187. return attribute;
  36188. }
  36189. }
  36190. // create a new if no exist
  36191. const attribute = new NodeAttribute( name, type );
  36192. this.registerDeclaration( attribute );
  36193. attributes.push( attribute );
  36194. return attribute;
  36195. }
  36196. /**
  36197. * Returns for the given node and shader stage the property name for the shader.
  36198. *
  36199. * @param {Node} node - The node.
  36200. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36201. * @return {string} The property name.
  36202. */
  36203. getPropertyName( node/*, shaderStage*/ ) {
  36204. return node.name;
  36205. }
  36206. /**
  36207. * Whether the given type is a vector type or not.
  36208. *
  36209. * @param {string} type - The type to check.
  36210. * @return {boolean} Whether the given type is a vector type or not.
  36211. */
  36212. isVector( type ) {
  36213. return /vec\d/.test( type );
  36214. }
  36215. /**
  36216. * Whether the given type is a matrix type or not.
  36217. *
  36218. * @param {string} type - The type to check.
  36219. * @return {boolean} Whether the given type is a matrix type or not.
  36220. */
  36221. isMatrix( type ) {
  36222. return /mat\d/.test( type );
  36223. }
  36224. /**
  36225. * Whether the given type is a reference type or not.
  36226. *
  36227. * @param {string} type - The type to check.
  36228. * @return {boolean} Whether the given type is a reference type or not.
  36229. */
  36230. isReference( type ) {
  36231. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  36232. }
  36233. /**
  36234. * Checks if the given texture requires a manual conversion to the working color space.
  36235. *
  36236. * @abstract
  36237. * @param {Texture} texture - The texture to check.
  36238. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  36239. */
  36240. needsToWorkingColorSpace( /*texture*/ ) {
  36241. return false;
  36242. }
  36243. /**
  36244. * Returns the component type of a given texture.
  36245. *
  36246. * @param {Texture} texture - The texture.
  36247. * @return {string} The component type.
  36248. */
  36249. getComponentTypeFromTexture( texture ) {
  36250. const type = texture.type;
  36251. if ( texture.isDataTexture ) {
  36252. if ( type === IntType ) return 'int';
  36253. if ( type === UnsignedIntType ) return 'uint';
  36254. }
  36255. return 'float';
  36256. }
  36257. /**
  36258. * Returns the element type for a given type.
  36259. *
  36260. * @param {string} type - The type.
  36261. * @return {string} The element type.
  36262. */
  36263. getElementType( type ) {
  36264. if ( type === 'mat2' ) return 'vec2';
  36265. if ( type === 'mat3' ) return 'vec3';
  36266. if ( type === 'mat4' ) return 'vec4';
  36267. return this.getComponentType( type );
  36268. }
  36269. /**
  36270. * Returns the component type for a given type.
  36271. *
  36272. * @param {string} type - The type.
  36273. * @return {string} The component type.
  36274. */
  36275. getComponentType( type ) {
  36276. type = this.getVectorType( type );
  36277. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  36278. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  36279. if ( componentType === null ) return null;
  36280. if ( componentType[ 1 ] === 'b' ) return 'bool';
  36281. if ( componentType[ 1 ] === 'i' ) return 'int';
  36282. if ( componentType[ 1 ] === 'u' ) return 'uint';
  36283. return 'float';
  36284. }
  36285. /**
  36286. * Returns the vector type for a given type.
  36287. *
  36288. * @param {string} type - The type.
  36289. * @return {string} The vector type.
  36290. */
  36291. getVectorType( type ) {
  36292. if ( type === 'color' ) return 'vec3';
  36293. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  36294. return type;
  36295. }
  36296. /**
  36297. * Returns the data type for the given the length and component type.
  36298. *
  36299. * @param {number} length - The length.
  36300. * @param {string} [componentType='float'] - The component type.
  36301. * @return {string} The type.
  36302. */
  36303. getTypeFromLength( length, componentType = 'float' ) {
  36304. if ( length === 1 ) return componentType;
  36305. let baseType = getTypeFromLength( length );
  36306. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  36307. // fix edge case for mat2x2 being same size as vec4
  36308. if ( /mat2/.test( componentType ) === true ) {
  36309. baseType = baseType.replace( 'vec', 'mat' );
  36310. }
  36311. return prefix + baseType;
  36312. }
  36313. /**
  36314. * Returns the type for a given typed array.
  36315. *
  36316. * @param {TypedArray} array - The typed array.
  36317. * @return {string} The type.
  36318. */
  36319. getTypeFromArray( array ) {
  36320. return typeFromArray.get( array.constructor );
  36321. }
  36322. /**
  36323. * Returns the type is an integer type.
  36324. *
  36325. * @param {string} type - The type.
  36326. * @return {boolean} Whether the type is an integer type or not.
  36327. */
  36328. isInteger( type ) {
  36329. return /int|uint|(i|u)vec/.test( type );
  36330. }
  36331. /**
  36332. * Returns the type for a given buffer attribute.
  36333. *
  36334. * @param {BufferAttribute} attribute - The buffer attribute.
  36335. * @return {string} The type.
  36336. */
  36337. getTypeFromAttribute( attribute ) {
  36338. let dataAttribute = attribute;
  36339. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36340. const array = dataAttribute.array;
  36341. const itemSize = attribute.itemSize;
  36342. const normalized = attribute.normalized;
  36343. let arrayType;
  36344. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  36345. arrayType = this.getTypeFromArray( array );
  36346. }
  36347. return this.getTypeFromLength( itemSize, arrayType );
  36348. }
  36349. /**
  36350. * Returns the length for the given data type.
  36351. *
  36352. * @param {string} type - The data type.
  36353. * @return {number} The length.
  36354. */
  36355. getTypeLength( type ) {
  36356. const vecType = this.getVectorType( type );
  36357. const vecNum = /vec([2-4])/.exec( vecType );
  36358. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  36359. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  36360. if ( /mat2/.test( type ) === true ) return 4;
  36361. if ( /mat3/.test( type ) === true ) return 9;
  36362. if ( /mat4/.test( type ) === true ) return 16;
  36363. return 0;
  36364. }
  36365. /**
  36366. * Returns the vector type for a given matrix type.
  36367. *
  36368. * @param {string} type - The matrix type.
  36369. * @return {string} The vector type.
  36370. */
  36371. getVectorFromMatrix( type ) {
  36372. return type.replace( 'mat', 'vec' );
  36373. }
  36374. /**
  36375. * For a given type this method changes the component type to the
  36376. * given value. E.g. `vec4` should be changed to the new component type
  36377. * `uint` which results in `uvec4`.
  36378. *
  36379. * @param {string} type - The type.
  36380. * @param {string} newComponentType - The new component type.
  36381. * @return {string} The new type.
  36382. */
  36383. changeComponentType( type, newComponentType ) {
  36384. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  36385. }
  36386. /**
  36387. * Returns the integer type pendant for the given type.
  36388. *
  36389. * @param {string} type - The type.
  36390. * @return {string} The integer type.
  36391. */
  36392. getIntegerType( type ) {
  36393. const componentType = this.getComponentType( type );
  36394. if ( componentType === 'int' || componentType === 'uint' ) return type;
  36395. return this.changeComponentType( type, 'int' );
  36396. }
  36397. /**
  36398. * Adds an active stack to the internal stack.
  36399. *
  36400. * @param {StackNode} stack - The stack node to add.
  36401. */
  36402. setActiveStack( stack ) {
  36403. this.activeStacks.push( stack );
  36404. }
  36405. /**
  36406. * Removes the active stack from the internal stack.
  36407. *
  36408. * @param {StackNode} stack - The stack node to remove.
  36409. */
  36410. removeActiveStack( stack ) {
  36411. if ( this.activeStacks[ this.activeStacks.length - 1 ] === stack ) {
  36412. this.activeStacks.pop();
  36413. } else {
  36414. throw new Error( 'NodeBuilder: Invalid active stack removal.' );
  36415. }
  36416. }
  36417. /**
  36418. * Returns the active stack.
  36419. *
  36420. * @return {StackNode} The active stack.
  36421. */
  36422. getActiveStack() {
  36423. return this.activeStacks[ this.activeStacks.length - 1 ];
  36424. }
  36425. /**
  36426. * Returns the base stack.
  36427. *
  36428. * @return {StackNode} The base stack.
  36429. */
  36430. getBaseStack() {
  36431. return this.activeStacks[ 0 ];
  36432. }
  36433. /**
  36434. * Adds a stack node to the internal stack.
  36435. *
  36436. * @return {StackNode} The added stack node.
  36437. */
  36438. addStack() {
  36439. this.stack = stack( this.stack );
  36440. const previousStack = getCurrentStack();
  36441. this.stacks.push( previousStack );
  36442. setCurrentStack( this.stack );
  36443. return this.stack;
  36444. }
  36445. /**
  36446. * Removes the last stack node from the internal stack.
  36447. *
  36448. * @return {StackNode} The removed stack node.
  36449. */
  36450. removeStack() {
  36451. const lastStack = this.stack;
  36452. for ( const node of lastStack.nodes ) {
  36453. const nodeData = this.getDataFromNode( node );
  36454. nodeData.stack = lastStack;
  36455. }
  36456. this.stack = lastStack.parent;
  36457. setCurrentStack( this.stacks.pop() );
  36458. return lastStack;
  36459. }
  36460. /**
  36461. * The builder maintains (cached) data for each node during the building process. This method
  36462. * can be used to get these data for a specific shader stage and cache.
  36463. *
  36464. * @param {Node} node - The node to get the data for.
  36465. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36466. * @param {?NodeCache} cache - An optional cache.
  36467. * @return {Object} The node data.
  36468. */
  36469. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  36470. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  36471. let nodeData = cache.getData( node );
  36472. if ( nodeData === undefined ) {
  36473. nodeData = {};
  36474. cache.setData( node, nodeData );
  36475. }
  36476. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  36477. //
  36478. let data = nodeData[ shaderStage ];
  36479. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  36480. const subBuild = this.getClosestSubBuild( subBuilds );
  36481. if ( subBuild ) {
  36482. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  36483. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  36484. data.subBuilds = subBuilds;
  36485. }
  36486. return data;
  36487. }
  36488. /**
  36489. * Returns the properties for the given node and shader stage.
  36490. *
  36491. * Properties are typically used within a build stage to reference a node's
  36492. * child node or nodes manually assigned to the properties in a separate build stage.
  36493. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  36494. * to the current node's properties in the setup stage and building those properties in the generate stage.
  36495. *
  36496. * @param {Node} node - The node to get the properties for.
  36497. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  36498. * @return {Object} The node properties.
  36499. */
  36500. getNodeProperties( node, shaderStage = 'any' ) {
  36501. const nodeData = this.getDataFromNode( node, shaderStage );
  36502. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  36503. }
  36504. /**
  36505. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  36506. *
  36507. * @param {BufferAttributeNode} node - The buffer attribute node.
  36508. * @param {string} type - The node type.
  36509. * @return {NodeAttribute} The node attribute.
  36510. */
  36511. getBufferAttributeFromNode( node, type ) {
  36512. const nodeData = this.getDataFromNode( node, 'vertex' );
  36513. let bufferAttribute = nodeData.bufferAttribute;
  36514. if ( bufferAttribute === undefined ) {
  36515. const index = this.uniforms.index ++;
  36516. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  36517. this.bufferAttributes.push( bufferAttribute );
  36518. nodeData.bufferAttribute = bufferAttribute;
  36519. }
  36520. return bufferAttribute;
  36521. }
  36522. /**
  36523. * Returns an instance of {@link StructType} for the given struct name and shader stage
  36524. * or null if not found.
  36525. *
  36526. * @param {string} name - The name of the struct.
  36527. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36528. * @return {?StructType} The struct type or null if not found.
  36529. */
  36530. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  36531. return this.types[ shaderStage ][ name ] || null;
  36532. }
  36533. /**
  36534. * Returns an instance of {@link StructType} for the given output struct node.
  36535. *
  36536. * @param {OutputStructNode} node - The output struct node.
  36537. * @param {Array<Object>} membersLayout - The output struct types.
  36538. * @param {?string} [name=null] - The name of the struct.
  36539. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36540. * @return {StructType} The struct type attribute.
  36541. */
  36542. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  36543. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36544. let structType = nodeData.structType;
  36545. if ( structType === undefined ) {
  36546. const index = this.structs.index ++;
  36547. if ( name === null ) name = 'StructType' + index;
  36548. structType = new StructType( name, membersLayout );
  36549. this.structs[ shaderStage ].push( structType );
  36550. this.types[ shaderStage ][ name ] = node;
  36551. nodeData.structType = structType;
  36552. }
  36553. return structType;
  36554. }
  36555. /**
  36556. * Returns an instance of {@link StructType} for the given output struct node.
  36557. *
  36558. * @param {OutputStructNode} node - The output struct node.
  36559. * @param {Array<Object>} membersLayout - The output struct types.
  36560. * @return {StructType} The struct type attribute.
  36561. */
  36562. getOutputStructTypeFromNode( node, membersLayout ) {
  36563. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  36564. structType.output = true;
  36565. return structType;
  36566. }
  36567. /**
  36568. * Returns an instance of {@link NodeUniform} for the given uniform node.
  36569. *
  36570. * @param {UniformNode} node - The uniform node.
  36571. * @param {string} type - The uniform type.
  36572. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36573. * @param {?string} name - The name of the uniform.
  36574. * @return {NodeUniform} The node uniform.
  36575. */
  36576. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  36577. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36578. let nodeUniform = nodeData.uniform;
  36579. if ( nodeUniform === undefined ) {
  36580. const index = this.uniforms.index ++;
  36581. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  36582. this.uniforms[ shaderStage ].push( nodeUniform );
  36583. this.registerDeclaration( nodeUniform );
  36584. nodeData.uniform = nodeUniform;
  36585. }
  36586. return nodeUniform;
  36587. }
  36588. /**
  36589. * Returns an instance of {@link NodeVar} for the given variable node.
  36590. *
  36591. * @param {VarNode} node - The variable node.
  36592. * @param {?string} name - The variable's name.
  36593. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  36594. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36595. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  36596. *
  36597. * @return {NodeVar} The node variable.
  36598. */
  36599. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  36600. const nodeData = this.getDataFromNode( node, shaderStage );
  36601. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  36602. let nodeVar = nodeData[ subBuildVariable ];
  36603. if ( nodeVar === undefined ) {
  36604. const idNS = readOnly ? '_const' : '_var';
  36605. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  36606. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  36607. if ( name === null ) {
  36608. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  36609. this.vars[ idNS ] ++;
  36610. }
  36611. //
  36612. if ( subBuildVariable !== 'variable' ) {
  36613. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  36614. }
  36615. //
  36616. const count = node.getArrayCount( this );
  36617. nodeVar = new NodeVar( name, type, readOnly, count );
  36618. if ( ! readOnly ) {
  36619. vars.push( nodeVar );
  36620. }
  36621. this.registerDeclaration( nodeVar );
  36622. nodeData[ subBuildVariable ] = nodeVar;
  36623. }
  36624. return nodeVar;
  36625. }
  36626. /**
  36627. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  36628. *
  36629. * @param {Node} node - The varying node.
  36630. * @return {boolean} Returns true if deterministic.
  36631. */
  36632. isDeterministic( node ) {
  36633. if ( node.isMathNode ) {
  36634. return this.isDeterministic( node.aNode ) &&
  36635. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  36636. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  36637. } else if ( node.isOperatorNode ) {
  36638. return this.isDeterministic( node.aNode ) &&
  36639. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  36640. } else if ( node.isArrayNode ) {
  36641. if ( node.values !== null ) {
  36642. for ( const n of node.values ) {
  36643. if ( ! this.isDeterministic( n ) ) {
  36644. return false;
  36645. }
  36646. }
  36647. }
  36648. return true;
  36649. } else if ( node.isConstNode ) {
  36650. return true;
  36651. }
  36652. return false;
  36653. }
  36654. /**
  36655. * Returns an instance of {@link NodeVarying} for the given varying node.
  36656. *
  36657. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  36658. * @param {?string} name - The varying's name.
  36659. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  36660. * @param {?string} interpolationType - The interpolation type of the varying.
  36661. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  36662. * @return {NodeVar} The node varying.
  36663. */
  36664. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  36665. const nodeData = this.getDataFromNode( node, 'any' );
  36666. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  36667. let nodeVarying = nodeData[ subBuildVarying ];
  36668. if ( nodeVarying === undefined ) {
  36669. const varyings = this.varyings;
  36670. const index = varyings.length;
  36671. if ( name === null ) name = 'nodeVarying' + index;
  36672. //
  36673. if ( subBuildVarying !== 'varying' ) {
  36674. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  36675. }
  36676. //
  36677. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  36678. varyings.push( nodeVarying );
  36679. this.registerDeclaration( nodeVarying );
  36680. nodeData[ subBuildVarying ] = nodeVarying;
  36681. }
  36682. return nodeVarying;
  36683. }
  36684. /**
  36685. * Registers a node declaration in the current shader stage.
  36686. *
  36687. * @param {Object} node - The node to be registered.
  36688. */
  36689. registerDeclaration( node ) {
  36690. const shaderStage = this.shaderStage;
  36691. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  36692. const property = this.getPropertyName( node );
  36693. let index = 1;
  36694. let name = property;
  36695. // Automatically renames the property if the name is already in use.
  36696. while ( declarations[ name ] !== undefined ) {
  36697. name = property + '_' + index ++;
  36698. }
  36699. if ( index > 1 ) {
  36700. node.name = name;
  36701. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  36702. }
  36703. declarations[ name ] = node;
  36704. }
  36705. /**
  36706. * Returns an instance of {@link NodeCode} for the given code node.
  36707. *
  36708. * @param {CodeNode} node - The code node.
  36709. * @param {string} type - The node type.
  36710. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36711. * @return {NodeCode} The node code.
  36712. */
  36713. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  36714. const nodeData = this.getDataFromNode( node );
  36715. let nodeCode = nodeData.code;
  36716. if ( nodeCode === undefined ) {
  36717. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  36718. const index = codes.length;
  36719. nodeCode = new NodeCode( 'nodeCode' + index, type );
  36720. codes.push( nodeCode );
  36721. nodeData.code = nodeCode;
  36722. }
  36723. return nodeCode;
  36724. }
  36725. /**
  36726. * Adds a code flow based on the code-block hierarchy.
  36727. * This is used so that code-blocks like If,Else create their variables locally if the Node
  36728. * is only used inside one of these conditionals in the current shader stage.
  36729. *
  36730. * @param {Node} node - The node to add.
  36731. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  36732. */
  36733. addFlowCodeHierarchy( node, nodeBlock ) {
  36734. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  36735. let needsFlowCode = true;
  36736. let nodeBlockHierarchy = nodeBlock;
  36737. while ( nodeBlockHierarchy ) {
  36738. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  36739. needsFlowCode = false;
  36740. break;
  36741. }
  36742. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  36743. }
  36744. if ( needsFlowCode ) {
  36745. for ( const flowCode of flowCodes ) {
  36746. this.addLineFlowCode( flowCode );
  36747. }
  36748. }
  36749. }
  36750. /**
  36751. * Add a inline-code to the current flow code-block.
  36752. *
  36753. * @param {Node} node - The node to add.
  36754. * @param {string} code - The code to add.
  36755. * @param {Node} nodeBlock - Current ConditionalNode
  36756. */
  36757. addLineFlowCodeBlock( node, code, nodeBlock ) {
  36758. const nodeData = this.getDataFromNode( node );
  36759. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  36760. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  36761. flowCodes.push( code );
  36762. codeBlock.set( nodeBlock, true );
  36763. }
  36764. /**
  36765. * Add a inline-code to the current flow.
  36766. *
  36767. * @param {string} code - The code to add.
  36768. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  36769. * @return {NodeBuilder} A reference to this node builder.
  36770. */
  36771. addLineFlowCode( code, node = null ) {
  36772. if ( code === '' ) return this;
  36773. if ( node !== null && this.context.nodeBlock ) {
  36774. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  36775. }
  36776. code = this.tab + code;
  36777. if ( ! /;\s*$/.test( code ) ) {
  36778. code = code + ';\n';
  36779. }
  36780. this.flow.code += code;
  36781. return this;
  36782. }
  36783. /**
  36784. * Adds a code to the current code flow.
  36785. *
  36786. * @param {string} code - Shader code.
  36787. * @return {NodeBuilder} A reference to this node builder.
  36788. */
  36789. addFlowCode( code ) {
  36790. this.flow.code += code;
  36791. return this;
  36792. }
  36793. /**
  36794. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  36795. * Typically used in codes with If,Else.
  36796. *
  36797. * @return {NodeBuilder} A reference to this node builder.
  36798. */
  36799. addFlowTab() {
  36800. this.tab += '\t';
  36801. return this;
  36802. }
  36803. /**
  36804. * Removes a tab.
  36805. *
  36806. * @return {NodeBuilder} A reference to this node builder.
  36807. */
  36808. removeFlowTab() {
  36809. this.tab = this.tab.slice( 0, -1 );
  36810. return this;
  36811. }
  36812. /**
  36813. * Gets the current flow data based on a Node.
  36814. *
  36815. * @param {Node} node - Node that the flow was started.
  36816. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36817. * @return {Object} The flow data.
  36818. */
  36819. getFlowData( node/*, shaderStage*/ ) {
  36820. return this.flowsData.get( node );
  36821. }
  36822. /**
  36823. * Executes the node flow based on a root node to generate the final shader code.
  36824. *
  36825. * @param {Node} node - The node to execute.
  36826. * @return {Object} The code flow.
  36827. */
  36828. flowNode( node ) {
  36829. const output = node.getNodeType( this );
  36830. const flowData = this.flowChildNode( node, output );
  36831. this.flowsData.set( node, flowData );
  36832. return flowData;
  36833. }
  36834. /**
  36835. * Includes a node in the current function node.
  36836. *
  36837. * @param {Node} node - The node to include.
  36838. * @returns {void}
  36839. */
  36840. addInclude( node ) {
  36841. if ( this.currentFunctionNode !== null ) {
  36842. this.currentFunctionNode.includes.push( node );
  36843. }
  36844. }
  36845. /**
  36846. * Returns the native shader operator name for a given generic name.
  36847. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  36848. *
  36849. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  36850. * @return {FunctionNode} The build function node.
  36851. */
  36852. buildFunctionNode( shaderNode ) {
  36853. const fn = new FunctionNode();
  36854. const previous = this.currentFunctionNode;
  36855. this.currentFunctionNode = fn;
  36856. fn.code = this.buildFunctionCode( shaderNode );
  36857. this.currentFunctionNode = previous;
  36858. return fn;
  36859. }
  36860. /**
  36861. * Generates a code flow based on a TSL function: Fn().
  36862. *
  36863. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  36864. * @return {Object}
  36865. */
  36866. flowShaderNode( shaderNode ) {
  36867. const layout = shaderNode.layout;
  36868. const inputs = {
  36869. [ Symbol.iterator ]() {
  36870. let index = 0;
  36871. const values = Object.values( this );
  36872. return {
  36873. next: () => ( {
  36874. value: values[ index ],
  36875. done: index ++ >= values.length
  36876. } )
  36877. };
  36878. }
  36879. };
  36880. for ( const input of layout.inputs ) {
  36881. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  36882. }
  36883. //
  36884. shaderNode.layout = null;
  36885. const callNode = shaderNode.call( inputs );
  36886. const flowData = this.flowStagesNode( callNode, layout.type );
  36887. shaderNode.layout = layout;
  36888. return flowData;
  36889. }
  36890. /**
  36891. * Executes the node in a specific build stage.
  36892. *
  36893. * This function can be used to arbitrarily execute the specified build stage
  36894. * outside of the standard build process. For instance, if a node's type depends
  36895. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  36896. * can be used to execute the setup build stage and access its generated nodes
  36897. * before the standard build process begins.
  36898. *
  36899. * @param {Node} node - The node to execute.
  36900. * @param {string} buildStage - The build stage to execute the node in.
  36901. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  36902. * @return {?(Node|string)} The result of the node build.
  36903. */
  36904. flowBuildStage( node, buildStage, output = null ) {
  36905. const previousBuildStage = this.getBuildStage();
  36906. this.setBuildStage( buildStage );
  36907. const result = node.build( this, output );
  36908. this.setBuildStage( previousBuildStage );
  36909. return result;
  36910. }
  36911. /**
  36912. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  36913. *
  36914. * @param {Node} node - The node to execute.
  36915. * @param {?string} output - Expected output type. For example 'vec3'.
  36916. * @return {Object}
  36917. */
  36918. flowStagesNode( node, output = null ) {
  36919. const previousFlow = this.flow;
  36920. const previousVars = this.vars;
  36921. const previousDeclarations = this.declarations;
  36922. const previousCache = this.cache;
  36923. const previousBuildStage = this.buildStage;
  36924. const previousStack = this.stack;
  36925. const flow = {
  36926. code: ''
  36927. };
  36928. this.flow = flow;
  36929. this.vars = {};
  36930. this.declarations = {};
  36931. this.cache = new NodeCache();
  36932. this.stack = stack();
  36933. for ( const buildStage of defaultBuildStages ) {
  36934. this.setBuildStage( buildStage );
  36935. flow.result = node.build( this, output );
  36936. }
  36937. flow.vars = this.getVars( this.shaderStage );
  36938. this.flow = previousFlow;
  36939. this.vars = previousVars;
  36940. this.declarations = previousDeclarations;
  36941. this.cache = previousCache;
  36942. this.stack = previousStack;
  36943. this.setBuildStage( previousBuildStage );
  36944. return flow;
  36945. }
  36946. /**
  36947. * Returns the native shader operator name for a given generic name.
  36948. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  36949. *
  36950. * @abstract
  36951. * @param {string} op - The operator name to resolve.
  36952. * @return {?string} The resolved operator name.
  36953. */
  36954. getFunctionOperator( /* op */ ) {
  36955. return null;
  36956. }
  36957. /**
  36958. * Builds the given shader node.
  36959. *
  36960. * @abstract
  36961. * @param {ShaderNodeInternal} shaderNode - The shader node.
  36962. * @return {string} The function code.
  36963. */
  36964. buildFunctionCode( /* shaderNode */ ) {
  36965. warn( 'Abstract function.' );
  36966. }
  36967. /**
  36968. * Generates a code flow based on a child Node.
  36969. *
  36970. * @param {Node} node - The node to execute.
  36971. * @param {?string} output - Expected output type. For example 'vec3'.
  36972. * @return {Object} The code flow.
  36973. */
  36974. flowChildNode( node, output = null ) {
  36975. const previousFlow = this.flow;
  36976. const flow = {
  36977. code: ''
  36978. };
  36979. this.flow = flow;
  36980. flow.result = node.build( this, output );
  36981. this.flow = previousFlow;
  36982. return flow;
  36983. }
  36984. /**
  36985. * Executes a flow of code in a different stage.
  36986. *
  36987. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  36988. * return the value in fragment-stage even if it is being executed in an input fragment.
  36989. *
  36990. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36991. * @param {Node} node - The node to execute.
  36992. * @param {?string} output - Expected output type. For example 'vec3'.
  36993. * @param {?string} propertyName - The property name to assign the result.
  36994. * @return {?(Object|Node)} The code flow or node.build() result.
  36995. */
  36996. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  36997. const previousTab = this.tab;
  36998. const previousCache = this.cache;
  36999. const previousShaderStage = this.shaderStage;
  37000. const previousContext = this.context;
  37001. this.setShaderStage( shaderStage );
  37002. const context = { ...this.context };
  37003. delete context.nodeBlock;
  37004. this.cache = this.globalCache;
  37005. this.tab = '\t';
  37006. this.context = context;
  37007. let result = null;
  37008. if ( this.buildStage === 'generate' ) {
  37009. const flowData = this.flowChildNode( node, output );
  37010. if ( propertyName !== null ) {
  37011. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  37012. }
  37013. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  37014. result = flowData;
  37015. } else {
  37016. result = node.build( this );
  37017. }
  37018. this.setShaderStage( previousShaderStage );
  37019. this.cache = previousCache;
  37020. this.tab = previousTab;
  37021. this.context = previousContext;
  37022. return result;
  37023. }
  37024. /**
  37025. * Returns an array holding all node attributes of this node builder.
  37026. *
  37027. * @return {Array<NodeAttribute>} The node attributes of this builder.
  37028. */
  37029. getAttributesArray() {
  37030. return this.attributes.concat( this.bufferAttributes );
  37031. }
  37032. /**
  37033. * Returns the attribute definitions as a shader string for the given shader stage.
  37034. *
  37035. * @abstract
  37036. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37037. * @return {string} The attribute code section.
  37038. */
  37039. getAttributes( /*shaderStage*/ ) {
  37040. warn( 'Abstract function.' );
  37041. }
  37042. /**
  37043. * Returns the varying definitions as a shader string for the given shader stage.
  37044. *
  37045. * @abstract
  37046. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37047. * @return {string} The varying code section.
  37048. */
  37049. getVaryings( /*shaderStage*/ ) {
  37050. warn( 'Abstract function.' );
  37051. }
  37052. /**
  37053. * Returns a single variable definition as a shader string for the given variable type and name.
  37054. *
  37055. * @param {string} type - The variable's type.
  37056. * @param {string} name - The variable's name.
  37057. * @param {?number} [count=null] - The array length.
  37058. * @return {string} The shader string.
  37059. */
  37060. getVar( type, name, count = null ) {
  37061. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  37062. }
  37063. /**
  37064. * Returns the variable definitions as a shader string for the given shader stage.
  37065. *
  37066. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37067. * @return {string} The variable code section.
  37068. */
  37069. getVars( shaderStage ) {
  37070. let snippet = '';
  37071. const vars = this.vars[ shaderStage ];
  37072. if ( vars !== undefined ) {
  37073. for ( const variable of vars ) {
  37074. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  37075. }
  37076. }
  37077. return snippet;
  37078. }
  37079. /**
  37080. * Returns the uniform definitions as a shader string for the given shader stage.
  37081. *
  37082. * @abstract
  37083. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37084. * @return {string} The uniform code section.
  37085. */
  37086. getUniforms( /*shaderStage*/ ) {
  37087. warn( 'Abstract function.' );
  37088. }
  37089. /**
  37090. * Returns the native code definitions as a shader string for the given shader stage.
  37091. *
  37092. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37093. * @return {string} The native code section.
  37094. */
  37095. getCodes( shaderStage ) {
  37096. const codes = this.codes[ shaderStage ];
  37097. let code = '';
  37098. if ( codes !== undefined ) {
  37099. for ( const nodeCode of codes ) {
  37100. code += nodeCode.code + '\n';
  37101. }
  37102. }
  37103. return code;
  37104. }
  37105. /**
  37106. * Returns the hash of this node builder.
  37107. *
  37108. * @return {string} The hash.
  37109. */
  37110. getHash() {
  37111. return this.vertexShader + this.fragmentShader + this.computeShader;
  37112. }
  37113. /**
  37114. * Sets the current shader stage.
  37115. *
  37116. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  37117. */
  37118. setShaderStage( shaderStage ) {
  37119. this.shaderStage = shaderStage;
  37120. }
  37121. /**
  37122. * Returns the current shader stage.
  37123. *
  37124. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  37125. */
  37126. getShaderStage() {
  37127. return this.shaderStage;
  37128. }
  37129. /**
  37130. * Sets the current build stage.
  37131. *
  37132. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  37133. */
  37134. setBuildStage( buildStage ) {
  37135. this.buildStage = buildStage;
  37136. }
  37137. /**
  37138. * Returns the current build stage.
  37139. *
  37140. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  37141. */
  37142. getBuildStage() {
  37143. return this.buildStage;
  37144. }
  37145. /**
  37146. * Controls the code build of the shader stages.
  37147. *
  37148. * @abstract
  37149. */
  37150. buildCode() {
  37151. warn( 'Abstract function.' );
  37152. }
  37153. /**
  37154. * Returns the current sub-build layer.
  37155. *
  37156. * @return {SubBuildNode} The current sub-build layers.
  37157. */
  37158. get subBuild() {
  37159. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  37160. }
  37161. /**
  37162. * Adds a sub-build layer to the node builder.
  37163. *
  37164. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  37165. */
  37166. addSubBuild( subBuild ) {
  37167. this.subBuildLayers.push( subBuild );
  37168. }
  37169. /**
  37170. * Removes the last sub-build layer from the node builder.
  37171. *
  37172. * @return {SubBuildNode} The removed sub-build layer.
  37173. */
  37174. removeSubBuild() {
  37175. return this.subBuildLayers.pop();
  37176. }
  37177. /**
  37178. * Returns the closest sub-build layer for the given data.
  37179. *
  37180. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  37181. * @return {?string} The closest sub-build name or null if none found.
  37182. */
  37183. getClosestSubBuild( data ) {
  37184. let subBuilds;
  37185. if ( data && data.isNode ) {
  37186. if ( data.isShaderCallNodeInternal ) {
  37187. subBuilds = data.shaderNode.subBuilds;
  37188. } else if ( data.isStackNode ) {
  37189. subBuilds = [ data.subBuild ];
  37190. } else {
  37191. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  37192. }
  37193. } else if ( data instanceof Set ) {
  37194. subBuilds = [ ...data ];
  37195. } else {
  37196. subBuilds = data;
  37197. }
  37198. if ( ! subBuilds ) return null;
  37199. const subBuildLayers = this.subBuildLayers;
  37200. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  37201. const subBuild = subBuilds[ i ];
  37202. if ( subBuildLayers.includes( subBuild ) ) {
  37203. return subBuild;
  37204. }
  37205. }
  37206. return null;
  37207. }
  37208. /**
  37209. * Returns the output node of a sub-build layer.
  37210. *
  37211. * @param {Node} node - The node to get the output from.
  37212. * @return {string} The output node name.
  37213. */
  37214. getSubBuildOutput( node ) {
  37215. return this.getSubBuildProperty( 'outputNode', node );
  37216. }
  37217. /**
  37218. * Returns the sub-build property name for the given property and node.
  37219. *
  37220. * @param {string} [property=''] - The property name.
  37221. * @param {?Node} [node=null] - The node to get the sub-build from.
  37222. * @return {string} The sub-build property name.
  37223. */
  37224. getSubBuildProperty( property = '', node = null ) {
  37225. let subBuild;
  37226. if ( node !== null ) {
  37227. subBuild = this.getClosestSubBuild( node );
  37228. } else {
  37229. subBuild = this.subBuildFn;
  37230. }
  37231. let result;
  37232. if ( subBuild ) {
  37233. result = property ? ( subBuild + '_' + property ) : subBuild;
  37234. } else {
  37235. result = property;
  37236. }
  37237. return result;
  37238. }
  37239. /**
  37240. * Central build method which controls the build for the given object.
  37241. *
  37242. * @return {NodeBuilder} A reference to this node builder.
  37243. */
  37244. build() {
  37245. const { object, material, renderer } = this;
  37246. if ( material !== null ) {
  37247. let nodeMaterial = renderer.library.fromMaterial( material );
  37248. if ( nodeMaterial === null ) {
  37249. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  37250. nodeMaterial = new NodeMaterial();
  37251. }
  37252. nodeMaterial.build( this );
  37253. } else {
  37254. this.addFlow( 'compute', object );
  37255. }
  37256. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  37257. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  37258. // generate() -> stage 3: generate shader
  37259. for ( const buildStage of defaultBuildStages ) {
  37260. this.setBuildStage( buildStage );
  37261. if ( this.context.vertex && this.context.vertex.isNode ) {
  37262. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  37263. }
  37264. for ( const shaderStage of shaderStages ) {
  37265. this.setShaderStage( shaderStage );
  37266. const flowNodes = this.flowNodes[ shaderStage ];
  37267. for ( const node of flowNodes ) {
  37268. if ( buildStage === 'generate' ) {
  37269. this.flowNode( node );
  37270. } else {
  37271. node.build( this );
  37272. }
  37273. }
  37274. }
  37275. }
  37276. this.setBuildStage( null );
  37277. this.setShaderStage( null );
  37278. // stage 4: build code for a specific output
  37279. this.buildCode();
  37280. this.buildUpdateNodes();
  37281. return this;
  37282. }
  37283. /**
  37284. * Returns shared data object for the given node.
  37285. *
  37286. * @param {Node} node - The node to get shared data from.
  37287. * @return {Object} The shared data.
  37288. */
  37289. getSharedDataFromNode( node ) {
  37290. let data = sharedNodeData.get( node );
  37291. if ( data === undefined ) {
  37292. data = {};
  37293. }
  37294. return data;
  37295. }
  37296. /**
  37297. * Returns a uniform representation which is later used for UBO generation and rendering.
  37298. *
  37299. * @param {NodeUniform} uniformNode - The uniform node.
  37300. * @param {string} type - The requested type.
  37301. * @return {Uniform} The uniform.
  37302. */
  37303. getNodeUniform( uniformNode, type ) {
  37304. const nodeData = this.getSharedDataFromNode( uniformNode );
  37305. let node = nodeData.cache;
  37306. if ( node === undefined ) {
  37307. if ( type === 'float' || type === 'int' || type === 'uint' ) node = new NumberNodeUniform( uniformNode );
  37308. else if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) node = new Vector2NodeUniform( uniformNode );
  37309. else if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) node = new Vector3NodeUniform( uniformNode );
  37310. else if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) node = new Vector4NodeUniform( uniformNode );
  37311. else if ( type === 'color' ) node = new ColorNodeUniform( uniformNode );
  37312. else if ( type === 'mat2' ) node = new Matrix2NodeUniform( uniformNode );
  37313. else if ( type === 'mat3' ) node = new Matrix3NodeUniform( uniformNode );
  37314. else if ( type === 'mat4' ) node = new Matrix4NodeUniform( uniformNode );
  37315. else {
  37316. throw new Error( `Uniform "${ type }" not implemented.` );
  37317. }
  37318. nodeData.cache = node;
  37319. }
  37320. return node;
  37321. }
  37322. /**
  37323. * Formats the given shader snippet from a given type into another one. E.g.
  37324. * this method might be used to convert a simple float string `"1.0"` into a
  37325. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  37326. *
  37327. * @param {string} snippet - The shader snippet.
  37328. * @param {string} fromType - The source type.
  37329. * @param {string} toType - The target type.
  37330. * @return {string} The updated shader string.
  37331. */
  37332. format( snippet, fromType, toType ) {
  37333. fromType = this.getVectorType( fromType );
  37334. toType = this.getVectorType( toType );
  37335. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  37336. return snippet;
  37337. }
  37338. const fromTypeLength = this.getTypeLength( fromType );
  37339. const toTypeLength = this.getTypeLength( toType );
  37340. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  37341. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  37342. }
  37343. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  37344. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  37345. }
  37346. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  37347. // @TODO: ignore for now
  37348. return snippet;
  37349. }
  37350. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  37351. // @TODO: ignore for now
  37352. return snippet;
  37353. }
  37354. if ( fromTypeLength === toTypeLength ) {
  37355. return `${ this.getType( toType ) }( ${ snippet } )`;
  37356. }
  37357. if ( fromTypeLength > toTypeLength ) {
  37358. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  37359. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  37360. }
  37361. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  37362. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  37363. }
  37364. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  37365. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  37366. }
  37367. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  37368. // convert a number value to vector type, e.g:
  37369. // vec3( 1u ) -> vec3( float( 1u ) )
  37370. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  37371. }
  37372. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  37373. }
  37374. /**
  37375. * Returns a signature with the engine's current revision.
  37376. *
  37377. * @return {string} The signature.
  37378. */
  37379. getSignature() {
  37380. return `// Three.js r${ REVISION } - Node System\n`;
  37381. }
  37382. }
  37383. /**
  37384. * Management class for updating nodes. The module tracks metrics like
  37385. * the elapsed time, delta time, the render and frame ID to correctly
  37386. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  37387. * and {@link Node#updateAfter} depending on the node's configuration.
  37388. */
  37389. class NodeFrame {
  37390. /**
  37391. * Constructs a new node fame.
  37392. */
  37393. constructor() {
  37394. /**
  37395. * The elapsed time in seconds.
  37396. *
  37397. * @type {number}
  37398. * @default 0
  37399. */
  37400. this.time = 0;
  37401. /**
  37402. * The delta time in seconds.
  37403. *
  37404. * @type {number}
  37405. * @default 0
  37406. */
  37407. this.deltaTime = 0;
  37408. /**
  37409. * The frame ID.
  37410. *
  37411. * @type {number}
  37412. * @default 0
  37413. */
  37414. this.frameId = 0;
  37415. /**
  37416. * The render ID.
  37417. *
  37418. * @type {number}
  37419. * @default 0
  37420. */
  37421. this.renderId = 0;
  37422. /**
  37423. * Used to control the {@link Node#update} call.
  37424. *
  37425. * @type {WeakMap<Node, Object>}
  37426. */
  37427. this.updateMap = new WeakMap();
  37428. /**
  37429. * Used to control the {@link Node#updateBefore} call.
  37430. *
  37431. * @type {WeakMap<Node, Object>}
  37432. */
  37433. this.updateBeforeMap = new WeakMap();
  37434. /**
  37435. * Used to control the {@link Node#updateAfter} call.
  37436. *
  37437. * @type {WeakMap<Node, Object>}
  37438. */
  37439. this.updateAfterMap = new WeakMap();
  37440. /**
  37441. * A reference to the current renderer.
  37442. *
  37443. * @type {?Renderer}
  37444. * @default null
  37445. */
  37446. this.renderer = null;
  37447. /**
  37448. * A reference to the current material.
  37449. *
  37450. * @type {?Material}
  37451. * @default null
  37452. */
  37453. this.material = null;
  37454. /**
  37455. * A reference to the current camera.
  37456. *
  37457. * @type {?Camera}
  37458. * @default null
  37459. */
  37460. this.camera = null;
  37461. /**
  37462. * A reference to the current 3D object.
  37463. *
  37464. * @type {?Object3D}
  37465. * @default null
  37466. */
  37467. this.object = null;
  37468. /**
  37469. * A reference to the current scene.
  37470. *
  37471. * @type {?Scene}
  37472. * @default null
  37473. */
  37474. this.scene = null;
  37475. }
  37476. /**
  37477. * Returns a dictionary for a given node and update map which
  37478. * is used to correctly call node update methods per frame or render.
  37479. *
  37480. * @private
  37481. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  37482. * @param {Node} nodeRef - The reference to the current node.
  37483. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  37484. */
  37485. _getMaps( referenceMap, nodeRef ) {
  37486. let maps = referenceMap.get( nodeRef );
  37487. if ( maps === undefined ) {
  37488. maps = {
  37489. renderId: 0,
  37490. frameId: 0,
  37491. };
  37492. referenceMap.set( nodeRef, maps );
  37493. }
  37494. return maps;
  37495. }
  37496. /**
  37497. * This method executes the {@link Node#updateBefore} for the given node.
  37498. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  37499. * is only executed once per frame, render or object depending on the update
  37500. * type.
  37501. *
  37502. * @param {Node} node - The node that should be updated.
  37503. */
  37504. updateBeforeNode( node ) {
  37505. const updateType = node.getUpdateBeforeType();
  37506. const reference = node.updateReference( this );
  37507. if ( updateType === NodeUpdateType.FRAME ) {
  37508. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37509. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  37510. const previousFrameId = nodeUpdateBeforeMap.frameId;
  37511. nodeUpdateBeforeMap.frameId = this.frameId;
  37512. if ( node.updateBefore( this ) === false ) {
  37513. nodeUpdateBeforeMap.frameId = previousFrameId;
  37514. }
  37515. }
  37516. } else if ( updateType === NodeUpdateType.RENDER ) {
  37517. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37518. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  37519. const previousRenderId = nodeUpdateBeforeMap.renderId;
  37520. nodeUpdateBeforeMap.renderId = this.renderId;
  37521. if ( node.updateBefore( this ) === false ) {
  37522. nodeUpdateBeforeMap.renderId = previousRenderId;
  37523. }
  37524. }
  37525. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37526. node.updateBefore( this );
  37527. }
  37528. }
  37529. /**
  37530. * This method executes the {@link Node#updateAfter} for the given node.
  37531. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  37532. * is only executed once per frame, render or object depending on the update
  37533. * type.
  37534. *
  37535. * @param {Node} node - The node that should be updated.
  37536. */
  37537. updateAfterNode( node ) {
  37538. const updateType = node.getUpdateAfterType();
  37539. const reference = node.updateReference( this );
  37540. if ( updateType === NodeUpdateType.FRAME ) {
  37541. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  37542. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  37543. if ( node.updateAfter( this ) !== false ) {
  37544. nodeUpdateAfterMap.frameId = this.frameId;
  37545. }
  37546. }
  37547. } else if ( updateType === NodeUpdateType.RENDER ) {
  37548. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  37549. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  37550. if ( node.updateAfter( this ) !== false ) {
  37551. nodeUpdateAfterMap.renderId = this.renderId;
  37552. }
  37553. }
  37554. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37555. node.updateAfter( this );
  37556. }
  37557. }
  37558. /**
  37559. * This method executes the {@link Node#update} for the given node.
  37560. * It makes sure {@link Node#updateType} is honored meaning the update
  37561. * is only executed once per frame, render or object depending on the update
  37562. * type.
  37563. *
  37564. * @param {Node} node - The node that should be updated.
  37565. */
  37566. updateNode( node ) {
  37567. const updateType = node.getUpdateType();
  37568. const reference = node.updateReference( this );
  37569. if ( updateType === NodeUpdateType.FRAME ) {
  37570. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  37571. if ( nodeUpdateMap.frameId !== this.frameId ) {
  37572. if ( node.update( this ) !== false ) {
  37573. nodeUpdateMap.frameId = this.frameId;
  37574. }
  37575. }
  37576. } else if ( updateType === NodeUpdateType.RENDER ) {
  37577. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  37578. if ( nodeUpdateMap.renderId !== this.renderId ) {
  37579. if ( node.update( this ) !== false ) {
  37580. nodeUpdateMap.renderId = this.renderId;
  37581. }
  37582. }
  37583. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37584. node.update( this );
  37585. }
  37586. }
  37587. /**
  37588. * Updates the internal state of the node frame. This method is
  37589. * called by the renderer in its internal animation loop.
  37590. */
  37591. update() {
  37592. this.frameId ++;
  37593. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  37594. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  37595. this.lastTime = performance.now();
  37596. this.time += this.deltaTime;
  37597. }
  37598. }
  37599. /**
  37600. * Describes the input of a {@link NodeFunction}.
  37601. */
  37602. class NodeFunctionInput {
  37603. /**
  37604. * Constructs a new node function input.
  37605. *
  37606. * @param {string} type - The input type.
  37607. * @param {string} name - The input name.
  37608. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  37609. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  37610. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  37611. */
  37612. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  37613. /**
  37614. * The input type.
  37615. *
  37616. * @type {string}
  37617. */
  37618. this.type = type;
  37619. /**
  37620. * The input name.
  37621. *
  37622. * @type {string}
  37623. */
  37624. this.name = name;
  37625. /**
  37626. * If the input is an Array, count will be the length.
  37627. *
  37628. * @type {?number}
  37629. * @default null
  37630. */
  37631. this.count = count;
  37632. /**
  37633. *The parameter qualifier (only relevant for GLSL).
  37634. *
  37635. * @type {('in'|'out'|'inout')}
  37636. * @default ''
  37637. */
  37638. this.qualifier = qualifier;
  37639. /**
  37640. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  37641. *
  37642. * @type {boolean}
  37643. * @default false
  37644. */
  37645. this.isConst = isConst;
  37646. }
  37647. }
  37648. NodeFunctionInput.isNodeFunctionInput = true;
  37649. /**
  37650. * Module for representing directional lights as nodes.
  37651. *
  37652. * @augments AnalyticLightNode
  37653. */
  37654. class DirectionalLightNode extends AnalyticLightNode {
  37655. static get type() {
  37656. return 'DirectionalLightNode';
  37657. }
  37658. /**
  37659. * Constructs a new directional light node.
  37660. *
  37661. * @param {?DirectionalLight} [light=null] - The directional light source.
  37662. */
  37663. constructor( light = null ) {
  37664. super( light );
  37665. }
  37666. setupDirect() {
  37667. const lightColor = this.colorNode;
  37668. const lightDirection = lightTargetDirection( this.light );
  37669. return { lightDirection, lightColor };
  37670. }
  37671. }
  37672. const _matrix41 = /*@__PURE__*/ new Matrix4();
  37673. const _matrix42 = /*@__PURE__*/ new Matrix4();
  37674. let _ltcLib = null;
  37675. /**
  37676. * Module for representing rect area lights as nodes.
  37677. *
  37678. * @augments AnalyticLightNode
  37679. */
  37680. class RectAreaLightNode extends AnalyticLightNode {
  37681. static get type() {
  37682. return 'RectAreaLightNode';
  37683. }
  37684. /**
  37685. * Constructs a new rect area light node.
  37686. *
  37687. * @param {?RectAreaLight} [light=null] - The rect area light source.
  37688. */
  37689. constructor( light = null ) {
  37690. super( light );
  37691. /**
  37692. * Uniform node representing the half height of the are light.
  37693. *
  37694. * @type {UniformNode<vec3>}
  37695. */
  37696. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  37697. /**
  37698. * Uniform node representing the half width of the are light.
  37699. *
  37700. * @type {UniformNode<vec3>}
  37701. */
  37702. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  37703. /**
  37704. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  37705. * relies on `viewMatrix` which might vary per render call.
  37706. *
  37707. * @type {string}
  37708. * @default 'render'
  37709. */
  37710. this.updateType = NodeUpdateType.RENDER;
  37711. }
  37712. /**
  37713. * Overwritten to updated rect area light specific uniforms.
  37714. *
  37715. * @param {NodeFrame} frame - A reference to the current node frame.
  37716. */
  37717. update( frame ) {
  37718. super.update( frame );
  37719. const { light } = this;
  37720. const viewMatrix = frame.camera.matrixWorldInverse;
  37721. _matrix42.identity();
  37722. _matrix41.copy( light.matrixWorld );
  37723. _matrix41.premultiply( viewMatrix );
  37724. _matrix42.extractRotation( _matrix41 );
  37725. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  37726. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  37727. this.halfWidth.value.applyMatrix4( _matrix42 );
  37728. this.halfHeight.value.applyMatrix4( _matrix42 );
  37729. }
  37730. setupDirectRectArea( builder ) {
  37731. let ltc_1, ltc_2;
  37732. if ( builder.isAvailable( 'float32Filterable' ) ) {
  37733. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  37734. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  37735. } else {
  37736. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  37737. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  37738. }
  37739. const { colorNode, light } = this;
  37740. const lightPosition = lightViewPosition( light );
  37741. return {
  37742. lightColor: colorNode,
  37743. lightPosition,
  37744. halfWidth: this.halfWidth,
  37745. halfHeight: this.halfHeight,
  37746. ltc_1,
  37747. ltc_2
  37748. };
  37749. }
  37750. /**
  37751. * Used to configure the internal BRDF approximation texture data.
  37752. *
  37753. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  37754. */
  37755. static setLTC( ltc ) {
  37756. _ltcLib = ltc;
  37757. }
  37758. }
  37759. /**
  37760. * Module for representing spot lights as nodes.
  37761. *
  37762. * @augments AnalyticLightNode
  37763. */
  37764. class SpotLightNode extends AnalyticLightNode {
  37765. static get type() {
  37766. return 'SpotLightNode';
  37767. }
  37768. /**
  37769. * Constructs a new spot light node.
  37770. *
  37771. * @param {?SpotLight} [light=null] - The spot light source.
  37772. */
  37773. constructor( light = null ) {
  37774. super( light );
  37775. /**
  37776. * Uniform node representing the cone cosine.
  37777. *
  37778. * @type {UniformNode<float>}
  37779. */
  37780. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  37781. /**
  37782. * Uniform node representing the penumbra cosine.
  37783. *
  37784. * @type {UniformNode<float>}
  37785. */
  37786. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  37787. /**
  37788. * Uniform node representing the cutoff distance.
  37789. *
  37790. * @type {UniformNode<float>}
  37791. */
  37792. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  37793. /**
  37794. * Uniform node representing the decay exponent.
  37795. *
  37796. * @type {UniformNode<float>}
  37797. */
  37798. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  37799. /**
  37800. * Uniform node representing the light color.
  37801. *
  37802. * @type {UniformNode<Color>}
  37803. */
  37804. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  37805. }
  37806. /**
  37807. * Overwritten to updated spot light specific uniforms.
  37808. *
  37809. * @param {NodeFrame} frame - A reference to the current node frame.
  37810. */
  37811. update( frame ) {
  37812. super.update( frame );
  37813. const { light } = this;
  37814. this.coneCosNode.value = Math.cos( light.angle );
  37815. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  37816. this.cutoffDistanceNode.value = light.distance;
  37817. this.decayExponentNode.value = light.decay;
  37818. }
  37819. /**
  37820. * Computes the spot attenuation for the given angle.
  37821. *
  37822. * @param {NodeBuilder} builder - The node builder.
  37823. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  37824. * @return {Node<float>} The spot attenuation.
  37825. */
  37826. getSpotAttenuation( builder, angleCosine ) {
  37827. const { coneCosNode, penumbraCosNode } = this;
  37828. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  37829. }
  37830. getLightCoord( builder ) {
  37831. const properties = builder.getNodeProperties( this );
  37832. let projectionUV = properties.projectionUV;
  37833. if ( projectionUV === undefined ) {
  37834. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  37835. properties.projectionUV = projectionUV;
  37836. }
  37837. return projectionUV;
  37838. }
  37839. setupDirect( builder ) {
  37840. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  37841. const lightVector = this.getLightVector( builder );
  37842. const lightDirection = lightVector.normalize();
  37843. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  37844. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  37845. const lightDistance = lightVector.length();
  37846. const lightAttenuation = getDistanceAttenuation( {
  37847. lightDistance,
  37848. cutoffDistance: cutoffDistanceNode,
  37849. decayExponent: decayExponentNode
  37850. } );
  37851. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  37852. let projected, lightCoord;
  37853. if ( light.colorNode ) {
  37854. lightCoord = this.getLightCoord( builder );
  37855. projected = light.colorNode( lightCoord );
  37856. } else if ( light.map ) {
  37857. lightCoord = this.getLightCoord( builder );
  37858. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  37859. }
  37860. if ( projected ) {
  37861. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  37862. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  37863. }
  37864. return { lightColor, lightDirection };
  37865. }
  37866. }
  37867. /**
  37868. * An IES version of the default spot light node.
  37869. *
  37870. * @augments SpotLightNode
  37871. */
  37872. class IESSpotLightNode extends SpotLightNode {
  37873. static get type() {
  37874. return 'IESSpotLightNode';
  37875. }
  37876. /**
  37877. * Overwrites the default implementation to compute an IES conform spot attenuation.
  37878. *
  37879. * @param {NodeBuilder} builder - The node builder.
  37880. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  37881. * @return {Node<float>} The spot attenuation.
  37882. */
  37883. getSpotAttenuation( builder, angleCosine ) {
  37884. const iesMap = this.light.iesMap;
  37885. let spotAttenuation = null;
  37886. if ( iesMap && iesMap.isTexture === true ) {
  37887. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  37888. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  37889. } else {
  37890. spotAttenuation = super.getSpotAttenuation( angleCosine );
  37891. }
  37892. return spotAttenuation;
  37893. }
  37894. }
  37895. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  37896. const d = p.abs().sub( b );
  37897. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  37898. } );
  37899. /**
  37900. * An implementation of a projector light node.
  37901. *
  37902. * @augments SpotLightNode
  37903. */
  37904. class ProjectorLightNode extends SpotLightNode {
  37905. static get type() {
  37906. return 'ProjectorLightNode';
  37907. }
  37908. update( frame ) {
  37909. super.update( frame );
  37910. const light = this.light;
  37911. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  37912. if ( light.aspect === null ) {
  37913. let aspect = 1;
  37914. if ( light.map !== null ) {
  37915. aspect = light.map.width / light.map.height;
  37916. }
  37917. light.shadow.aspect = aspect;
  37918. } else {
  37919. light.shadow.aspect = light.aspect;
  37920. }
  37921. }
  37922. /**
  37923. * Overwrites the default implementation to compute projection attenuation.
  37924. *
  37925. * @param {NodeBuilder} builder - The node builder.
  37926. * @return {Node<float>} The spot attenuation.
  37927. */
  37928. getSpotAttenuation( builder ) {
  37929. const attenuation = float( 0 );
  37930. const penumbraCos = this.penumbraCosNode;
  37931. // compute the fragment's position in the light's clip space
  37932. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  37933. // the sign of w determines whether the current fragment is in front or behind the light.
  37934. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  37935. If( spotLightCoord.w.greaterThan( 0 ), () => {
  37936. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  37937. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  37938. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  37939. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  37940. } );
  37941. return attenuation;
  37942. }
  37943. }
  37944. /**
  37945. * Module for representing ambient lights as nodes.
  37946. *
  37947. * @augments AnalyticLightNode
  37948. */
  37949. class AmbientLightNode extends AnalyticLightNode {
  37950. static get type() {
  37951. return 'AmbientLightNode';
  37952. }
  37953. /**
  37954. * Constructs a new ambient light node.
  37955. *
  37956. * @param {?AmbientLight} [light=null] - The ambient light source.
  37957. */
  37958. constructor( light = null ) {
  37959. super( light );
  37960. }
  37961. setup( { context } ) {
  37962. context.irradiance.addAssign( this.colorNode );
  37963. }
  37964. }
  37965. /**
  37966. * Module for representing hemisphere lights as nodes.
  37967. *
  37968. * @augments AnalyticLightNode
  37969. */
  37970. class HemisphereLightNode extends AnalyticLightNode {
  37971. static get type() {
  37972. return 'HemisphereLightNode';
  37973. }
  37974. /**
  37975. * Constructs a new hemisphere light node.
  37976. *
  37977. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  37978. */
  37979. constructor( light = null ) {
  37980. super( light );
  37981. /**
  37982. * Uniform node representing the light's position.
  37983. *
  37984. * @type {UniformNode<vec3>}
  37985. */
  37986. this.lightPositionNode = lightPosition( light );
  37987. /**
  37988. * A node representing the light's direction.
  37989. *
  37990. * @type {Node<vec3>}
  37991. */
  37992. this.lightDirectionNode = this.lightPositionNode.normalize();
  37993. /**
  37994. * Uniform node representing the light's ground color.
  37995. *
  37996. * @type {UniformNode<vec3>}
  37997. */
  37998. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  37999. }
  38000. /**
  38001. * Overwritten to updated hemisphere light specific uniforms.
  38002. *
  38003. * @param {NodeFrame} frame - A reference to the current node frame.
  38004. */
  38005. update( frame ) {
  38006. const { light } = this;
  38007. super.update( frame );
  38008. this.lightPositionNode.object3d = light;
  38009. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  38010. }
  38011. setup( builder ) {
  38012. const { colorNode, groundColorNode, lightDirectionNode } = this;
  38013. const dotNL = normalWorld.dot( lightDirectionNode );
  38014. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  38015. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  38016. builder.context.irradiance.addAssign( irradiance );
  38017. }
  38018. }
  38019. /**
  38020. * Module for representing light probes as nodes.
  38021. *
  38022. * @augments AnalyticLightNode
  38023. */
  38024. class LightProbeNode extends AnalyticLightNode {
  38025. static get type() {
  38026. return 'LightProbeNode';
  38027. }
  38028. /**
  38029. * Constructs a new light probe node.
  38030. *
  38031. * @param {?LightProbe} [light=null] - The light probe.
  38032. */
  38033. constructor( light = null ) {
  38034. super( light );
  38035. const array = [];
  38036. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  38037. /**
  38038. * Light probe represented as a uniform of spherical harmonics.
  38039. *
  38040. * @type {UniformArrayNode}
  38041. */
  38042. this.lightProbe = uniformArray( array );
  38043. }
  38044. /**
  38045. * Overwritten to updated light probe specific uniforms.
  38046. *
  38047. * @param {NodeFrame} frame - A reference to the current node frame.
  38048. */
  38049. update( frame ) {
  38050. const { light } = this;
  38051. super.update( frame );
  38052. //
  38053. for ( let i = 0; i < 9; i ++ ) {
  38054. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  38055. }
  38056. }
  38057. setup( builder ) {
  38058. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  38059. builder.context.irradiance.addAssign( irradiance );
  38060. }
  38061. }
  38062. /**
  38063. * Base class for node parsers. A derived parser must be implemented
  38064. * for each supported native shader language.
  38065. */
  38066. class NodeParser {
  38067. /**
  38068. * The method parses the given native code an returns a node function.
  38069. *
  38070. * @abstract
  38071. * @param {string} source - The native shader code.
  38072. * @return {NodeFunction} A node function.
  38073. */
  38074. parseFunction( /*source*/ ) {
  38075. warn( 'Abstract function.' );
  38076. }
  38077. }
  38078. /**
  38079. * Base class for node functions. A derived module must be implemented
  38080. * for each supported native shader language. Similar to other `Node*` modules,
  38081. * this class is only relevant during the building process and not used
  38082. * in user-level code.
  38083. */
  38084. class NodeFunction {
  38085. /**
  38086. * Constructs a new node function.
  38087. *
  38088. * @param {string} type - The node type. This type is the return type of the node function.
  38089. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  38090. * @param {string} [name=''] - The function's name.
  38091. * @param {string} [precision=''] - The precision qualifier.
  38092. */
  38093. constructor( type, inputs, name = '', precision = '' ) {
  38094. /**
  38095. * The node type. This type is the return type of the node function.
  38096. *
  38097. * @type {string}
  38098. */
  38099. this.type = type;
  38100. /**
  38101. * The function's inputs.
  38102. *
  38103. * @type {Array<NodeFunctionInput>}
  38104. */
  38105. this.inputs = inputs;
  38106. /**
  38107. * The name of the uniform.
  38108. *
  38109. * @type {string}
  38110. * @default ''
  38111. */
  38112. this.name = name;
  38113. /**
  38114. * The precision qualifier.
  38115. *
  38116. * @type {string}
  38117. * @default ''
  38118. */
  38119. this.precision = precision;
  38120. }
  38121. /**
  38122. * This method returns the native code of the node function.
  38123. *
  38124. * @abstract
  38125. * @param {string} name - The function's name.
  38126. * @return {string} A shader code.
  38127. */
  38128. getCode( /*name = this.name*/ ) {
  38129. warn( 'Abstract function.' );
  38130. }
  38131. }
  38132. NodeFunction.isNodeFunction = true;
  38133. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  38134. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  38135. const pragmaMain = '#pragma main';
  38136. const parse$1 = ( source ) => {
  38137. source = source.trim();
  38138. const pragmaMainIndex = source.indexOf( pragmaMain );
  38139. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  38140. const declaration = mainCode.match( declarationRegexp$1 );
  38141. if ( declaration !== null && declaration.length === 5 ) {
  38142. // tokenizer
  38143. const inputsCode = declaration[ 4 ];
  38144. const propsMatches = [];
  38145. let nameMatch = null;
  38146. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  38147. propsMatches.push( nameMatch );
  38148. }
  38149. // parser
  38150. const inputs = [];
  38151. let i = 0;
  38152. while ( i < propsMatches.length ) {
  38153. const isConst = propsMatches[ i ][ 0 ] === 'const';
  38154. if ( isConst === true ) {
  38155. i ++;
  38156. }
  38157. let qualifier = propsMatches[ i ][ 0 ];
  38158. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  38159. i ++;
  38160. } else {
  38161. qualifier = '';
  38162. }
  38163. const type = propsMatches[ i ++ ][ 0 ];
  38164. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  38165. if ( Number.isNaN( count ) === false ) i ++;
  38166. else count = null;
  38167. const name = propsMatches[ i ++ ][ 0 ];
  38168. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  38169. }
  38170. //
  38171. const blockCode = mainCode.substring( declaration[ 0 ].length );
  38172. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  38173. const type = declaration[ 2 ];
  38174. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  38175. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  38176. return {
  38177. type,
  38178. inputs,
  38179. name,
  38180. precision,
  38181. inputsCode,
  38182. blockCode,
  38183. headerCode
  38184. };
  38185. } else {
  38186. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  38187. }
  38188. };
  38189. /**
  38190. * This class represents a GLSL node function.
  38191. *
  38192. * @augments NodeFunction
  38193. */
  38194. class GLSLNodeFunction extends NodeFunction {
  38195. /**
  38196. * Constructs a new GLSL node function.
  38197. *
  38198. * @param {string} source - The GLSL source.
  38199. */
  38200. constructor( source ) {
  38201. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  38202. super( type, inputs, name, precision );
  38203. this.inputsCode = inputsCode;
  38204. this.blockCode = blockCode;
  38205. this.headerCode = headerCode;
  38206. }
  38207. /**
  38208. * This method returns the GLSL code of the node function.
  38209. *
  38210. * @param {string} [name=this.name] - The function's name.
  38211. * @return {string} The shader code.
  38212. */
  38213. getCode( name = this.name ) {
  38214. let code;
  38215. const blockCode = this.blockCode;
  38216. if ( blockCode !== '' ) {
  38217. const { type, inputsCode, headerCode, precision } = this;
  38218. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  38219. if ( precision !== '' ) {
  38220. declarationCode = `${ precision } ${ declarationCode }`;
  38221. }
  38222. code = headerCode + declarationCode + blockCode;
  38223. } else {
  38224. // interface function
  38225. code = '';
  38226. }
  38227. return code;
  38228. }
  38229. }
  38230. /**
  38231. * A GLSL node parser.
  38232. *
  38233. * @augments NodeParser
  38234. */
  38235. class GLSLNodeParser extends NodeParser {
  38236. /**
  38237. * The method parses the given GLSL code an returns a node function.
  38238. *
  38239. * @param {string} source - The GLSL code.
  38240. * @return {GLSLNodeFunction} A node function.
  38241. */
  38242. parseFunction( source ) {
  38243. return new GLSLNodeFunction( source );
  38244. }
  38245. }
  38246. const _outputNodeMap = new WeakMap();
  38247. const _chainKeys$2 = [];
  38248. const _cacheKeyValues = [];
  38249. /**
  38250. * This renderer module manages node-related objects and is the
  38251. * primary interface between the renderer and the node system.
  38252. *
  38253. * @private
  38254. * @augments DataMap
  38255. */
  38256. class Nodes extends DataMap {
  38257. /**
  38258. * Constructs a new nodes management component.
  38259. *
  38260. * @param {Renderer} renderer - The renderer.
  38261. * @param {Backend} backend - The renderer's backend.
  38262. */
  38263. constructor( renderer, backend ) {
  38264. super();
  38265. /**
  38266. * The renderer.
  38267. *
  38268. * @type {Renderer}
  38269. */
  38270. this.renderer = renderer;
  38271. /**
  38272. * The renderer's backend.
  38273. *
  38274. * @type {Backend}
  38275. */
  38276. this.backend = backend;
  38277. /**
  38278. * The node frame.
  38279. *
  38280. * @type {Renderer}
  38281. */
  38282. this.nodeFrame = new NodeFrame();
  38283. /**
  38284. * A cache for managing node builder states.
  38285. *
  38286. * @type {Map<number,NodeBuilderState>}
  38287. */
  38288. this.nodeBuilderCache = new Map();
  38289. /**
  38290. * A cache for managing data cache key data.
  38291. *
  38292. * @type {ChainMap}
  38293. */
  38294. this.callHashCache = new ChainMap();
  38295. /**
  38296. * A cache for managing node uniforms group data.
  38297. *
  38298. * @type {ChainMap}
  38299. */
  38300. this.groupsData = new ChainMap();
  38301. /**
  38302. * A cache for managing node objects of
  38303. * scene properties like fog or environments.
  38304. *
  38305. * @type {Object<string,WeakMap>}
  38306. */
  38307. this.cacheLib = {};
  38308. }
  38309. /**
  38310. * Returns `true` if the given node uniforms group must be updated or not.
  38311. *
  38312. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  38313. * @return {boolean} Whether the node uniforms group requires an update or not.
  38314. */
  38315. updateGroup( nodeUniformsGroup ) {
  38316. const groupNode = nodeUniformsGroup.groupNode;
  38317. const name = groupNode.name;
  38318. // objectGroup is always updated
  38319. if ( name === objectGroup.name ) return true;
  38320. // renderGroup is updated once per render/compute call
  38321. if ( name === renderGroup.name ) {
  38322. const uniformsGroupData = this.get( nodeUniformsGroup );
  38323. const renderId = this.nodeFrame.renderId;
  38324. if ( uniformsGroupData.renderId !== renderId ) {
  38325. uniformsGroupData.renderId = renderId;
  38326. return true;
  38327. }
  38328. return false;
  38329. }
  38330. // frameGroup is updated once per frame
  38331. if ( name === frameGroup.name ) {
  38332. const uniformsGroupData = this.get( nodeUniformsGroup );
  38333. const frameId = this.nodeFrame.frameId;
  38334. if ( uniformsGroupData.frameId !== frameId ) {
  38335. uniformsGroupData.frameId = frameId;
  38336. return true;
  38337. }
  38338. return false;
  38339. }
  38340. // other groups are updated just when groupNode.needsUpdate is true
  38341. _chainKeys$2[ 0 ] = groupNode;
  38342. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  38343. let groupData = this.groupsData.get( _chainKeys$2 );
  38344. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  38345. _chainKeys$2.length = 0;
  38346. if ( groupData.version !== groupNode.version ) {
  38347. groupData.version = groupNode.version;
  38348. return true;
  38349. }
  38350. return false;
  38351. }
  38352. /**
  38353. * Returns the cache key for the given render object.
  38354. *
  38355. * @param {RenderObject} renderObject - The render object.
  38356. * @return {number} The cache key.
  38357. */
  38358. getForRenderCacheKey( renderObject ) {
  38359. return renderObject.initialCacheKey;
  38360. }
  38361. /**
  38362. * Returns a node builder state for the given render object.
  38363. *
  38364. * @param {RenderObject} renderObject - The render object.
  38365. * @return {NodeBuilderState} The node builder state.
  38366. */
  38367. getForRender( renderObject ) {
  38368. const renderObjectData = this.get( renderObject );
  38369. let nodeBuilderState = renderObjectData.nodeBuilderState;
  38370. if ( nodeBuilderState === undefined ) {
  38371. const { nodeBuilderCache } = this;
  38372. const cacheKey = this.getForRenderCacheKey( renderObject );
  38373. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  38374. if ( nodeBuilderState === undefined ) {
  38375. const createNodeBuilder = ( material ) => {
  38376. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  38377. nodeBuilder.scene = renderObject.scene;
  38378. nodeBuilder.material = material;
  38379. nodeBuilder.camera = renderObject.camera;
  38380. nodeBuilder.context.material = material;
  38381. nodeBuilder.lightsNode = renderObject.lightsNode;
  38382. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  38383. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  38384. nodeBuilder.clippingContext = renderObject.clippingContext;
  38385. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  38386. nodeBuilder.enableMultiview();
  38387. }
  38388. return nodeBuilder;
  38389. };
  38390. let nodeBuilder = createNodeBuilder( renderObject.material );
  38391. try {
  38392. nodeBuilder.build();
  38393. } catch ( e ) {
  38394. nodeBuilder = createNodeBuilder( new NodeMaterial() );
  38395. nodeBuilder.build();
  38396. error( 'TSL: ' + e );
  38397. }
  38398. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38399. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  38400. }
  38401. nodeBuilderState.usedTimes ++;
  38402. renderObjectData.nodeBuilderState = nodeBuilderState;
  38403. }
  38404. return nodeBuilderState;
  38405. }
  38406. /**
  38407. * Deletes the given object from the internal data map
  38408. *
  38409. * @param {any} object - The object to delete.
  38410. * @return {?Object} The deleted dictionary.
  38411. */
  38412. delete( object ) {
  38413. if ( object.isRenderObject ) {
  38414. const nodeBuilderState = this.get( object ).nodeBuilderState;
  38415. nodeBuilderState.usedTimes --;
  38416. if ( nodeBuilderState.usedTimes === 0 ) {
  38417. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  38418. }
  38419. }
  38420. return super.delete( object );
  38421. }
  38422. /**
  38423. * Returns a node builder state for the given compute node.
  38424. *
  38425. * @param {Node} computeNode - The compute node.
  38426. * @return {NodeBuilderState} The node builder state.
  38427. */
  38428. getForCompute( computeNode ) {
  38429. const computeData = this.get( computeNode );
  38430. let nodeBuilderState = computeData.nodeBuilderState;
  38431. if ( nodeBuilderState === undefined ) {
  38432. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  38433. nodeBuilder.build();
  38434. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38435. computeData.nodeBuilderState = nodeBuilderState;
  38436. }
  38437. return nodeBuilderState;
  38438. }
  38439. /**
  38440. * Creates a node builder state for the given node builder.
  38441. *
  38442. * @private
  38443. * @param {NodeBuilder} nodeBuilder - The node builder.
  38444. * @return {NodeBuilderState} The node builder state.
  38445. */
  38446. _createNodeBuilderState( nodeBuilder ) {
  38447. return new NodeBuilderState(
  38448. nodeBuilder.vertexShader,
  38449. nodeBuilder.fragmentShader,
  38450. nodeBuilder.computeShader,
  38451. nodeBuilder.getAttributesArray(),
  38452. nodeBuilder.getBindings(),
  38453. nodeBuilder.updateNodes,
  38454. nodeBuilder.updateBeforeNodes,
  38455. nodeBuilder.updateAfterNodes,
  38456. nodeBuilder.observer,
  38457. nodeBuilder.transforms
  38458. );
  38459. }
  38460. /**
  38461. * Returns an environment node for the current configured
  38462. * scene environment.
  38463. *
  38464. * @param {Scene} scene - The scene.
  38465. * @return {Node} A node representing the current scene environment.
  38466. */
  38467. getEnvironmentNode( scene ) {
  38468. this.updateEnvironment( scene );
  38469. let environmentNode = null;
  38470. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  38471. environmentNode = scene.environmentNode;
  38472. } else {
  38473. const sceneData = this.get( scene );
  38474. if ( sceneData.environmentNode ) {
  38475. environmentNode = sceneData.environmentNode;
  38476. }
  38477. }
  38478. return environmentNode;
  38479. }
  38480. /**
  38481. * Returns a background node for the current configured
  38482. * scene background.
  38483. *
  38484. * @param {Scene} scene - The scene.
  38485. * @return {Node} A node representing the current scene background.
  38486. */
  38487. getBackgroundNode( scene ) {
  38488. this.updateBackground( scene );
  38489. let backgroundNode = null;
  38490. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  38491. backgroundNode = scene.backgroundNode;
  38492. } else {
  38493. const sceneData = this.get( scene );
  38494. if ( sceneData.backgroundNode ) {
  38495. backgroundNode = sceneData.backgroundNode;
  38496. }
  38497. }
  38498. return backgroundNode;
  38499. }
  38500. /**
  38501. * Returns a fog node for the current configured scene fog.
  38502. *
  38503. * @param {Scene} scene - The scene.
  38504. * @return {Node} A node representing the current scene fog.
  38505. */
  38506. getFogNode( scene ) {
  38507. this.updateFog( scene );
  38508. return scene.fogNode || this.get( scene ).fogNode || null;
  38509. }
  38510. /**
  38511. * Returns a cache key for the given scene and lights node.
  38512. * This key is used by `RenderObject` as a part of the dynamic
  38513. * cache key (a key that must be checked every time the render
  38514. * objects is drawn).
  38515. *
  38516. * @param {Scene} scene - The scene.
  38517. * @param {LightsNode} lightsNode - The lights node.
  38518. * @return {number} The cache key.
  38519. */
  38520. getCacheKey( scene, lightsNode ) {
  38521. _chainKeys$2[ 0 ] = scene;
  38522. _chainKeys$2[ 1 ] = lightsNode;
  38523. const callId = this.renderer.info.calls;
  38524. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  38525. if ( cacheKeyData.callId !== callId ) {
  38526. const environmentNode = this.getEnvironmentNode( scene );
  38527. const fogNode = this.getFogNode( scene );
  38528. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  38529. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  38530. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  38531. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  38532. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  38533. _cacheKeyValues.push( this.renderer.shadowMap.type );
  38534. cacheKeyData.callId = callId;
  38535. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  38536. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  38537. _cacheKeyValues.length = 0;
  38538. }
  38539. _chainKeys$2.length = 0;
  38540. return cacheKeyData.cacheKey;
  38541. }
  38542. /**
  38543. * A boolean that indicates whether tone mapping should be enabled
  38544. * or not.
  38545. *
  38546. * @type {boolean}
  38547. */
  38548. get isToneMappingState() {
  38549. return this.renderer.getRenderTarget() ? false : true;
  38550. }
  38551. /**
  38552. * If a scene background is configured, this method makes sure to
  38553. * represent the background with a corresponding node-based implementation.
  38554. *
  38555. * @param {Scene} scene - The scene.
  38556. */
  38557. updateBackground( scene ) {
  38558. const sceneData = this.get( scene );
  38559. const background = scene.background;
  38560. if ( background ) {
  38561. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  38562. if ( sceneData.background !== background || forceUpdate ) {
  38563. const backgroundNode = this.getCacheNode( 'background', background, () => {
  38564. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  38565. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  38566. return pmremTexture( background );
  38567. } else {
  38568. let envMap;
  38569. if ( background.isCubeTexture === true ) {
  38570. envMap = cubeTexture( background );
  38571. } else {
  38572. envMap = texture( background );
  38573. }
  38574. return cubeMapNode( envMap );
  38575. }
  38576. } else if ( background.isTexture === true ) {
  38577. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  38578. } else if ( background.isColor !== true ) {
  38579. error( 'WebGPUNodes: Unsupported background configuration.', background );
  38580. }
  38581. }, forceUpdate );
  38582. sceneData.backgroundNode = backgroundNode;
  38583. sceneData.background = background;
  38584. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  38585. }
  38586. } else if ( sceneData.backgroundNode ) {
  38587. delete sceneData.backgroundNode;
  38588. delete sceneData.background;
  38589. }
  38590. }
  38591. /**
  38592. * This method is part of the caching of nodes which are used to represents the
  38593. * scene's background, fog or environment.
  38594. *
  38595. * @param {string} type - The type of object to cache.
  38596. * @param {Object} object - The object.
  38597. * @param {Function} callback - A callback that produces a node representation for the given object.
  38598. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  38599. * @return {Node} The node representation.
  38600. */
  38601. getCacheNode( type, object, callback, forceUpdate = false ) {
  38602. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  38603. let node = nodeCache.get( object );
  38604. if ( node === undefined || forceUpdate ) {
  38605. node = callback();
  38606. nodeCache.set( object, node );
  38607. }
  38608. return node;
  38609. }
  38610. /**
  38611. * If a scene fog is configured, this method makes sure to
  38612. * represent the fog with a corresponding node-based implementation.
  38613. *
  38614. * @param {Scene} scene - The scene.
  38615. */
  38616. updateFog( scene ) {
  38617. const sceneData = this.get( scene );
  38618. const sceneFog = scene.fog;
  38619. if ( sceneFog ) {
  38620. if ( sceneData.fog !== sceneFog ) {
  38621. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  38622. if ( sceneFog.isFogExp2 ) {
  38623. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  38624. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  38625. return fog( color, densityFogFactor( density ) );
  38626. } else if ( sceneFog.isFog ) {
  38627. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  38628. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  38629. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  38630. return fog( color, rangeFogFactor( near, far ) );
  38631. } else {
  38632. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  38633. }
  38634. } );
  38635. sceneData.fogNode = fogNode;
  38636. sceneData.fog = sceneFog;
  38637. }
  38638. } else {
  38639. delete sceneData.fogNode;
  38640. delete sceneData.fog;
  38641. }
  38642. }
  38643. /**
  38644. * If a scene environment is configured, this method makes sure to
  38645. * represent the environment with a corresponding node-based implementation.
  38646. *
  38647. * @param {Scene} scene - The scene.
  38648. */
  38649. updateEnvironment( scene ) {
  38650. const sceneData = this.get( scene );
  38651. const environment = scene.environment;
  38652. if ( environment ) {
  38653. if ( sceneData.environment !== environment ) {
  38654. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  38655. if ( environment.isCubeTexture === true ) {
  38656. return cubeTexture( environment );
  38657. } else if ( environment.isTexture === true ) {
  38658. return texture( environment );
  38659. } else {
  38660. error( 'Nodes: Unsupported environment configuration.', environment );
  38661. }
  38662. } );
  38663. sceneData.environmentNode = environmentNode;
  38664. sceneData.environment = environment;
  38665. }
  38666. } else if ( sceneData.environmentNode ) {
  38667. delete sceneData.environmentNode;
  38668. delete sceneData.environment;
  38669. }
  38670. }
  38671. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  38672. const nodeFrame = this.nodeFrame;
  38673. nodeFrame.renderer = renderer;
  38674. nodeFrame.scene = scene;
  38675. nodeFrame.object = object;
  38676. nodeFrame.camera = camera;
  38677. nodeFrame.material = material;
  38678. return nodeFrame;
  38679. }
  38680. getNodeFrameForRender( renderObject ) {
  38681. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  38682. }
  38683. /**
  38684. * Returns the current output cache key.
  38685. *
  38686. * @return {string} The output cache key.
  38687. */
  38688. getOutputCacheKey() {
  38689. const renderer = this.renderer;
  38690. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  38691. }
  38692. /**
  38693. * Checks if the output configuration (tone mapping and color space) for
  38694. * the given target has changed.
  38695. *
  38696. * @param {Texture} outputTarget - The output target.
  38697. * @return {boolean} Whether the output configuration has changed or not.
  38698. */
  38699. hasOutputChange( outputTarget ) {
  38700. const cacheKey = _outputNodeMap.get( outputTarget );
  38701. return cacheKey !== this.getOutputCacheKey();
  38702. }
  38703. /**
  38704. * Returns a node that represents the output configuration (tone mapping and
  38705. * color space) for the current target.
  38706. *
  38707. * @param {Texture} outputTarget - The output target.
  38708. * @return {Node} The output node.
  38709. */
  38710. getOutputNode( outputTarget ) {
  38711. const renderer = this.renderer;
  38712. const cacheKey = this.getOutputCacheKey();
  38713. const output = outputTarget.isArrayTexture ?
  38714. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  38715. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  38716. _outputNodeMap.set( outputTarget, cacheKey );
  38717. return output;
  38718. }
  38719. /**
  38720. * Triggers the call of `updateBefore()` methods
  38721. * for all nodes of the given render object.
  38722. *
  38723. * @param {RenderObject} renderObject - The render object.
  38724. */
  38725. updateBefore( renderObject ) {
  38726. const nodeBuilder = renderObject.getNodeBuilderState();
  38727. for ( const node of nodeBuilder.updateBeforeNodes ) {
  38728. // update frame state for each node
  38729. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  38730. }
  38731. }
  38732. /**
  38733. * Triggers the call of `updateAfter()` methods
  38734. * for all nodes of the given render object.
  38735. *
  38736. * @param {RenderObject} renderObject - The render object.
  38737. */
  38738. updateAfter( renderObject ) {
  38739. const nodeBuilder = renderObject.getNodeBuilderState();
  38740. for ( const node of nodeBuilder.updateAfterNodes ) {
  38741. // update frame state for each node
  38742. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  38743. }
  38744. }
  38745. /**
  38746. * Triggers the call of `update()` methods
  38747. * for all nodes of the given compute node.
  38748. *
  38749. * @param {Node} computeNode - The compute node.
  38750. */
  38751. updateForCompute( computeNode ) {
  38752. const nodeFrame = this.getNodeFrame();
  38753. const nodeBuilder = this.getForCompute( computeNode );
  38754. for ( const node of nodeBuilder.updateNodes ) {
  38755. nodeFrame.updateNode( node );
  38756. }
  38757. }
  38758. /**
  38759. * Triggers the call of `update()` methods
  38760. * for all nodes of the given compute node.
  38761. *
  38762. * @param {RenderObject} renderObject - The render object.
  38763. */
  38764. updateForRender( renderObject ) {
  38765. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38766. const nodeBuilder = renderObject.getNodeBuilderState();
  38767. for ( const node of nodeBuilder.updateNodes ) {
  38768. nodeFrame.updateNode( node );
  38769. }
  38770. }
  38771. /**
  38772. * Returns `true` if the given render object requires a refresh.
  38773. *
  38774. * @param {RenderObject} renderObject - The render object.
  38775. * @return {boolean} Whether the given render object requires a refresh or not.
  38776. */
  38777. needsRefresh( renderObject ) {
  38778. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38779. const monitor = renderObject.getMonitor();
  38780. return monitor.needsRefresh( renderObject, nodeFrame );
  38781. }
  38782. /**
  38783. * Frees the internal resources.
  38784. */
  38785. dispose() {
  38786. super.dispose();
  38787. this.nodeFrame = new NodeFrame();
  38788. this.nodeBuilderCache = new Map();
  38789. this.cacheLib = {};
  38790. }
  38791. }
  38792. const _plane = /*@__PURE__*/ new Plane();
  38793. /**
  38794. * Represents the state that is used to perform clipping via clipping planes.
  38795. * There is a default clipping context for each render context. When the
  38796. * scene holds instances of `ClippingGroup`, there will be a context for each
  38797. * group.
  38798. *
  38799. * @private
  38800. */
  38801. class ClippingContext {
  38802. /**
  38803. * Constructs a new clipping context.
  38804. *
  38805. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  38806. */
  38807. constructor( parentContext = null ) {
  38808. /**
  38809. * The clipping context's version.
  38810. *
  38811. * @type {number}
  38812. * @readonly
  38813. */
  38814. this.version = 0;
  38815. /**
  38816. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  38817. *
  38818. * @type {?boolean}
  38819. * @default null
  38820. */
  38821. this.clipIntersection = null;
  38822. /**
  38823. * The clipping context's cache key.
  38824. *
  38825. * @type {string}
  38826. */
  38827. this.cacheKey = '';
  38828. /**
  38829. * Whether the shadow pass is active or not.
  38830. *
  38831. * @type {boolean}
  38832. * @default false
  38833. */
  38834. this.shadowPass = false;
  38835. /**
  38836. * The view normal matrix.
  38837. *
  38838. * @type {Matrix3}
  38839. */
  38840. this.viewNormalMatrix = new Matrix3();
  38841. /**
  38842. * Internal cache for maintaining clipping contexts.
  38843. *
  38844. * @type {WeakMap<ClippingGroup,ClippingContext>}
  38845. */
  38846. this.clippingGroupContexts = new WeakMap();
  38847. /**
  38848. * The intersection planes.
  38849. *
  38850. * @type {Array<Vector4>}
  38851. */
  38852. this.intersectionPlanes = [];
  38853. /**
  38854. * The intersection planes.
  38855. *
  38856. * @type {Array<Vector4>}
  38857. */
  38858. this.unionPlanes = [];
  38859. /**
  38860. * The version of the clipping context's parent context.
  38861. *
  38862. * @type {?number}
  38863. * @readonly
  38864. */
  38865. this.parentVersion = null;
  38866. if ( parentContext !== null ) {
  38867. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  38868. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  38869. this.shadowPass = parentContext.shadowPass;
  38870. this.viewMatrix = parentContext.viewMatrix;
  38871. }
  38872. }
  38873. /**
  38874. * Projects the given source clipping planes and writes the result into the
  38875. * destination array.
  38876. *
  38877. * @param {Array<Plane>} source - The source clipping planes.
  38878. * @param {Array<Vector4>} destination - The destination.
  38879. * @param {number} offset - The offset.
  38880. */
  38881. projectPlanes( source, destination, offset ) {
  38882. const l = source.length;
  38883. for ( let i = 0; i < l; i ++ ) {
  38884. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  38885. const v = destination[ offset + i ];
  38886. const normal = _plane.normal;
  38887. v.x = - normal.x;
  38888. v.y = - normal.y;
  38889. v.z = - normal.z;
  38890. v.w = _plane.constant;
  38891. }
  38892. }
  38893. /**
  38894. * Updates the root clipping context of a scene.
  38895. *
  38896. * @param {Scene} scene - The scene.
  38897. * @param {Camera} camera - The camera that is used to render the scene.
  38898. */
  38899. updateGlobal( scene, camera ) {
  38900. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  38901. this.viewMatrix = camera.matrixWorldInverse;
  38902. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  38903. }
  38904. /**
  38905. * Updates the clipping context.
  38906. *
  38907. * @param {ClippingContext} parentContext - The parent context.
  38908. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  38909. */
  38910. update( parentContext, clippingGroup ) {
  38911. let update = false;
  38912. if ( parentContext.version !== this.parentVersion ) {
  38913. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  38914. this.unionPlanes = Array.from( parentContext.unionPlanes );
  38915. this.parentVersion = parentContext.version;
  38916. }
  38917. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  38918. this.clipIntersection = clippingGroup.clipIntersection;
  38919. if ( this.clipIntersection ) {
  38920. this.unionPlanes.length = parentContext.unionPlanes.length;
  38921. } else {
  38922. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  38923. }
  38924. }
  38925. const srcClippingPlanes = clippingGroup.clippingPlanes;
  38926. const l = srcClippingPlanes.length;
  38927. let dstClippingPlanes;
  38928. let offset;
  38929. if ( this.clipIntersection ) {
  38930. dstClippingPlanes = this.intersectionPlanes;
  38931. offset = parentContext.intersectionPlanes.length;
  38932. } else {
  38933. dstClippingPlanes = this.unionPlanes;
  38934. offset = parentContext.unionPlanes.length;
  38935. }
  38936. if ( dstClippingPlanes.length !== offset + l ) {
  38937. dstClippingPlanes.length = offset + l;
  38938. for ( let i = 0; i < l; i ++ ) {
  38939. dstClippingPlanes[ offset + i ] = new Vector4();
  38940. }
  38941. update = true;
  38942. }
  38943. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  38944. if ( update ) {
  38945. this.version ++;
  38946. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  38947. }
  38948. }
  38949. /**
  38950. * Returns a clipping context for the given clipping group.
  38951. *
  38952. * @param {ClippingGroup} clippingGroup - The clipping group.
  38953. * @return {ClippingContext} The clipping context.
  38954. */
  38955. getGroupContext( clippingGroup ) {
  38956. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  38957. let context = this.clippingGroupContexts.get( clippingGroup );
  38958. if ( context === undefined ) {
  38959. context = new ClippingContext( this );
  38960. this.clippingGroupContexts.set( clippingGroup, context );
  38961. }
  38962. context.update( this, clippingGroup );
  38963. return context;
  38964. }
  38965. /**
  38966. * The count of union clipping planes.
  38967. *
  38968. * @type {number}
  38969. * @readonly
  38970. */
  38971. get unionClippingCount() {
  38972. return this.unionPlanes.length;
  38973. }
  38974. }
  38975. /**
  38976. * This module is used to represent render bundles inside the renderer
  38977. * for further processing.
  38978. *
  38979. * @private
  38980. */
  38981. class RenderBundle {
  38982. /**
  38983. * Constructs a new bundle group.
  38984. *
  38985. * @param {BundleGroup} bundleGroup - The bundle group.
  38986. * @param {Camera} camera - The camera the bundle group is rendered with.
  38987. */
  38988. constructor( bundleGroup, camera ) {
  38989. this.bundleGroup = bundleGroup;
  38990. this.camera = camera;
  38991. }
  38992. }
  38993. const _chainKeys$1 = [];
  38994. /**
  38995. * This renderer module manages render bundles.
  38996. *
  38997. * @private
  38998. */
  38999. class RenderBundles {
  39000. /**
  39001. * Constructs a new render bundle management component.
  39002. */
  39003. constructor() {
  39004. /**
  39005. * A chain map for maintaining the render bundles.
  39006. *
  39007. * @type {ChainMap}
  39008. */
  39009. this.bundles = new ChainMap();
  39010. }
  39011. /**
  39012. * Returns a render bundle for the given bundle group and camera.
  39013. *
  39014. * @param {BundleGroup} bundleGroup - The bundle group.
  39015. * @param {Camera} camera - The camera the bundle group is rendered with.
  39016. * @return {RenderBundle} The render bundle.
  39017. */
  39018. get( bundleGroup, camera ) {
  39019. const bundles = this.bundles;
  39020. _chainKeys$1[ 0 ] = bundleGroup;
  39021. _chainKeys$1[ 1 ] = camera;
  39022. let bundle = bundles.get( _chainKeys$1 );
  39023. if ( bundle === undefined ) {
  39024. bundle = new RenderBundle( bundleGroup, camera );
  39025. bundles.set( _chainKeys$1, bundle );
  39026. }
  39027. _chainKeys$1.length = 0;
  39028. return bundle;
  39029. }
  39030. /**
  39031. * Frees all internal resources.
  39032. */
  39033. dispose() {
  39034. this.bundles = new ChainMap();
  39035. }
  39036. }
  39037. /**
  39038. * The purpose of a node library is to assign node implementations
  39039. * to existing library features. In `WebGPURenderer` lights, materials
  39040. * which are not based on `NodeMaterial` as well as tone mapping techniques
  39041. * are implemented with node-based modules.
  39042. *
  39043. * @private
  39044. */
  39045. class NodeLibrary {
  39046. /**
  39047. * Constructs a new node library.
  39048. */
  39049. constructor() {
  39050. /**
  39051. * A weak map that maps lights to light nodes.
  39052. *
  39053. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  39054. */
  39055. this.lightNodes = new WeakMap();
  39056. /**
  39057. * A map that maps materials to node materials.
  39058. *
  39059. * @type {Map<string,NodeMaterial.constructor>}
  39060. */
  39061. this.materialNodes = new Map();
  39062. /**
  39063. * A map that maps tone mapping techniques (constants)
  39064. * to tone mapping node functions.
  39065. *
  39066. * @type {Map<number,Function>}
  39067. */
  39068. this.toneMappingNodes = new Map();
  39069. }
  39070. /**
  39071. * Returns a matching node material instance for the given material object.
  39072. *
  39073. * This method also assigns/copies the properties of the given material object
  39074. * to the node material. This is done to make sure the current material
  39075. * configuration carries over to the node version.
  39076. *
  39077. * @param {Material} material - A material.
  39078. * @return {NodeMaterial} The corresponding node material.
  39079. */
  39080. fromMaterial( material ) {
  39081. if ( material.isNodeMaterial ) return material;
  39082. let nodeMaterial = null;
  39083. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  39084. if ( nodeMaterialClass !== null ) {
  39085. nodeMaterial = new nodeMaterialClass();
  39086. for ( const key in material ) {
  39087. nodeMaterial[ key ] = material[ key ];
  39088. }
  39089. }
  39090. return nodeMaterial;
  39091. }
  39092. /**
  39093. * Adds a tone mapping node function for a tone mapping technique (constant).
  39094. *
  39095. * @param {Function} toneMappingNode - The tone mapping node function.
  39096. * @param {number} toneMapping - The tone mapping.
  39097. */
  39098. addToneMapping( toneMappingNode, toneMapping ) {
  39099. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  39100. }
  39101. /**
  39102. * Returns a tone mapping node function for a tone mapping technique (constant).
  39103. *
  39104. * @param {number} toneMapping - The tone mapping.
  39105. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  39106. */
  39107. getToneMappingFunction( toneMapping ) {
  39108. return this.toneMappingNodes.get( toneMapping ) || null;
  39109. }
  39110. /**
  39111. * Returns a node material class definition for a material type.
  39112. *
  39113. * @param {string} materialType - The material type.
  39114. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  39115. */
  39116. getMaterialNodeClass( materialType ) {
  39117. return this.materialNodes.get( materialType ) || null;
  39118. }
  39119. /**
  39120. * Adds a node material class definition for a given material type.
  39121. *
  39122. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  39123. * @param {string} materialClassType - The material type.
  39124. */
  39125. addMaterial( materialNodeClass, materialClassType ) {
  39126. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  39127. }
  39128. /**
  39129. * Returns a light node class definition for a light class definition.
  39130. *
  39131. * @param {Light.constructor} light - The light class definition.
  39132. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  39133. */
  39134. getLightNodeClass( light ) {
  39135. return this.lightNodes.get( light ) || null;
  39136. }
  39137. /**
  39138. * Adds a light node class definition for a given light class definition.
  39139. *
  39140. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  39141. * @param {Light.constructor} lightClass - The light class definition.
  39142. */
  39143. addLight( lightNodeClass, lightClass ) {
  39144. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  39145. }
  39146. /**
  39147. * Adds a node class definition for the given type to the provided type library.
  39148. *
  39149. * @param {Node.constructor} nodeClass - The node class definition.
  39150. * @param {number|string} type - The object type.
  39151. * @param {Map<number|string,Node.constructor>} library - The type library.
  39152. */
  39153. addType( nodeClass, type, library ) {
  39154. if ( library.has( type ) ) {
  39155. warn( `Redefinition of node ${ type }` );
  39156. return;
  39157. }
  39158. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39159. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  39160. library.set( type, nodeClass );
  39161. }
  39162. /**
  39163. * Adds a node class definition for the given class definition to the provided type library.
  39164. *
  39165. * @param {Node.constructor} nodeClass - The node class definition.
  39166. * @param {Node.constructor} baseClass - The class definition.
  39167. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  39168. */
  39169. addClass( nodeClass, baseClass, library ) {
  39170. if ( library.has( baseClass ) ) {
  39171. warn( `Redefinition of node ${ baseClass.name }` );
  39172. return;
  39173. }
  39174. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39175. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  39176. library.set( baseClass, nodeClass );
  39177. }
  39178. }
  39179. const _defaultLights = /*@__PURE__*/ new LightsNode();
  39180. const _chainKeys = [];
  39181. /**
  39182. * This renderer module manages the lights nodes which are unique
  39183. * per scene and camera combination.
  39184. *
  39185. * The lights node itself is later configured in the render list
  39186. * with the actual lights from the scene.
  39187. *
  39188. * @private
  39189. * @augments ChainMap
  39190. */
  39191. class Lighting extends ChainMap {
  39192. /**
  39193. * Constructs a lighting management component.
  39194. */
  39195. constructor() {
  39196. super();
  39197. }
  39198. /**
  39199. * Creates a new lights node for the given array of lights.
  39200. *
  39201. * @param {Array<Light>} lights - The render object.
  39202. * @return {LightsNode} The lights node.
  39203. */
  39204. createNode( lights = [] ) {
  39205. return new LightsNode().setLights( lights );
  39206. }
  39207. /**
  39208. * Returns a lights node for the given scene and camera.
  39209. *
  39210. * @param {Scene} scene - The scene.
  39211. * @param {Camera} camera - The camera.
  39212. * @return {LightsNode} The lights node.
  39213. */
  39214. getNode( scene, camera ) {
  39215. // ignore post-processing
  39216. if ( scene.isQuadMesh ) return _defaultLights;
  39217. _chainKeys[ 0 ] = scene;
  39218. _chainKeys[ 1 ] = camera;
  39219. let node = this.get( _chainKeys );
  39220. if ( node === undefined ) {
  39221. node = this.createNode();
  39222. this.set( _chainKeys, node );
  39223. }
  39224. _chainKeys.length = 0;
  39225. return node;
  39226. }
  39227. }
  39228. /**
  39229. * A special type of render target that is used when rendering
  39230. * with the WebXR Device API.
  39231. *
  39232. * @private
  39233. * @augments RenderTarget
  39234. */
  39235. class XRRenderTarget extends RenderTarget {
  39236. /**
  39237. * Constructs a new XR render target.
  39238. *
  39239. * @param {number} [width=1] - The width of the render target.
  39240. * @param {number} [height=1] - The height of the render target.
  39241. * @param {Object} [options={}] - The configuration options.
  39242. */
  39243. constructor( width = 1, height = 1, options = {} ) {
  39244. super( width, height, options );
  39245. /**
  39246. * This flag can be used for type testing.
  39247. *
  39248. * @type {boolean}
  39249. * @readonly
  39250. * @default true
  39251. */
  39252. this.isXRRenderTarget = true;
  39253. /**
  39254. * Whether the attachments of the render target
  39255. * are defined by external textures. This flag is
  39256. * set to `true` when using the WebXR Layers API.
  39257. *
  39258. * @private
  39259. * @type {boolean}
  39260. * @default false
  39261. */
  39262. this._hasExternalTextures = false;
  39263. /**
  39264. * Whether a depth buffer should automatically be allocated
  39265. * for this XR render target or not.
  39266. *
  39267. * Allocating a depth buffer is the default behavior of XR render
  39268. * targets. However, when using the WebXR Layers API, this flag
  39269. * must be set to `false` when the `ignoreDepthValues` property of
  39270. * the projection layers evaluates to `false`.
  39271. *
  39272. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  39273. *
  39274. * @private
  39275. * @type {boolean}
  39276. * @default true
  39277. */
  39278. this._autoAllocateDepthBuffer = true;
  39279. /**
  39280. * Whether this render target is associated with a XRWebGLLayer.
  39281. *
  39282. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  39283. * this means that you don't have access to its bound color,
  39284. * stencil and depth buffers. We need to handle this framebuffer
  39285. * differently since its textures are always bound.
  39286. *
  39287. * @private
  39288. * @type {boolean}
  39289. * @default false
  39290. * */
  39291. this._isOpaqueFramebuffer = false;
  39292. }
  39293. copy( source ) {
  39294. super.copy( source );
  39295. this._hasExternalTextures = source._hasExternalTextures;
  39296. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  39297. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  39298. return this;
  39299. }
  39300. }
  39301. const _cameraLPos = /*@__PURE__*/ new Vector3();
  39302. const _cameraRPos = /*@__PURE__*/ new Vector3();
  39303. /**
  39304. * The XR manager is built on top of the WebXR Device API to
  39305. * manage XR sessions with `WebGPURenderer`.
  39306. *
  39307. * XR is currently only supported with a WebGL 2 backend.
  39308. *
  39309. * @augments EventDispatcher
  39310. */
  39311. class XRManager extends EventDispatcher {
  39312. /**
  39313. * Constructs a new XR manager.
  39314. *
  39315. * @param {Renderer} renderer - The renderer.
  39316. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  39317. */
  39318. constructor( renderer, multiview = false ) {
  39319. super();
  39320. /**
  39321. * This flag globally enables XR rendering.
  39322. *
  39323. * @type {boolean}
  39324. * @default false
  39325. */
  39326. this.enabled = false;
  39327. /**
  39328. * Whether the XR device is currently presenting or not.
  39329. *
  39330. * @type {boolean}
  39331. * @default false
  39332. * @readonly
  39333. */
  39334. this.isPresenting = false;
  39335. /**
  39336. * Whether the XR camera should automatically be updated or not.
  39337. *
  39338. * @type {boolean}
  39339. * @default true
  39340. */
  39341. this.cameraAutoUpdate = true;
  39342. /**
  39343. * The renderer.
  39344. *
  39345. * @private
  39346. * @type {Renderer}
  39347. */
  39348. this._renderer = renderer;
  39349. // camera
  39350. /**
  39351. * Represents the camera for the left eye.
  39352. *
  39353. * @private
  39354. * @type {PerspectiveCamera}
  39355. */
  39356. this._cameraL = new PerspectiveCamera();
  39357. this._cameraL.viewport = new Vector4();
  39358. /**
  39359. * Represents the camera for the right eye.
  39360. *
  39361. * @private
  39362. * @type {PerspectiveCamera}
  39363. */
  39364. this._cameraR = new PerspectiveCamera();
  39365. this._cameraR.viewport = new Vector4();
  39366. /**
  39367. * A list of cameras used for rendering the XR views.
  39368. *
  39369. * @private
  39370. * @type {Array<Camera>}
  39371. */
  39372. this._cameras = [ this._cameraL, this._cameraR ];
  39373. /**
  39374. * The main XR camera.
  39375. *
  39376. * @private
  39377. * @type {ArrayCamera}
  39378. */
  39379. this._cameraXR = new ArrayCamera();
  39380. /**
  39381. * The current near value of the XR camera.
  39382. *
  39383. * @private
  39384. * @type {?number}
  39385. * @default null
  39386. */
  39387. this._currentDepthNear = null;
  39388. /**
  39389. * The current far value of the XR camera.
  39390. *
  39391. * @private
  39392. * @type {?number}
  39393. * @default null
  39394. */
  39395. this._currentDepthFar = null;
  39396. /**
  39397. * A list of WebXR controllers requested by the application.
  39398. *
  39399. * @private
  39400. * @type {Array<WebXRController>}
  39401. */
  39402. this._controllers = [];
  39403. /**
  39404. * A list of XR input source. Each input source belongs to
  39405. * an instance of WebXRController.
  39406. *
  39407. * @private
  39408. * @type {Array<XRInputSource?>}
  39409. */
  39410. this._controllerInputSources = [];
  39411. /**
  39412. * The XR render target that represents the rendering destination
  39413. * during an active XR session.
  39414. *
  39415. * @private
  39416. * @type {?RenderTarget}
  39417. * @default null
  39418. */
  39419. this._xrRenderTarget = null;
  39420. /**
  39421. * An array holding all the non-projection layers
  39422. *
  39423. * @private
  39424. * @type {Array<Object>}
  39425. * @default []
  39426. */
  39427. this._layers = [];
  39428. /**
  39429. * Whether the XR session uses layers.
  39430. *
  39431. * @private
  39432. * @type {boolean}
  39433. * @default false
  39434. */
  39435. this._sessionUsesLayers = false;
  39436. /**
  39437. * Whether the device supports binding gl objects.
  39438. *
  39439. * @private
  39440. * @type {boolean}
  39441. * @readonly
  39442. */
  39443. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  39444. this._frameBufferTargets = null;
  39445. /**
  39446. * Helper function to create native WebXR Layer.
  39447. *
  39448. * @private
  39449. * @type {Function}
  39450. */
  39451. this._createXRLayer = createXRLayer.bind( this );
  39452. /**
  39453. * The current WebGL context.
  39454. *
  39455. * @private
  39456. * @type {?WebGL2RenderingContext}
  39457. * @default null
  39458. */
  39459. this._gl = null;
  39460. /**
  39461. * The current animation context.
  39462. *
  39463. * @private
  39464. * @type {?Window}
  39465. * @default null
  39466. */
  39467. this._currentAnimationContext = null;
  39468. /**
  39469. * The current animation loop.
  39470. *
  39471. * @private
  39472. * @type {?Function}
  39473. * @default null
  39474. */
  39475. this._currentAnimationLoop = null;
  39476. /**
  39477. * The current pixel ratio.
  39478. *
  39479. * @private
  39480. * @type {?number}
  39481. * @default null
  39482. */
  39483. this._currentPixelRatio = null;
  39484. /**
  39485. * The current size of the renderer's canvas
  39486. * in logical pixel unit.
  39487. *
  39488. * @private
  39489. * @type {Vector2}
  39490. */
  39491. this._currentSize = new Vector2();
  39492. /**
  39493. * The default event listener for handling events inside a XR session.
  39494. *
  39495. * @private
  39496. * @type {Function}
  39497. */
  39498. this._onSessionEvent = onSessionEvent.bind( this );
  39499. /**
  39500. * The event listener for handling the end of a XR session.
  39501. *
  39502. * @private
  39503. * @type {Function}
  39504. */
  39505. this._onSessionEnd = onSessionEnd.bind( this );
  39506. /**
  39507. * The event listener for handling the `inputsourceschange` event.
  39508. *
  39509. * @private
  39510. * @type {Function}
  39511. */
  39512. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  39513. /**
  39514. * The animation loop which is used as a replacement for the default
  39515. * animation loop of the application. It is only used when a XR session
  39516. * is active.
  39517. *
  39518. * @private
  39519. * @type {Function}
  39520. */
  39521. this._onAnimationFrame = onAnimationFrame.bind( this );
  39522. /**
  39523. * The current XR reference space.
  39524. *
  39525. * @private
  39526. * @type {?XRReferenceSpace}
  39527. * @default null
  39528. */
  39529. this._referenceSpace = null;
  39530. /**
  39531. * The current XR reference space type.
  39532. *
  39533. * @private
  39534. * @type {XRReferenceSpaceType}
  39535. * @default 'local-floor'
  39536. */
  39537. this._referenceSpaceType = 'local-floor';
  39538. /**
  39539. * A custom reference space defined by the application.
  39540. *
  39541. * @private
  39542. * @type {?XRReferenceSpace}
  39543. * @default null
  39544. */
  39545. this._customReferenceSpace = null;
  39546. /**
  39547. * The framebuffer scale factor.
  39548. *
  39549. * @private
  39550. * @type {number}
  39551. * @default 1
  39552. */
  39553. this._framebufferScaleFactor = 1;
  39554. /**
  39555. * The foveation factor.
  39556. *
  39557. * @private
  39558. * @type {number}
  39559. * @default 1
  39560. */
  39561. this._foveation = 1.0;
  39562. /**
  39563. * A reference to the current XR session.
  39564. *
  39565. * @private
  39566. * @type {?XRSession}
  39567. * @default null
  39568. */
  39569. this._session = null;
  39570. /**
  39571. * A reference to the current XR base layer.
  39572. *
  39573. * @private
  39574. * @type {?XRWebGLLayer}
  39575. * @default null
  39576. */
  39577. this._glBaseLayer = null;
  39578. /**
  39579. * A reference to the current XR binding.
  39580. *
  39581. * @private
  39582. * @type {?XRWebGLBinding}
  39583. * @default null
  39584. */
  39585. this._glBinding = null;
  39586. /**
  39587. * A reference to the current XR projection layer.
  39588. *
  39589. * @private
  39590. * @type {?XRProjectionLayer}
  39591. * @default null
  39592. */
  39593. this._glProjLayer = null;
  39594. /**
  39595. * A reference to the current XR frame.
  39596. *
  39597. * @private
  39598. * @type {?XRFrame}
  39599. * @default null
  39600. */
  39601. this._xrFrame = null;
  39602. /**
  39603. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  39604. *
  39605. * Note: this does not represent XRSession explicitly requesting
  39606. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  39607. *
  39608. * @private
  39609. * @type {boolean}
  39610. * @readonly
  39611. */
  39612. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  39613. /**
  39614. * Whether the usage of multiview has been requested by the application or not.
  39615. *
  39616. * @private
  39617. * @type {boolean}
  39618. * @default false
  39619. * @readonly
  39620. */
  39621. this._useMultiviewIfPossible = multiview;
  39622. /**
  39623. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  39624. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  39625. *
  39626. * @private
  39627. * @type {boolean}
  39628. * @readonly
  39629. */
  39630. this._useMultiview = false;
  39631. }
  39632. /**
  39633. * Returns an instance of `THREE.Group` that represents the transformation
  39634. * of a XR controller in target ray space. The requested controller is defined
  39635. * by the given index.
  39636. *
  39637. * @param {number} index - The index of the XR controller.
  39638. * @return {Group} A group that represents the controller's transformation.
  39639. */
  39640. getController( index ) {
  39641. const controller = this._getController( index );
  39642. return controller.getTargetRaySpace();
  39643. }
  39644. /**
  39645. * Returns an instance of `THREE.Group` that represents the transformation
  39646. * of a XR controller in grip space. The requested controller is defined
  39647. * by the given index.
  39648. *
  39649. * @param {number} index - The index of the XR controller.
  39650. * @return {Group} A group that represents the controller's transformation.
  39651. */
  39652. getControllerGrip( index ) {
  39653. const controller = this._getController( index );
  39654. return controller.getGripSpace();
  39655. }
  39656. /**
  39657. * Returns an instance of `THREE.Group` that represents the transformation
  39658. * of a XR controller in hand space. The requested controller is defined
  39659. * by the given index.
  39660. *
  39661. * @param {number} index - The index of the XR controller.
  39662. * @return {Group} A group that represents the controller's transformation.
  39663. */
  39664. getHand( index ) {
  39665. const controller = this._getController( index );
  39666. return controller.getHandSpace();
  39667. }
  39668. /**
  39669. * Returns the foveation value.
  39670. *
  39671. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  39672. */
  39673. getFoveation() {
  39674. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  39675. return undefined;
  39676. }
  39677. return this._foveation;
  39678. }
  39679. /**
  39680. * Sets the foveation value.
  39681. *
  39682. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  39683. * and `1` means maximum foveation (the edges render at lower resolution).
  39684. */
  39685. setFoveation( foveation ) {
  39686. this._foveation = foveation;
  39687. if ( this._glProjLayer !== null ) {
  39688. this._glProjLayer.fixedFoveation = foveation;
  39689. }
  39690. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  39691. this._glBaseLayer.fixedFoveation = foveation;
  39692. }
  39693. }
  39694. /**
  39695. * Returns the framebuffer scale factor.
  39696. *
  39697. * @return {number} The framebuffer scale factor.
  39698. */
  39699. getFramebufferScaleFactor() {
  39700. return this._framebufferScaleFactor;
  39701. }
  39702. /**
  39703. * Sets the framebuffer scale factor.
  39704. *
  39705. * This method can not be used during a XR session.
  39706. *
  39707. * @param {number} factor - The framebuffer scale factor.
  39708. */
  39709. setFramebufferScaleFactor( factor ) {
  39710. this._framebufferScaleFactor = factor;
  39711. if ( this.isPresenting === true ) {
  39712. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  39713. }
  39714. }
  39715. /**
  39716. * Returns the reference space type.
  39717. *
  39718. * @return {XRReferenceSpaceType} The reference space type.
  39719. */
  39720. getReferenceSpaceType() {
  39721. return this._referenceSpaceType;
  39722. }
  39723. /**
  39724. * Sets the reference space type.
  39725. *
  39726. * This method can not be used during a XR session.
  39727. *
  39728. * @param {XRReferenceSpaceType} type - The reference space type.
  39729. */
  39730. setReferenceSpaceType( type ) {
  39731. this._referenceSpaceType = type;
  39732. if ( this.isPresenting === true ) {
  39733. warn( 'XRManager: Cannot change reference space type while presenting.' );
  39734. }
  39735. }
  39736. /**
  39737. * Returns the XR reference space.
  39738. *
  39739. * @return {XRReferenceSpace} The XR reference space.
  39740. */
  39741. getReferenceSpace() {
  39742. return this._customReferenceSpace || this._referenceSpace;
  39743. }
  39744. /**
  39745. * Sets a custom XR reference space.
  39746. *
  39747. * @param {XRReferenceSpace} space - The XR reference space.
  39748. */
  39749. setReferenceSpace( space ) {
  39750. this._customReferenceSpace = space;
  39751. }
  39752. /**
  39753. * Returns the XR camera.
  39754. *
  39755. * @return {ArrayCamera} The XR camera.
  39756. */
  39757. getCamera() {
  39758. return this._cameraXR;
  39759. }
  39760. /**
  39761. * Returns the environment blend mode from the current XR session.
  39762. *
  39763. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  39764. */
  39765. getEnvironmentBlendMode() {
  39766. if ( this._session !== null ) {
  39767. return this._session.environmentBlendMode;
  39768. }
  39769. }
  39770. /**
  39771. * Returns the current XR binding.
  39772. *
  39773. * Creates a new binding if needed and the browser is
  39774. * capable of doing so.
  39775. *
  39776. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  39777. */
  39778. getBinding() {
  39779. if ( this._glBinding === null && this._supportsGlBinding ) {
  39780. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  39781. }
  39782. return this._glBinding;
  39783. }
  39784. /**
  39785. * Returns the current XR frame.
  39786. *
  39787. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  39788. */
  39789. getFrame() {
  39790. return this._xrFrame;
  39791. }
  39792. /**
  39793. * Returns `true` if the engine renders to a multiview target.
  39794. *
  39795. * @return {boolean} Whether the engine renders to a multiview render target or not.
  39796. */
  39797. useMultiview() {
  39798. return this._useMultiview;
  39799. }
  39800. /**
  39801. * This method can be used in XR applications to create a quadratic layer that presents a separate
  39802. * rendered scene.
  39803. *
  39804. * @param {number} width - The width of the layer plane in world units.
  39805. * @param {number} height - The height of the layer plane in world units.
  39806. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  39807. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  39808. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  39809. * @param {number} pixelheight - The height of the layer's render target in pixels.
  39810. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  39811. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  39812. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  39813. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  39814. */
  39815. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  39816. const geometry = new PlaneGeometry( width, height );
  39817. const renderTarget = new XRRenderTarget(
  39818. pixelwidth,
  39819. pixelheight,
  39820. {
  39821. format: RGBAFormat,
  39822. type: UnsignedByteType,
  39823. depthTexture: new DepthTexture(
  39824. pixelwidth,
  39825. pixelheight,
  39826. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  39827. undefined,
  39828. undefined,
  39829. undefined,
  39830. undefined,
  39831. undefined,
  39832. undefined,
  39833. attributes.stencil ? DepthStencilFormat : DepthFormat
  39834. ),
  39835. stencilBuffer: attributes.stencil,
  39836. resolveDepthBuffer: false,
  39837. resolveStencilBuffer: false
  39838. } );
  39839. renderTarget._autoAllocateDepthBuffer = true;
  39840. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  39841. material.map = renderTarget.texture;
  39842. material.map.offset.y = 1;
  39843. material.map.repeat.y = -1;
  39844. const plane = new Mesh( geometry, material );
  39845. plane.position.copy( translation );
  39846. plane.quaternion.copy( quaternion );
  39847. const layer = {
  39848. type: 'quad',
  39849. width: width,
  39850. height: height,
  39851. translation: translation,
  39852. quaternion: quaternion,
  39853. pixelwidth: pixelwidth,
  39854. pixelheight: pixelheight,
  39855. plane: plane,
  39856. material: material,
  39857. rendercall: rendercall,
  39858. renderTarget: renderTarget };
  39859. this._layers.push( layer );
  39860. if ( this._session !== null ) {
  39861. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  39862. layer.plane.material.blending = CustomBlending;
  39863. layer.plane.material.blendEquation = AddEquation;
  39864. layer.plane.material.blendSrc = ZeroFactor;
  39865. layer.plane.material.blendDst = ZeroFactor;
  39866. layer.xrlayer = this._createXRLayer( layer );
  39867. const xrlayers = this._session.renderState.layers;
  39868. xrlayers.unshift( layer.xrlayer );
  39869. this._session.updateRenderState( { layers: xrlayers } );
  39870. } else {
  39871. renderTarget.isXRRenderTarget = false;
  39872. }
  39873. return plane;
  39874. }
  39875. /**
  39876. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  39877. * rendered scene.
  39878. *
  39879. * @param {number} radius - The radius of the cylinder in world units.
  39880. * @param {number} centralAngle - The central angle of the cylinder in radians.
  39881. * @param {number} aspectratio - The aspect ratio.
  39882. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  39883. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  39884. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  39885. * @param {number} pixelheight - The height of the layer's render target in pixels.
  39886. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  39887. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  39888. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  39889. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  39890. */
  39891. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  39892. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  39893. const renderTarget = new XRRenderTarget(
  39894. pixelwidth,
  39895. pixelheight,
  39896. {
  39897. format: RGBAFormat,
  39898. type: UnsignedByteType,
  39899. depthTexture: new DepthTexture(
  39900. pixelwidth,
  39901. pixelheight,
  39902. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  39903. undefined,
  39904. undefined,
  39905. undefined,
  39906. undefined,
  39907. undefined,
  39908. undefined,
  39909. attributes.stencil ? DepthStencilFormat : DepthFormat
  39910. ),
  39911. stencilBuffer: attributes.stencil,
  39912. resolveDepthBuffer: false,
  39913. resolveStencilBuffer: false
  39914. } );
  39915. renderTarget._autoAllocateDepthBuffer = true;
  39916. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  39917. material.map = renderTarget.texture;
  39918. material.map.offset.y = 1;
  39919. material.map.repeat.y = -1;
  39920. const plane = new Mesh( geometry, material );
  39921. plane.position.copy( translation );
  39922. plane.quaternion.copy( quaternion );
  39923. const layer = {
  39924. type: 'cylinder',
  39925. radius: radius,
  39926. centralAngle: centralAngle,
  39927. aspectratio: aspectratio,
  39928. translation: translation,
  39929. quaternion: quaternion,
  39930. pixelwidth: pixelwidth,
  39931. pixelheight: pixelheight,
  39932. plane: plane,
  39933. material: material,
  39934. rendercall: rendercall,
  39935. renderTarget: renderTarget };
  39936. this._layers.push( layer );
  39937. if ( this._session !== null ) {
  39938. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  39939. layer.plane.material.blending = CustomBlending;
  39940. layer.plane.material.blendEquation = AddEquation;
  39941. layer.plane.material.blendSrc = ZeroFactor;
  39942. layer.plane.material.blendDst = ZeroFactor;
  39943. layer.xrlayer = this._createXRLayer( layer );
  39944. const xrlayers = this._session.renderState.layers;
  39945. xrlayers.unshift( layer.xrlayer );
  39946. this._session.updateRenderState( { layers: xrlayers } );
  39947. } else {
  39948. renderTarget.isXRRenderTarget = false;
  39949. }
  39950. return plane;
  39951. }
  39952. /**
  39953. * Renders the XR layers that have been previously added to the scene.
  39954. *
  39955. * This method is usually called in your animation loop before rendering
  39956. * the actual scene via `renderer.render( scene, camera );`.
  39957. */
  39958. renderLayers( ) {
  39959. const translationObject = new Vector3();
  39960. const quaternionObject = new Quaternion();
  39961. const renderer = this._renderer;
  39962. const wasPresenting = this.isPresenting;
  39963. const rendererOutputTarget = renderer.getOutputRenderTarget();
  39964. const rendererFramebufferTarget = renderer._frameBufferTarget;
  39965. this.isPresenting = false;
  39966. const rendererSize = new Vector2();
  39967. renderer.getSize( rendererSize );
  39968. const rendererQuad = renderer._quad;
  39969. for ( const layer of this._layers ) {
  39970. layer.renderTarget.isXRRenderTarget = this._session !== null;
  39971. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  39972. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  39973. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  39974. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  39975. renderer.backend.setXRRenderTargetTextures(
  39976. layer.renderTarget,
  39977. glSubImage.colorTexture,
  39978. undefined );
  39979. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  39980. renderer.setOutputRenderTarget( layer.renderTarget );
  39981. renderer.setRenderTarget( null );
  39982. renderer._frameBufferTarget = null;
  39983. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  39984. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  39985. if ( ! frameBufferTarget ) {
  39986. renderer._quad = new QuadMesh( new NodeMaterial() );
  39987. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  39988. } else {
  39989. renderer._frameBufferTarget = frameBufferTarget;
  39990. renderer._quad = quad;
  39991. }
  39992. layer.rendercall();
  39993. renderer._frameBufferTarget = null;
  39994. } else {
  39995. renderer.setRenderTarget( layer.renderTarget );
  39996. layer.rendercall();
  39997. }
  39998. }
  39999. renderer.setRenderTarget( null );
  40000. renderer.setOutputRenderTarget( rendererOutputTarget );
  40001. renderer._frameBufferTarget = rendererFramebufferTarget;
  40002. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  40003. renderer._quad = rendererQuad;
  40004. this.isPresenting = wasPresenting;
  40005. }
  40006. /**
  40007. * Returns the current XR session.
  40008. *
  40009. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  40010. */
  40011. getSession() {
  40012. return this._session;
  40013. }
  40014. /**
  40015. * After a XR session has been requested usually with one of the `*Button` modules, it
  40016. * is injected into the renderer with this method. This method triggers the start of
  40017. * the actual XR rendering.
  40018. *
  40019. * @async
  40020. * @param {XRSession} session - The XR session to set.
  40021. * @return {Promise} A Promise that resolves when the session has been set.
  40022. */
  40023. async setSession( session ) {
  40024. const renderer = this._renderer;
  40025. const backend = renderer.backend;
  40026. this._gl = renderer.getContext();
  40027. const gl = this._gl;
  40028. const attributes = gl.getContextAttributes();
  40029. this._session = session;
  40030. if ( session !== null ) {
  40031. 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.' );
  40032. session.addEventListener( 'select', this._onSessionEvent );
  40033. session.addEventListener( 'selectstart', this._onSessionEvent );
  40034. session.addEventListener( 'selectend', this._onSessionEvent );
  40035. session.addEventListener( 'squeeze', this._onSessionEvent );
  40036. session.addEventListener( 'squeezestart', this._onSessionEvent );
  40037. session.addEventListener( 'squeezeend', this._onSessionEvent );
  40038. session.addEventListener( 'end', this._onSessionEnd );
  40039. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40040. await backend.makeXRCompatible();
  40041. this._currentPixelRatio = renderer.getPixelRatio();
  40042. renderer.getSize( this._currentSize );
  40043. this._currentAnimationContext = renderer._animation.getContext();
  40044. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  40045. renderer._animation.stop();
  40046. //
  40047. if ( this._supportsLayers === true ) {
  40048. // default path using XRProjectionLayer
  40049. let depthFormat = null;
  40050. let depthType = null;
  40051. let glDepthFormat = null;
  40052. if ( renderer.depth ) {
  40053. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  40054. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  40055. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  40056. }
  40057. const projectionlayerInit = {
  40058. colorFormat: gl.RGBA8,
  40059. depthFormat: glDepthFormat,
  40060. scaleFactor: this._framebufferScaleFactor,
  40061. clearOnAccess: false
  40062. };
  40063. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  40064. projectionlayerInit.textureType = 'texture-array';
  40065. this._useMultiview = true;
  40066. }
  40067. this._glBinding = this.getBinding();
  40068. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  40069. const layersArray = [ glProjLayer ];
  40070. this._glProjLayer = glProjLayer;
  40071. renderer.setPixelRatio( 1 );
  40072. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  40073. const depth = this._useMultiview ? 2 : 1;
  40074. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  40075. this._xrRenderTarget = new XRRenderTarget(
  40076. glProjLayer.textureWidth,
  40077. glProjLayer.textureHeight,
  40078. {
  40079. format: RGBAFormat,
  40080. type: UnsignedByteType,
  40081. colorSpace: renderer.outputColorSpace,
  40082. depthTexture: depthTexture,
  40083. stencilBuffer: renderer.stencil,
  40084. samples: attributes.antialias ? 4 : 0,
  40085. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  40086. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  40087. depth: this._useMultiview ? 2 : 1,
  40088. multiview: this._useMultiview
  40089. } );
  40090. this._xrRenderTarget._hasExternalTextures = true;
  40091. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  40092. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  40093. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  40094. if ( this._sessionUsesLayers ) {
  40095. // switch layers to native
  40096. for ( const layer of this._layers ) {
  40097. // change material so it "punches" out a hole to show the XR Layer.
  40098. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  40099. layer.plane.material.blending = CustomBlending;
  40100. layer.plane.material.blendEquation = AddEquation;
  40101. layer.plane.material.blendSrc = ZeroFactor;
  40102. layer.plane.material.blendDst = ZeroFactor;
  40103. layer.xrlayer = this._createXRLayer( layer );
  40104. layersArray.unshift( layer.xrlayer );
  40105. }
  40106. }
  40107. session.updateRenderState( { layers: layersArray } );
  40108. } else {
  40109. // fallback to XRWebGLLayer
  40110. const layerInit = {
  40111. antialias: renderer.currentSamples > 0,
  40112. alpha: true,
  40113. depth: renderer.depth,
  40114. stencil: renderer.stencil,
  40115. framebufferScaleFactor: this.getFramebufferScaleFactor()
  40116. };
  40117. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  40118. this._glBaseLayer = glBaseLayer;
  40119. session.updateRenderState( { baseLayer: glBaseLayer } );
  40120. renderer.setPixelRatio( 1 );
  40121. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  40122. this._xrRenderTarget = new XRRenderTarget(
  40123. glBaseLayer.framebufferWidth,
  40124. glBaseLayer.framebufferHeight,
  40125. {
  40126. format: RGBAFormat,
  40127. type: UnsignedByteType,
  40128. colorSpace: renderer.outputColorSpace,
  40129. stencilBuffer: renderer.stencil,
  40130. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  40131. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  40132. }
  40133. );
  40134. this._xrRenderTarget._isOpaqueFramebuffer = true;
  40135. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  40136. }
  40137. //
  40138. this.setFoveation( this.getFoveation() );
  40139. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  40140. renderer._animation.setContext( session );
  40141. renderer._animation.start();
  40142. this.isPresenting = true;
  40143. this.dispatchEvent( { type: 'sessionstart' } );
  40144. }
  40145. }
  40146. /**
  40147. * This method is called by the renderer per frame and updates the XR camera
  40148. * and it sub cameras based on the given camera. The given camera is the "user"
  40149. * camera created on application level and used for non-XR rendering.
  40150. *
  40151. * @param {PerspectiveCamera} camera - The camera.
  40152. */
  40153. updateCamera( camera ) {
  40154. const session = this._session;
  40155. if ( session === null ) return;
  40156. const depthNear = camera.near;
  40157. const depthFar = camera.far;
  40158. const cameraXR = this._cameraXR;
  40159. const cameraL = this._cameraL;
  40160. const cameraR = this._cameraR;
  40161. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  40162. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  40163. cameraXR.isMultiViewCamera = this._useMultiview;
  40164. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  40165. // Note that the new renderState won't apply until the next frame. See #18320
  40166. session.updateRenderState( {
  40167. depthNear: cameraXR.near,
  40168. depthFar: cameraXR.far
  40169. } );
  40170. this._currentDepthNear = cameraXR.near;
  40171. this._currentDepthFar = cameraXR.far;
  40172. }
  40173. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  40174. cameraXR.layers.mask = camera.layers.mask | 0b110;
  40175. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  40176. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  40177. const parent = camera.parent;
  40178. const cameras = cameraXR.cameras;
  40179. updateCamera( cameraXR, parent );
  40180. for ( let i = 0; i < cameras.length; i ++ ) {
  40181. updateCamera( cameras[ i ], parent );
  40182. }
  40183. // update projection matrix for proper view frustum culling
  40184. if ( cameras.length === 2 ) {
  40185. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  40186. } else {
  40187. // assume single camera setup (AR)
  40188. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  40189. }
  40190. // update user camera and its children
  40191. updateUserCamera( camera, cameraXR, parent );
  40192. }
  40193. /**
  40194. * Returns a WebXR controller for the given controller index.
  40195. *
  40196. * @private
  40197. * @param {number} index - The controller index.
  40198. * @return {WebXRController} The XR controller.
  40199. */
  40200. _getController( index ) {
  40201. let controller = this._controllers[ index ];
  40202. if ( controller === undefined ) {
  40203. controller = new WebXRController();
  40204. this._controllers[ index ] = controller;
  40205. }
  40206. return controller;
  40207. }
  40208. }
  40209. /**
  40210. * Assumes 2 cameras that are parallel and share an X-axis, and that
  40211. * the cameras' projection and world matrices have already been set.
  40212. * And that near and far planes are identical for both cameras.
  40213. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  40214. *
  40215. * @param {ArrayCamera} camera - The camera to update.
  40216. * @param {PerspectiveCamera} cameraL - The left camera.
  40217. * @param {PerspectiveCamera} cameraR - The right camera.
  40218. */
  40219. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  40220. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  40221. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  40222. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  40223. const projL = cameraL.projectionMatrix.elements;
  40224. const projR = cameraR.projectionMatrix.elements;
  40225. // VR systems will have identical far and near planes, and
  40226. // most likely identical top and bottom frustum extents.
  40227. // Use the left camera for these values.
  40228. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  40229. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  40230. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  40231. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  40232. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  40233. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  40234. const left = near * leftFov;
  40235. const right = near * rightFov;
  40236. // Calculate the new camera's position offset from the
  40237. // left camera. xOffset should be roughly half `ipd`.
  40238. const zOffset = ipd / ( - leftFov + rightFov );
  40239. const xOffset = zOffset * - leftFov;
  40240. // TODO: Better way to apply this offset?
  40241. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  40242. camera.translateX( xOffset );
  40243. camera.translateZ( zOffset );
  40244. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  40245. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40246. // Check if the projection uses an infinite far plane.
  40247. if ( projL[ 10 ] === -1 ) {
  40248. // Use the projection matrix from the left eye.
  40249. // The camera offset is sufficient to include the view volumes
  40250. // of both eyes (assuming symmetric projections).
  40251. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  40252. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  40253. } else {
  40254. // Find the union of the frustum values of the cameras and scale
  40255. // the values so that the near plane's position does not change in world space,
  40256. // although must now be relative to the new union camera.
  40257. const near2 = near + zOffset;
  40258. const far2 = far + zOffset;
  40259. const left2 = left - xOffset;
  40260. const right2 = right + ( ipd - xOffset );
  40261. const top2 = topFov * far / far2 * near2;
  40262. const bottom2 = bottomFov * far / far2 * near2;
  40263. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  40264. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40265. }
  40266. }
  40267. /**
  40268. * Updates the world matrices for the given camera based on the parent 3D object.
  40269. *
  40270. * @inner
  40271. * @param {Camera} camera - The camera to update.
  40272. * @param {Object3D} parent - The parent 3D object.
  40273. */
  40274. function updateCamera( camera, parent ) {
  40275. if ( parent === null ) {
  40276. camera.matrixWorld.copy( camera.matrix );
  40277. } else {
  40278. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  40279. }
  40280. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40281. }
  40282. /**
  40283. * Updates the given camera with the transformation of the XR camera and parent object.
  40284. *
  40285. * @inner
  40286. * @param {Camera} camera - The camera to update.
  40287. * @param {ArrayCamera} cameraXR - The XR camera.
  40288. * @param {Object3D} parent - The parent 3D object.
  40289. */
  40290. function updateUserCamera( camera, cameraXR, parent ) {
  40291. if ( parent === null ) {
  40292. camera.matrix.copy( cameraXR.matrixWorld );
  40293. } else {
  40294. camera.matrix.copy( parent.matrixWorld );
  40295. camera.matrix.invert();
  40296. camera.matrix.multiply( cameraXR.matrixWorld );
  40297. }
  40298. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40299. camera.updateMatrixWorld( true );
  40300. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  40301. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  40302. if ( camera.isPerspectiveCamera ) {
  40303. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  40304. camera.zoom = 1;
  40305. }
  40306. }
  40307. function onSessionEvent( event ) {
  40308. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  40309. if ( controllerIndex === -1 ) {
  40310. return;
  40311. }
  40312. const controller = this._controllers[ controllerIndex ];
  40313. if ( controller !== undefined ) {
  40314. const referenceSpace = this.getReferenceSpace();
  40315. controller.update( event.inputSource, event.frame, referenceSpace );
  40316. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  40317. }
  40318. }
  40319. function onSessionEnd() {
  40320. const session = this._session;
  40321. const renderer = this._renderer;
  40322. session.removeEventListener( 'select', this._onSessionEvent );
  40323. session.removeEventListener( 'selectstart', this._onSessionEvent );
  40324. session.removeEventListener( 'selectend', this._onSessionEvent );
  40325. session.removeEventListener( 'squeeze', this._onSessionEvent );
  40326. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  40327. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  40328. session.removeEventListener( 'end', this._onSessionEnd );
  40329. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40330. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40331. const inputSource = this._controllerInputSources[ i ];
  40332. if ( inputSource === null ) continue;
  40333. this._controllerInputSources[ i ] = null;
  40334. this._controllers[ i ].disconnect( inputSource );
  40335. }
  40336. this._currentDepthNear = null;
  40337. this._currentDepthFar = null;
  40338. // restore framebuffer/rendering state
  40339. renderer._resetXRState();
  40340. this._session = null;
  40341. this._xrRenderTarget = null;
  40342. this._glBinding = null;
  40343. this._glBaseLayer = null;
  40344. this._glProjLayer = null;
  40345. // switch layers back to emulated
  40346. if ( this._sessionUsesLayers === true ) {
  40347. for ( const layer of this._layers ) {
  40348. // Recreate layer render target to reset state
  40349. layer.renderTarget = new XRRenderTarget(
  40350. layer.pixelwidth,
  40351. layer.pixelheight,
  40352. {
  40353. format: RGBAFormat,
  40354. type: UnsignedByteType,
  40355. depthTexture: new DepthTexture(
  40356. layer.pixelwidth,
  40357. layer.pixelheight,
  40358. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  40359. undefined,
  40360. undefined,
  40361. undefined,
  40362. undefined,
  40363. undefined,
  40364. undefined,
  40365. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  40366. ),
  40367. stencilBuffer: layer.stencilBuffer,
  40368. resolveDepthBuffer: false,
  40369. resolveStencilBuffer: false
  40370. } );
  40371. layer.renderTarget.isXRRenderTarget = false;
  40372. layer.plane.material = layer.material;
  40373. layer.material.map = layer.renderTarget.texture;
  40374. layer.material.map.offset.y = 1;
  40375. layer.material.map.repeat.y = -1;
  40376. delete layer.xrlayer;
  40377. }
  40378. }
  40379. //
  40380. this.isPresenting = false;
  40381. this._useMultiview = false;
  40382. renderer._animation.stop();
  40383. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  40384. renderer._animation.setContext( this._currentAnimationContext );
  40385. renderer._animation.start();
  40386. renderer.setPixelRatio( this._currentPixelRatio );
  40387. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  40388. this.dispatchEvent( { type: 'sessionend' } );
  40389. }
  40390. function onInputSourcesChange( event ) {
  40391. const controllers = this._controllers;
  40392. const controllerInputSources = this._controllerInputSources;
  40393. // Notify disconnected
  40394. for ( let i = 0; i < event.removed.length; i ++ ) {
  40395. const inputSource = event.removed[ i ];
  40396. const index = controllerInputSources.indexOf( inputSource );
  40397. if ( index >= 0 ) {
  40398. controllerInputSources[ index ] = null;
  40399. controllers[ index ].disconnect( inputSource );
  40400. }
  40401. }
  40402. // Notify connected
  40403. for ( let i = 0; i < event.added.length; i ++ ) {
  40404. const inputSource = event.added[ i ];
  40405. let controllerIndex = controllerInputSources.indexOf( inputSource );
  40406. if ( controllerIndex === -1 ) {
  40407. // Assign input source a controller that currently has no input source
  40408. for ( let i = 0; i < controllers.length; i ++ ) {
  40409. if ( i >= controllerInputSources.length ) {
  40410. controllerInputSources.push( inputSource );
  40411. controllerIndex = i;
  40412. break;
  40413. } else if ( controllerInputSources[ i ] === null ) {
  40414. controllerInputSources[ i ] = inputSource;
  40415. controllerIndex = i;
  40416. break;
  40417. }
  40418. }
  40419. // If all controllers do currently receive input we ignore new ones
  40420. if ( controllerIndex === -1 ) break;
  40421. }
  40422. const controller = controllers[ controllerIndex ];
  40423. if ( controller ) {
  40424. controller.connect( inputSource );
  40425. }
  40426. }
  40427. }
  40428. // Creation method for native WebXR layers
  40429. function createXRLayer( layer ) {
  40430. if ( layer.type === 'quad' ) {
  40431. return this._glBinding.createQuadLayer( {
  40432. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40433. width: layer.width / 2,
  40434. height: layer.height / 2,
  40435. space: this._referenceSpace,
  40436. viewPixelWidth: layer.pixelwidth,
  40437. viewPixelHeight: layer.pixelheight,
  40438. clearOnAccess: false
  40439. } );
  40440. } else {
  40441. return this._glBinding.createCylinderLayer( {
  40442. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40443. radius: layer.radius,
  40444. centralAngle: layer.centralAngle,
  40445. aspectRatio: layer.aspectRatio,
  40446. space: this._referenceSpace,
  40447. viewPixelWidth: layer.pixelwidth,
  40448. viewPixelHeight: layer.pixelheight,
  40449. clearOnAccess: false
  40450. } );
  40451. }
  40452. }
  40453. // Animation Loop
  40454. function onAnimationFrame( time, frame ) {
  40455. if ( frame === undefined ) return;
  40456. const cameraXR = this._cameraXR;
  40457. const renderer = this._renderer;
  40458. const backend = renderer.backend;
  40459. const glBaseLayer = this._glBaseLayer;
  40460. const referenceSpace = this.getReferenceSpace();
  40461. const pose = frame.getViewerPose( referenceSpace );
  40462. this._xrFrame = frame;
  40463. if ( pose !== null ) {
  40464. const views = pose.views;
  40465. if ( this._glBaseLayer !== null ) {
  40466. backend.setXRTarget( glBaseLayer.framebuffer );
  40467. }
  40468. let cameraXRNeedsUpdate = false;
  40469. // check if it's necessary to rebuild cameraXR's camera list
  40470. if ( views.length !== cameraXR.cameras.length ) {
  40471. cameraXR.cameras.length = 0;
  40472. cameraXRNeedsUpdate = true;
  40473. }
  40474. for ( let i = 0; i < views.length; i ++ ) {
  40475. const view = views[ i ];
  40476. let viewport;
  40477. if ( this._supportsLayers === true ) {
  40478. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  40479. viewport = glSubImage.viewport;
  40480. // For side-by-side projection, we only produce a single texture for both eyes.
  40481. if ( i === 0 ) {
  40482. backend.setXRRenderTargetTextures(
  40483. this._xrRenderTarget,
  40484. glSubImage.colorTexture,
  40485. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  40486. );
  40487. }
  40488. } else {
  40489. viewport = glBaseLayer.getViewport( view );
  40490. }
  40491. let camera = this._cameras[ i ];
  40492. if ( camera === undefined ) {
  40493. camera = new PerspectiveCamera();
  40494. camera.layers.enable( i );
  40495. camera.viewport = new Vector4();
  40496. this._cameras[ i ] = camera;
  40497. }
  40498. camera.matrix.fromArray( view.transform.matrix );
  40499. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40500. camera.projectionMatrix.fromArray( view.projectionMatrix );
  40501. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40502. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  40503. if ( i === 0 ) {
  40504. cameraXR.matrix.copy( camera.matrix );
  40505. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  40506. }
  40507. if ( cameraXRNeedsUpdate === true ) {
  40508. cameraXR.cameras.push( camera );
  40509. }
  40510. }
  40511. renderer.setOutputRenderTarget( this._xrRenderTarget );
  40512. }
  40513. //
  40514. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40515. const inputSource = this._controllerInputSources[ i ];
  40516. const controller = this._controllers[ i ];
  40517. if ( inputSource !== null && controller !== undefined ) {
  40518. controller.update( inputSource, frame, referenceSpace );
  40519. }
  40520. }
  40521. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  40522. if ( frame.detectedPlanes ) {
  40523. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  40524. }
  40525. this._xrFrame = null;
  40526. }
  40527. /**
  40528. * CanvasTarget is a class that represents the final output destination of the renderer.
  40529. *
  40530. * @augments EventDispatcher
  40531. */
  40532. class CanvasTarget extends EventDispatcher {
  40533. /**
  40534. * Constructs a new CanvasTarget.
  40535. *
  40536. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  40537. */
  40538. constructor( domElement ) {
  40539. super();
  40540. /**
  40541. * A reference to the canvas element the renderer is drawing to.
  40542. * This value of this property will automatically be created by
  40543. * the renderer.
  40544. *
  40545. * @type {HTMLCanvasElement|OffscreenCanvas}
  40546. */
  40547. this.domElement = domElement;
  40548. /**
  40549. * The renderer's pixel ratio.
  40550. *
  40551. * @private
  40552. * @type {number}
  40553. * @default 1
  40554. */
  40555. this._pixelRatio = 1;
  40556. /**
  40557. * The width of the renderer's default framebuffer in logical pixel unit.
  40558. *
  40559. * @private
  40560. * @type {number}
  40561. */
  40562. this._width = this.domElement.width;
  40563. /**
  40564. * The height of the renderer's default framebuffer in logical pixel unit.
  40565. *
  40566. * @private
  40567. * @type {number}
  40568. */
  40569. this._height = this.domElement.height;
  40570. /**
  40571. * The viewport of the renderer in logical pixel unit.
  40572. *
  40573. * @private
  40574. * @type {Vector4}
  40575. */
  40576. this._viewport = new Vector4( 0, 0, this._width, this._height );
  40577. /**
  40578. * The scissor rectangle of the renderer in logical pixel unit.
  40579. *
  40580. * @private
  40581. * @type {Vector4}
  40582. */
  40583. this._scissor = new Vector4( 0, 0, this._width, this._height );
  40584. /**
  40585. * Whether the scissor test should be enabled or not.
  40586. *
  40587. * @private
  40588. * @type {boolean}
  40589. */
  40590. this._scissorTest = false;
  40591. /**
  40592. * The color texture of the default framebuffer.
  40593. *
  40594. * @type {FramebufferTexture}
  40595. */
  40596. this.colorTexture = new FramebufferTexture();
  40597. /**
  40598. * The depth texture of the default framebuffer.
  40599. *
  40600. * @type {DepthTexture}
  40601. */
  40602. this.depthTexture = new DepthTexture();
  40603. }
  40604. /**
  40605. * Returns the pixel ratio.
  40606. *
  40607. * @return {number} The pixel ratio.
  40608. */
  40609. getPixelRatio() {
  40610. return this._pixelRatio;
  40611. }
  40612. /**
  40613. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  40614. *
  40615. * @param {Vector2} target - The method writes the result in this target object.
  40616. * @return {Vector2} The drawing buffer size.
  40617. */
  40618. getDrawingBufferSize( target ) {
  40619. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  40620. }
  40621. /**
  40622. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  40623. *
  40624. * @param {Vector2} target - The method writes the result in this target object.
  40625. * @return {Vector2} The renderer's size in logical pixels.
  40626. */
  40627. getSize( target ) {
  40628. return target.set( this._width, this._height );
  40629. }
  40630. /**
  40631. * Sets the given pixel ratio and resizes the canvas if necessary.
  40632. *
  40633. * @param {number} [value=1] - The pixel ratio.
  40634. */
  40635. setPixelRatio( value = 1 ) {
  40636. if ( this._pixelRatio === value ) return;
  40637. this._pixelRatio = value;
  40638. this.setSize( this._width, this._height, false );
  40639. }
  40640. /**
  40641. * This method allows to define the drawing buffer size by specifying
  40642. * width, height and pixel ratio all at once. The size of the drawing
  40643. * buffer is computed with this formula:
  40644. * ```js
  40645. * size.x = width * pixelRatio;
  40646. * size.y = height * pixelRatio;
  40647. * ```
  40648. *
  40649. * @param {number} width - The width in logical pixels.
  40650. * @param {number} height - The height in logical pixels.
  40651. * @param {number} pixelRatio - The pixel ratio.
  40652. */
  40653. setDrawingBufferSize( width, height, pixelRatio ) {
  40654. // Renderer can't be resized while presenting in XR.
  40655. if ( this.xr && this.xr.isPresenting ) return;
  40656. this._width = width;
  40657. this._height = height;
  40658. this._pixelRatio = pixelRatio;
  40659. this.domElement.width = Math.floor( width * pixelRatio );
  40660. this.domElement.height = Math.floor( height * pixelRatio );
  40661. this.setViewport( 0, 0, width, height );
  40662. this._dispatchResize();
  40663. }
  40664. /**
  40665. * Sets the size of the renderer.
  40666. *
  40667. * @param {number} width - The width in logical pixels.
  40668. * @param {number} height - The height in logical pixels.
  40669. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  40670. */
  40671. setSize( width, height, updateStyle = true ) {
  40672. // Renderer can't be resized while presenting in XR.
  40673. if ( this.xr && this.xr.isPresenting ) return;
  40674. this._width = width;
  40675. this._height = height;
  40676. this.domElement.width = Math.floor( width * this._pixelRatio );
  40677. this.domElement.height = Math.floor( height * this._pixelRatio );
  40678. if ( updateStyle === true ) {
  40679. this.domElement.style.width = width + 'px';
  40680. this.domElement.style.height = height + 'px';
  40681. }
  40682. this.setViewport( 0, 0, width, height );
  40683. this._dispatchResize();
  40684. }
  40685. /**
  40686. * Returns the scissor rectangle.
  40687. *
  40688. * @param {Vector4} target - The method writes the result in this target object.
  40689. * @return {Vector4} The scissor rectangle.
  40690. */
  40691. getScissor( target ) {
  40692. const scissor = this._scissor;
  40693. target.x = scissor.x;
  40694. target.y = scissor.y;
  40695. target.width = scissor.width;
  40696. target.height = scissor.height;
  40697. return target;
  40698. }
  40699. /**
  40700. * Defines the scissor rectangle.
  40701. *
  40702. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  40703. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  40704. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  40705. * @param {number} width - The width of the scissor box in logical pixel unit.
  40706. * @param {number} height - The height of the scissor box in logical pixel unit.
  40707. */
  40708. setScissor( x, y, width, height ) {
  40709. const scissor = this._scissor;
  40710. if ( x.isVector4 ) {
  40711. scissor.copy( x );
  40712. } else {
  40713. scissor.set( x, y, width, height );
  40714. }
  40715. }
  40716. /**
  40717. * Returns the scissor test value.
  40718. *
  40719. * @return {boolean} Whether the scissor test should be enabled or not.
  40720. */
  40721. getScissorTest() {
  40722. return this._scissorTest;
  40723. }
  40724. /**
  40725. * Defines the scissor test.
  40726. *
  40727. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40728. */
  40729. setScissorTest( boolean ) {
  40730. this._scissorTest = boolean;
  40731. }
  40732. /**
  40733. * Returns the viewport definition.
  40734. *
  40735. * @param {Vector4} target - The method writes the result in this target object.
  40736. * @return {Vector4} The viewport definition.
  40737. */
  40738. getViewport( target ) {
  40739. return target.copy( this._viewport );
  40740. }
  40741. /**
  40742. * Defines the viewport.
  40743. *
  40744. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40745. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40746. * @param {number} width - The width of the viewport in logical pixel unit.
  40747. * @param {number} height - The height of the viewport in logical pixel unit.
  40748. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  40749. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  40750. */
  40751. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  40752. const viewport = this._viewport;
  40753. if ( x.isVector4 ) {
  40754. viewport.copy( x );
  40755. } else {
  40756. viewport.set( x, y, width, height );
  40757. }
  40758. viewport.minDepth = minDepth;
  40759. viewport.maxDepth = maxDepth;
  40760. }
  40761. /**
  40762. * Dispatches the resize event.
  40763. *
  40764. * @private
  40765. */
  40766. _dispatchResize() {
  40767. this.dispatchEvent( { type: 'resize' } );
  40768. }
  40769. /**
  40770. * Frees the GPU-related resources allocated by this instance. Call this
  40771. * method whenever this instance is no longer used in your app.
  40772. *
  40773. * @fires RenderTarget#dispose
  40774. */
  40775. dispose() {
  40776. this.dispatchEvent( { type: 'dispose' } );
  40777. }
  40778. }
  40779. const _scene = /*@__PURE__*/ new Scene();
  40780. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  40781. const _screen = /*@__PURE__*/ new Vector4();
  40782. const _frustum = /*@__PURE__*/ new Frustum();
  40783. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  40784. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  40785. const _vector4 = /*@__PURE__*/ new Vector4();
  40786. /**
  40787. * Base class for renderers.
  40788. */
  40789. class Renderer {
  40790. /**
  40791. * Renderer options.
  40792. *
  40793. * @typedef {Object} Renderer~Options
  40794. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  40795. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  40796. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  40797. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  40798. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  40799. * @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
  40800. * to overwrite the default.
  40801. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  40802. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  40803. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  40804. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  40805. */
  40806. /**
  40807. * Constructs a new renderer.
  40808. *
  40809. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  40810. * @param {Renderer~Options} [parameters] - The configuration parameter.
  40811. */
  40812. constructor( backend, parameters = {} ) {
  40813. /**
  40814. * This flag can be used for type testing.
  40815. *
  40816. * @type {boolean}
  40817. * @readonly
  40818. * @default true
  40819. */
  40820. this.isRenderer = true;
  40821. //
  40822. const {
  40823. logarithmicDepthBuffer = false,
  40824. alpha = true,
  40825. depth = true,
  40826. stencil = false,
  40827. antialias = false,
  40828. samples = 0,
  40829. getFallback = null,
  40830. colorBufferType = HalfFloatType,
  40831. multiview = false
  40832. } = parameters;
  40833. /**
  40834. * A reference to the current backend.
  40835. *
  40836. * @type {Backend}
  40837. */
  40838. this.backend = backend;
  40839. /**
  40840. * Whether the renderer should automatically clear the current rendering target
  40841. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  40842. * or the current bound render target (custom framebuffer).
  40843. *
  40844. * @type {boolean}
  40845. * @default true
  40846. */
  40847. this.autoClear = true;
  40848. /**
  40849. * When `autoClear` is set to `true`, this property defines whether the renderer
  40850. * should clear the color buffer.
  40851. *
  40852. * @type {boolean}
  40853. * @default true
  40854. */
  40855. this.autoClearColor = true;
  40856. /**
  40857. * When `autoClear` is set to `true`, this property defines whether the renderer
  40858. * should clear the depth buffer.
  40859. *
  40860. * @type {boolean}
  40861. * @default true
  40862. */
  40863. this.autoClearDepth = true;
  40864. /**
  40865. * When `autoClear` is set to `true`, this property defines whether the renderer
  40866. * should clear the stencil buffer.
  40867. *
  40868. * @type {boolean}
  40869. * @default true
  40870. */
  40871. this.autoClearStencil = true;
  40872. /**
  40873. * Whether the default framebuffer should be transparent or opaque.
  40874. *
  40875. * @type {boolean}
  40876. * @default true
  40877. */
  40878. this.alpha = alpha;
  40879. /**
  40880. * Whether logarithmic depth buffer is enabled or not.
  40881. *
  40882. * @type {boolean}
  40883. * @default false
  40884. */
  40885. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  40886. /**
  40887. * Defines the output color space of the renderer.
  40888. *
  40889. * @type {string}
  40890. * @default SRGBColorSpace
  40891. */
  40892. this.outputColorSpace = SRGBColorSpace;
  40893. /**
  40894. * Defines the tone mapping of the renderer.
  40895. *
  40896. * @type {number}
  40897. * @default NoToneMapping
  40898. */
  40899. this.toneMapping = NoToneMapping;
  40900. /**
  40901. * Defines the tone mapping exposure.
  40902. *
  40903. * @type {number}
  40904. * @default 1
  40905. */
  40906. this.toneMappingExposure = 1.0;
  40907. /**
  40908. * Whether the renderer should sort its render lists or not.
  40909. *
  40910. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  40911. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  40912. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  40913. * e.g. manually determining each object's rendering order.
  40914. *
  40915. * @type {boolean}
  40916. * @default true
  40917. */
  40918. this.sortObjects = true;
  40919. /**
  40920. * Whether the default framebuffer should have a depth buffer or not.
  40921. *
  40922. * @type {boolean}
  40923. * @default true
  40924. */
  40925. this.depth = depth;
  40926. /**
  40927. * Whether the default framebuffer should have a stencil buffer or not.
  40928. *
  40929. * @type {boolean}
  40930. * @default false
  40931. */
  40932. this.stencil = stencil;
  40933. /**
  40934. * Holds a series of statistical information about the GPU memory
  40935. * and the rendering process. Useful for debugging and monitoring.
  40936. *
  40937. * @type {Info}
  40938. */
  40939. this.info = new Info();
  40940. /**
  40941. * A global context node that stores override nodes for specific transformations or calculations.
  40942. * These nodes can be used to replace default behavior in the rendering pipeline.
  40943. *
  40944. * @type {ContextNode}
  40945. * @property {Object} value - The context value object.
  40946. */
  40947. this.contextNode = context();
  40948. /**
  40949. * The node library defines how certain library objects like materials, lights
  40950. * or tone mapping functions are mapped to node types. This is required since
  40951. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  40952. * be part of the scene graph, they are internally represented as nodes for
  40953. * further processing.
  40954. *
  40955. * @type {NodeLibrary}
  40956. */
  40957. this.library = new NodeLibrary();
  40958. /**
  40959. * A map-like data structure for managing lights.
  40960. *
  40961. * @type {Lighting}
  40962. */
  40963. this.lighting = new Lighting();
  40964. // internals
  40965. /**
  40966. * The number of MSAA samples.
  40967. *
  40968. * @private
  40969. * @type {number}
  40970. * @default 0
  40971. */
  40972. this._samples = samples || ( antialias === true ) ? 4 : 0;
  40973. /**
  40974. * OnCanvasTargetResize callback function.
  40975. *
  40976. * @private
  40977. * @type {Function}
  40978. */
  40979. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  40980. /**
  40981. * The canvas target for rendering.
  40982. *
  40983. * @private
  40984. * @type {CanvasTarget}
  40985. */
  40986. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  40987. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  40988. this._canvasTarget.isDefaultCanvasTarget = true;
  40989. /**
  40990. * The inspector provides information about the internal renderer state.
  40991. *
  40992. * @private
  40993. * @type {InspectorBase}
  40994. */
  40995. this._inspector = new InspectorBase();
  40996. this._inspector.setRenderer( this );
  40997. /**
  40998. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  40999. *
  41000. * @private
  41001. * @type {?Function}
  41002. */
  41003. this._getFallback = getFallback;
  41004. /**
  41005. * A reference to a renderer module for managing shader attributes.
  41006. *
  41007. * @private
  41008. * @type {?Attributes}
  41009. * @default null
  41010. */
  41011. this._attributes = null;
  41012. /**
  41013. * A reference to a renderer module for managing geometries.
  41014. *
  41015. * @private
  41016. * @type {?Geometries}
  41017. * @default null
  41018. */
  41019. this._geometries = null;
  41020. /**
  41021. * A reference to a renderer module for managing node related logic.
  41022. *
  41023. * @private
  41024. * @type {?Nodes}
  41025. * @default null
  41026. */
  41027. this._nodes = null;
  41028. /**
  41029. * A reference to a renderer module for managing the internal animation loop.
  41030. *
  41031. * @private
  41032. * @type {?Animation}
  41033. * @default null
  41034. */
  41035. this._animation = null;
  41036. /**
  41037. * A reference to a renderer module for managing shader program bindings.
  41038. *
  41039. * @private
  41040. * @type {?Bindings}
  41041. * @default null
  41042. */
  41043. this._bindings = null;
  41044. /**
  41045. * A reference to a renderer module for managing render objects.
  41046. *
  41047. * @private
  41048. * @type {?RenderObjects}
  41049. * @default null
  41050. */
  41051. this._objects = null;
  41052. /**
  41053. * A reference to a renderer module for managing render and compute pipelines.
  41054. *
  41055. * @private
  41056. * @type {?Pipelines}
  41057. * @default null
  41058. */
  41059. this._pipelines = null;
  41060. /**
  41061. * A reference to a renderer module for managing render bundles.
  41062. *
  41063. * @private
  41064. * @type {?RenderBundles}
  41065. * @default null
  41066. */
  41067. this._bundles = null;
  41068. /**
  41069. * A reference to a renderer module for managing render lists.
  41070. *
  41071. * @private
  41072. * @type {?RenderLists}
  41073. * @default null
  41074. */
  41075. this._renderLists = null;
  41076. /**
  41077. * A reference to a renderer module for managing render contexts.
  41078. *
  41079. * @private
  41080. * @type {?RenderContexts}
  41081. * @default null
  41082. */
  41083. this._renderContexts = null;
  41084. /**
  41085. * A reference to a renderer module for managing textures.
  41086. *
  41087. * @private
  41088. * @type {?Textures}
  41089. * @default null
  41090. */
  41091. this._textures = null;
  41092. /**
  41093. * A reference to a renderer module for backgrounds.
  41094. *
  41095. * @private
  41096. * @type {?Background}
  41097. * @default null
  41098. */
  41099. this._background = null;
  41100. /**
  41101. * This fullscreen quad is used for internal render passes
  41102. * like the tone mapping and color space output pass.
  41103. *
  41104. * @private
  41105. * @type {QuadMesh}
  41106. */
  41107. this._quad = new QuadMesh( new NodeMaterial() );
  41108. this._quad.name = 'Output Color Transform';
  41109. this._quad.material.name = 'outputColorTransform';
  41110. /**
  41111. * A reference to the current render context.
  41112. *
  41113. * @private
  41114. * @type {?RenderContext}
  41115. * @default null
  41116. */
  41117. this._currentRenderContext = null;
  41118. /**
  41119. * A custom sort function for the opaque render list.
  41120. *
  41121. * @private
  41122. * @type {?Function}
  41123. * @default null
  41124. */
  41125. this._opaqueSort = null;
  41126. /**
  41127. * A custom sort function for the transparent render list.
  41128. *
  41129. * @private
  41130. * @type {?Function}
  41131. * @default null
  41132. */
  41133. this._transparentSort = null;
  41134. /**
  41135. * The framebuffer target.
  41136. *
  41137. * @private
  41138. * @type {?RenderTarget}
  41139. * @default null
  41140. */
  41141. this._frameBufferTarget = null;
  41142. const alphaClear = this.alpha === true ? 0 : 1;
  41143. /**
  41144. * The clear color value.
  41145. *
  41146. * @private
  41147. * @type {Color4}
  41148. */
  41149. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  41150. /**
  41151. * The clear depth value.
  41152. *
  41153. * @private
  41154. * @type {number}
  41155. * @default 1
  41156. */
  41157. this._clearDepth = 1;
  41158. /**
  41159. * The clear stencil value.
  41160. *
  41161. * @private
  41162. * @type {number}
  41163. * @default 0
  41164. */
  41165. this._clearStencil = 0;
  41166. /**
  41167. * The current render target.
  41168. *
  41169. * @private
  41170. * @type {?RenderTarget}
  41171. * @default null
  41172. */
  41173. this._renderTarget = null;
  41174. /**
  41175. * The active cube face.
  41176. *
  41177. * @private
  41178. * @type {number}
  41179. * @default 0
  41180. */
  41181. this._activeCubeFace = 0;
  41182. /**
  41183. * The active mipmap level.
  41184. *
  41185. * @private
  41186. * @type {number}
  41187. * @default 0
  41188. */
  41189. this._activeMipmapLevel = 0;
  41190. /**
  41191. * The current output render target.
  41192. *
  41193. * @private
  41194. * @type {?RenderTarget}
  41195. * @default null
  41196. */
  41197. this._outputRenderTarget = null;
  41198. /**
  41199. * The MRT setting.
  41200. *
  41201. * @private
  41202. * @type {?MRTNode}
  41203. * @default null
  41204. */
  41205. this._mrt = null;
  41206. /**
  41207. * This function defines how a render object is going
  41208. * to be rendered.
  41209. *
  41210. * @private
  41211. * @type {?Function}
  41212. * @default null
  41213. */
  41214. this._renderObjectFunction = null;
  41215. /**
  41216. * Used to keep track of the current render object function.
  41217. *
  41218. * @private
  41219. * @type {?Function}
  41220. * @default null
  41221. */
  41222. this._currentRenderObjectFunction = null;
  41223. /**
  41224. * Used to keep track of the current render bundle.
  41225. *
  41226. * @private
  41227. * @type {?RenderBundle}
  41228. * @default null
  41229. */
  41230. this._currentRenderBundle = null;
  41231. /**
  41232. * Next to `_renderObjectFunction()`, this function provides another hook
  41233. * for influencing the render process of a render object. It is meant for internal
  41234. * use and only relevant for `compileAsync()` right now. Instead of using
  41235. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  41236. * a different function might be used which performs no draw but just the node
  41237. * and pipeline updates.
  41238. *
  41239. * @private
  41240. * @type {?Function}
  41241. * @default null
  41242. */
  41243. this._handleObjectFunction = this._renderObjectDirect;
  41244. /**
  41245. * Indicates whether the device has been lost or not. In WebGL terms, the device
  41246. * lost is considered as a context lost. When this is set to `true`, rendering
  41247. * isn't possible anymore.
  41248. *
  41249. * @private
  41250. * @type {boolean}
  41251. * @default false
  41252. */
  41253. this._isDeviceLost = false;
  41254. /**
  41255. * A callback function that defines what should happen when a device/context lost occurs.
  41256. *
  41257. * @type {Function}
  41258. */
  41259. this.onDeviceLost = this._onDeviceLost;
  41260. /**
  41261. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  41262. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  41263. * This will reduce rendering quality though.
  41264. *
  41265. * @private
  41266. * @type {number}
  41267. * @default HalfFloatType
  41268. */
  41269. this._colorBufferType = colorBufferType;
  41270. /**
  41271. * A cache for shadow nodes per material
  41272. *
  41273. * @private
  41274. * @type {WeakMap<Material, Object>}
  41275. */
  41276. this._cacheShadowNodes = new WeakMap();
  41277. /**
  41278. * Whether the renderer has been initialized or not.
  41279. *
  41280. * @private
  41281. * @type {boolean}
  41282. * @default false
  41283. */
  41284. this._initialized = false;
  41285. /**
  41286. * A reference to the promise which initializes the renderer.
  41287. *
  41288. * @private
  41289. * @type {?Promise<this>}
  41290. * @default null
  41291. */
  41292. this._initPromise = null;
  41293. /**
  41294. * An array of compilation promises which are used in `compileAsync()`.
  41295. *
  41296. * @private
  41297. * @type {?Array<Promise>}
  41298. * @default null
  41299. */
  41300. this._compilationPromises = null;
  41301. /**
  41302. * Whether the renderer should render transparent render objects or not.
  41303. *
  41304. * @type {boolean}
  41305. * @default true
  41306. */
  41307. this.transparent = true;
  41308. /**
  41309. * Whether the renderer should render opaque render objects or not.
  41310. *
  41311. * @type {boolean}
  41312. * @default true
  41313. */
  41314. this.opaque = true;
  41315. /**
  41316. * Shadow map configuration
  41317. * @typedef {Object} ShadowMapConfig
  41318. * @property {boolean} enabled - Whether to globally enable shadows or not.
  41319. * @property {number} type - The shadow map type.
  41320. */
  41321. /**
  41322. * The renderer's shadow configuration.
  41323. *
  41324. * @type {ShadowMapConfig}
  41325. */
  41326. this.shadowMap = {
  41327. enabled: false,
  41328. type: PCFShadowMap
  41329. };
  41330. /**
  41331. * XR configuration.
  41332. * @typedef {Object} XRConfig
  41333. * @property {boolean} enabled - Whether to globally enable XR or not.
  41334. */
  41335. /**
  41336. * The renderer's XR manager.
  41337. *
  41338. * @type {XRManager}
  41339. */
  41340. this.xr = new XRManager( this, multiview );
  41341. /**
  41342. * Debug configuration.
  41343. * @typedef {Object} DebugConfig
  41344. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  41345. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  41346. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  41347. */
  41348. /**
  41349. * The renderer's debug configuration.
  41350. *
  41351. * @type {DebugConfig}
  41352. */
  41353. this.debug = {
  41354. checkShaderErrors: true,
  41355. onShaderError: null,
  41356. getShaderAsync: async ( scene, camera, object ) => {
  41357. await this.compileAsync( scene, camera );
  41358. const renderList = this._renderLists.get( scene, camera );
  41359. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget, this._mrt );
  41360. const material = scene.overrideMaterial || object.material;
  41361. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  41362. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  41363. return { fragmentShader, vertexShader };
  41364. }
  41365. };
  41366. }
  41367. /**
  41368. * Initializes the renderer so it is ready for usage.
  41369. *
  41370. * @async
  41371. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  41372. */
  41373. async init() {
  41374. if ( this._initPromise !== null ) {
  41375. return this._initPromise;
  41376. }
  41377. this._initPromise = new Promise( async ( resolve, reject ) => {
  41378. let backend = this.backend;
  41379. try {
  41380. await backend.init( this );
  41381. } catch ( error ) {
  41382. if ( this._getFallback !== null ) {
  41383. // try the fallback
  41384. try {
  41385. this.backend = backend = this._getFallback( error );
  41386. await backend.init( this );
  41387. } catch ( error ) {
  41388. reject( error );
  41389. return;
  41390. }
  41391. } else {
  41392. reject( error );
  41393. return;
  41394. }
  41395. }
  41396. this._nodes = new Nodes( this, backend );
  41397. this._animation = new Animation( this, this._nodes, this.info );
  41398. this._attributes = new Attributes( backend );
  41399. this._background = new Background( this, this._nodes );
  41400. this._geometries = new Geometries( this._attributes, this.info );
  41401. this._textures = new Textures( this, backend, this.info );
  41402. this._pipelines = new Pipelines( backend, this._nodes );
  41403. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  41404. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  41405. this._renderLists = new RenderLists( this.lighting );
  41406. this._bundles = new RenderBundles();
  41407. this._renderContexts = new RenderContexts();
  41408. //
  41409. this._animation.start();
  41410. this._initialized = true;
  41411. //
  41412. this._inspector.init();
  41413. //
  41414. resolve( this );
  41415. } );
  41416. return this._initPromise;
  41417. }
  41418. /**
  41419. * A reference to the canvas element the renderer is drawing to.
  41420. * This value of this property will automatically be created by
  41421. * the renderer.
  41422. *
  41423. * @type {HTMLCanvasElement|OffscreenCanvas}
  41424. */
  41425. get domElement() {
  41426. return this._canvasTarget.domElement;
  41427. }
  41428. /**
  41429. * The coordinate system of the renderer. The value of this property
  41430. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  41431. * `THREE.WebGPUCoordinateSystem`.
  41432. *
  41433. * @readonly
  41434. * @type {number}
  41435. */
  41436. get coordinateSystem() {
  41437. return this.backend.coordinateSystem;
  41438. }
  41439. /**
  41440. * Compiles all materials in the given scene. This can be useful to avoid a
  41441. * phenomenon which is called "shader compilation stutter", which occurs when
  41442. * rendering an object with a new shader for the first time.
  41443. *
  41444. * If you want to add a 3D object to an existing scene, use the third optional
  41445. * parameter for applying the target scene. Note that the (target) scene's lighting
  41446. * and environment must be configured before calling this method.
  41447. *
  41448. * @async
  41449. * @param {Object3D} scene - The scene or 3D object to precompile.
  41450. * @param {Camera} camera - The camera that is used to render the scene.
  41451. * @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.
  41452. * @return {Promise} A Promise that resolves when the compile has been finished.
  41453. */
  41454. async compileAsync( scene, camera, targetScene = null ) {
  41455. if ( this._isDeviceLost === true ) return;
  41456. if ( this._initialized === false ) await this.init();
  41457. // preserve render tree
  41458. const nodeFrame = this._nodes.nodeFrame;
  41459. const previousRenderId = nodeFrame.renderId;
  41460. const previousRenderContext = this._currentRenderContext;
  41461. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  41462. const previousCompilationPromises = this._compilationPromises;
  41463. //
  41464. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  41465. if ( targetScene === null ) targetScene = scene;
  41466. const renderTarget = this._renderTarget;
  41467. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget, this._mrt );
  41468. const activeMipmapLevel = this._activeMipmapLevel;
  41469. const compilationPromises = [];
  41470. this._currentRenderContext = renderContext;
  41471. this._currentRenderObjectFunction = this.renderObject;
  41472. this._handleObjectFunction = this._createObjectPipeline;
  41473. this._compilationPromises = compilationPromises;
  41474. nodeFrame.renderId ++;
  41475. //
  41476. nodeFrame.update();
  41477. //
  41478. renderContext.depth = this.depth;
  41479. renderContext.stencil = this.stencil;
  41480. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  41481. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  41482. //
  41483. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  41484. //
  41485. const renderList = this._renderLists.get( scene, camera );
  41486. renderList.begin();
  41487. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  41488. // include lights from target scene
  41489. if ( targetScene !== scene ) {
  41490. targetScene.traverseVisible( function ( object ) {
  41491. if ( object.isLight && object.layers.test( camera.layers ) ) {
  41492. renderList.pushLight( object );
  41493. }
  41494. } );
  41495. }
  41496. renderList.finish();
  41497. //
  41498. if ( renderTarget !== null ) {
  41499. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  41500. const renderTargetData = this._textures.get( renderTarget );
  41501. renderContext.textures = renderTargetData.textures;
  41502. renderContext.depthTexture = renderTargetData.depthTexture;
  41503. } else {
  41504. renderContext.textures = null;
  41505. renderContext.depthTexture = null;
  41506. }
  41507. //
  41508. this._background.update( sceneRef, renderList, renderContext );
  41509. // process render lists
  41510. const opaqueObjects = renderList.opaque;
  41511. const transparentObjects = renderList.transparent;
  41512. const transparentDoublePassObjects = renderList.transparentDoublePass;
  41513. const lightsNode = renderList.lightsNode;
  41514. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41515. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41516. // restore render tree
  41517. nodeFrame.renderId = previousRenderId;
  41518. this._currentRenderContext = previousRenderContext;
  41519. this._currentRenderObjectFunction = previousRenderObjectFunction;
  41520. this._compilationPromises = previousCompilationPromises;
  41521. this._handleObjectFunction = this._renderObjectDirect;
  41522. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  41523. await Promise.all( compilationPromises );
  41524. }
  41525. /**
  41526. * Renders the scene in an async fashion.
  41527. *
  41528. * @async
  41529. * @deprecated
  41530. * @param {Object3D} scene - The scene or 3D object to render.
  41531. * @param {Camera} camera - The camera.
  41532. * @return {Promise} A Promise that resolves when the render has been finished.
  41533. */
  41534. async renderAsync( scene, camera ) {
  41535. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41536. await this.init();
  41537. this.render( scene, camera );
  41538. }
  41539. /**
  41540. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  41541. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  41542. *
  41543. * @async
  41544. * @deprecated
  41545. * @return {Promise} A Promise that resolves when synchronization has been finished.
  41546. */
  41547. async waitForGPU() {
  41548. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  41549. }
  41550. //
  41551. set inspector( value ) {
  41552. if ( this._inspector !== null ) {
  41553. this._inspector.setRenderer( null );
  41554. }
  41555. this._inspector = value;
  41556. this._inspector.setRenderer( this );
  41557. }
  41558. /**
  41559. * The inspector instance. The inspector can be any class that extends from `InspectorBase`.
  41560. *
  41561. * @type {InspectorBase}
  41562. */
  41563. get inspector() {
  41564. return this._inspector;
  41565. }
  41566. /**
  41567. * Enables or disables high precision for model-view and normal-view matrices.
  41568. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  41569. *
  41570. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  41571. *
  41572. * @param {boolean} value - Whether to enable or disable high precision.
  41573. * @type {boolean}
  41574. */
  41575. set highPrecision( value ) {
  41576. const contextNodeData = this.contextNode.value;
  41577. if ( value === true ) {
  41578. contextNodeData.modelViewMatrix = highpModelViewMatrix;
  41579. contextNodeData.modelNormalViewMatrix = highpModelNormalViewMatrix;
  41580. } else if ( this.highPrecision ) {
  41581. delete contextNodeData.modelViewMatrix;
  41582. delete contextNodeData.modelNormalViewMatrix;
  41583. }
  41584. }
  41585. /**
  41586. * Returns whether high precision is enabled or not.
  41587. *
  41588. * @return {boolean} Whether high precision is enabled or not.
  41589. * @type {boolean}
  41590. */
  41591. get highPrecision() {
  41592. const contextNodeData = this.contextNode.value;
  41593. return contextNodeData.modelViewMatrix === highpModelViewMatrix && contextNodeData.modelNormalViewMatrix === highpModelNormalViewMatrix;
  41594. }
  41595. /**
  41596. * Sets the given MRT configuration.
  41597. *
  41598. * @param {MRTNode} mrt - The MRT node to set.
  41599. * @return {Renderer} A reference to this renderer.
  41600. */
  41601. setMRT( mrt ) {
  41602. this._mrt = mrt;
  41603. return this;
  41604. }
  41605. /**
  41606. * Returns the MRT configuration.
  41607. *
  41608. * @return {MRTNode} The MRT configuration.
  41609. */
  41610. getMRT() {
  41611. return this._mrt;
  41612. }
  41613. /**
  41614. * Returns the color buffer type.
  41615. *
  41616. * @return {number} The color buffer type.
  41617. */
  41618. getColorBufferType() {
  41619. return this._colorBufferType;
  41620. }
  41621. /**
  41622. * Default implementation of the device lost callback.
  41623. *
  41624. * @private
  41625. * @param {Object} info - Information about the context lost.
  41626. */
  41627. _onDeviceLost( info ) {
  41628. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  41629. if ( info.reason ) {
  41630. errorMessage += `\nReason: ${info.reason}`;
  41631. }
  41632. error( errorMessage );
  41633. this._isDeviceLost = true;
  41634. }
  41635. /**
  41636. * Renders the given render bundle.
  41637. *
  41638. * @private
  41639. * @param {Object} bundle - Render bundle data.
  41640. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  41641. * @param {LightsNode} lightsNode - The lights node.
  41642. */
  41643. _renderBundle( bundle, sceneRef, lightsNode ) {
  41644. const { bundleGroup, camera, renderList } = bundle;
  41645. const renderContext = this._currentRenderContext;
  41646. //
  41647. const renderBundle = this._bundles.get( bundleGroup, camera );
  41648. const renderBundleData = this.backend.get( renderBundle );
  41649. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  41650. //
  41651. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  41652. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  41653. renderBundleData.renderContexts.add( renderContext );
  41654. if ( renderBundleNeedsUpdate ) {
  41655. this.backend.beginBundle( renderContext );
  41656. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  41657. renderBundleData.renderObjects = [];
  41658. }
  41659. this._currentRenderBundle = renderBundle;
  41660. const {
  41661. transparentDoublePass: transparentDoublePassObjects,
  41662. transparent: transparentObjects,
  41663. opaque: opaqueObjects
  41664. } = renderList;
  41665. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41666. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41667. this._currentRenderBundle = null;
  41668. //
  41669. this.backend.finishBundle( renderContext, renderBundle );
  41670. renderBundleData.version = bundleGroup.version;
  41671. } else {
  41672. const { renderObjects } = renderBundleData;
  41673. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  41674. const renderObject = renderObjects[ i ];
  41675. if ( this._nodes.needsRefresh( renderObject ) ) {
  41676. this._nodes.updateBefore( renderObject );
  41677. this._nodes.updateForRender( renderObject );
  41678. this._bindings.updateForRender( renderObject );
  41679. this._nodes.updateAfter( renderObject );
  41680. }
  41681. }
  41682. }
  41683. this.backend.addBundle( renderContext, renderBundle );
  41684. }
  41685. /**
  41686. * Renders the scene or 3D object with the given camera. This method can only be called
  41687. * if the renderer has been initialized. When using `render()` inside an animation loop,
  41688. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  41689. * with {@link Renderer#setAnimationLoop} though.
  41690. *
  41691. * For all other use cases (like when using on-demand rendering), you must call
  41692. * {@link Renderer#init} before rendering.
  41693. *
  41694. * The target of the method is the default framebuffer (meaning the canvas)
  41695. * or alternatively a render target when specified via `setRenderTarget()`.
  41696. *
  41697. * @param {Object3D} scene - The scene or 3D object to render.
  41698. * @param {Camera} camera - The camera to render the scene with.
  41699. */
  41700. render( scene, camera ) {
  41701. if ( this._initialized === false ) {
  41702. throw new Error( 'Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  41703. }
  41704. this._renderScene( scene, camera );
  41705. }
  41706. /**
  41707. * Returns whether the renderer has been initialized or not.
  41708. *
  41709. * @readonly
  41710. * @return {boolean} Whether the renderer has been initialized or not.
  41711. */
  41712. get initialized() {
  41713. return this._initialized;
  41714. }
  41715. /**
  41716. * Returns an internal render target which is used when computing the output tone mapping
  41717. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  41718. * pass and not inline to achieve more correct results.
  41719. *
  41720. * @private
  41721. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  41722. */
  41723. _getFrameBufferTarget() {
  41724. const { currentToneMapping, currentColorSpace } = this;
  41725. const useToneMapping = currentToneMapping !== NoToneMapping;
  41726. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  41727. if ( useToneMapping === false && useColorSpace === false ) return null;
  41728. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  41729. const { depth, stencil } = this;
  41730. let frameBufferTarget = this._frameBufferTarget;
  41731. if ( frameBufferTarget === null ) {
  41732. frameBufferTarget = new RenderTarget( width, height, {
  41733. depthBuffer: depth,
  41734. stencilBuffer: stencil,
  41735. type: this._colorBufferType,
  41736. format: RGBAFormat,
  41737. colorSpace: ColorManagement.workingColorSpace,
  41738. generateMipmaps: false,
  41739. minFilter: LinearFilter,
  41740. magFilter: LinearFilter,
  41741. samples: this.samples
  41742. } );
  41743. frameBufferTarget.isPostProcessingRenderTarget = true;
  41744. this._frameBufferTarget = frameBufferTarget;
  41745. }
  41746. const outputRenderTarget = this.getOutputRenderTarget();
  41747. frameBufferTarget.depthBuffer = depth;
  41748. frameBufferTarget.stencilBuffer = stencil;
  41749. if ( outputRenderTarget !== null ) {
  41750. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  41751. } else {
  41752. frameBufferTarget.setSize( width, height, 1 );
  41753. }
  41754. const canvasTarget = this._canvasTarget;
  41755. frameBufferTarget.viewport.copy( canvasTarget._viewport );
  41756. frameBufferTarget.scissor.copy( canvasTarget._scissor );
  41757. frameBufferTarget.viewport.multiplyScalar( canvasTarget._pixelRatio );
  41758. frameBufferTarget.scissor.multiplyScalar( canvasTarget._pixelRatio );
  41759. frameBufferTarget.scissorTest = canvasTarget._scissorTest;
  41760. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  41761. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  41762. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  41763. return frameBufferTarget;
  41764. }
  41765. /**
  41766. * Renders the scene or 3D object with the given camera.
  41767. *
  41768. * @private
  41769. * @param {Object3D} scene - The scene or 3D object to render.
  41770. * @param {Camera} camera - The camera to render the scene with.
  41771. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  41772. * @return {RenderContext} The current render context.
  41773. */
  41774. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  41775. if ( this._isDeviceLost === true ) return;
  41776. //
  41777. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  41778. // preserve render tree
  41779. const nodeFrame = this._nodes.nodeFrame;
  41780. const previousRenderId = nodeFrame.renderId;
  41781. const previousRenderContext = this._currentRenderContext;
  41782. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  41783. //
  41784. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  41785. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  41786. const activeCubeFace = this._activeCubeFace;
  41787. const activeMipmapLevel = this._activeMipmapLevel;
  41788. //
  41789. let renderTarget;
  41790. if ( frameBufferTarget !== null ) {
  41791. renderTarget = frameBufferTarget;
  41792. this.setRenderTarget( renderTarget );
  41793. } else {
  41794. renderTarget = outputRenderTarget;
  41795. }
  41796. //
  41797. const renderContext = this._renderContexts.get( scene, camera, renderTarget, this._mrt );
  41798. this._currentRenderContext = renderContext;
  41799. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  41800. //
  41801. this.info.calls ++;
  41802. this.info.render.calls ++;
  41803. this.info.render.frameCalls ++;
  41804. nodeFrame.renderId = this.info.calls;
  41805. //
  41806. this.backend.updateTimeStampUID( renderContext );
  41807. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  41808. //
  41809. const coordinateSystem = this.coordinateSystem;
  41810. const xr = this.xr;
  41811. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  41812. camera.coordinateSystem = coordinateSystem;
  41813. camera.updateProjectionMatrix();
  41814. if ( camera.isArrayCamera ) {
  41815. for ( const subCamera of camera.cameras ) {
  41816. subCamera.coordinateSystem = coordinateSystem;
  41817. subCamera.updateProjectionMatrix();
  41818. }
  41819. }
  41820. }
  41821. //
  41822. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  41823. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  41824. if ( xr.enabled === true && xr.isPresenting === true ) {
  41825. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  41826. camera = xr.getCamera(); // use XR camera for rendering
  41827. }
  41828. //
  41829. const canvasTarget = this._canvasTarget;
  41830. let viewport = canvasTarget._viewport;
  41831. let scissor = canvasTarget._scissor;
  41832. let pixelRatio = canvasTarget._pixelRatio;
  41833. if ( renderTarget !== null ) {
  41834. viewport = renderTarget.viewport;
  41835. scissor = renderTarget.scissor;
  41836. pixelRatio = 1;
  41837. }
  41838. this.getDrawingBufferSize( _drawingBufferSize );
  41839. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  41840. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  41841. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  41842. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  41843. renderContext.viewportValue.width >>= activeMipmapLevel;
  41844. renderContext.viewportValue.height >>= activeMipmapLevel;
  41845. renderContext.viewportValue.minDepth = minDepth;
  41846. renderContext.viewportValue.maxDepth = maxDepth;
  41847. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  41848. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  41849. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  41850. renderContext.scissorValue.width >>= activeMipmapLevel;
  41851. renderContext.scissorValue.height >>= activeMipmapLevel;
  41852. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  41853. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  41854. //
  41855. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  41856. //
  41857. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41858. if ( ! camera.isArrayCamera ) {
  41859. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  41860. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  41861. }
  41862. const renderList = this._renderLists.get( scene, camera );
  41863. renderList.begin();
  41864. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  41865. renderList.finish();
  41866. if ( this.sortObjects === true ) {
  41867. renderList.sort( this._opaqueSort, this._transparentSort );
  41868. }
  41869. //
  41870. if ( renderTarget !== null ) {
  41871. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  41872. const renderTargetData = this._textures.get( renderTarget );
  41873. renderContext.textures = renderTargetData.textures;
  41874. renderContext.depthTexture = renderTargetData.depthTexture;
  41875. renderContext.width = renderTargetData.width;
  41876. renderContext.height = renderTargetData.height;
  41877. renderContext.renderTarget = renderTarget;
  41878. renderContext.depth = renderTarget.depthBuffer;
  41879. renderContext.stencil = renderTarget.stencilBuffer;
  41880. } else {
  41881. renderContext.textures = null;
  41882. renderContext.depthTexture = null;
  41883. renderContext.width = _drawingBufferSize.width;
  41884. renderContext.height = _drawingBufferSize.height;
  41885. renderContext.depth = this.depth;
  41886. renderContext.stencil = this.stencil;
  41887. }
  41888. renderContext.width >>= activeMipmapLevel;
  41889. renderContext.height >>= activeMipmapLevel;
  41890. renderContext.activeCubeFace = activeCubeFace;
  41891. renderContext.activeMipmapLevel = activeMipmapLevel;
  41892. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  41893. //
  41894. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  41895. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  41896. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  41897. }
  41898. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  41899. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  41900. }
  41901. //
  41902. this._background.update( sceneRef, renderList, renderContext );
  41903. //
  41904. renderContext.camera = camera;
  41905. this.backend.beginRender( renderContext );
  41906. // process render lists
  41907. const {
  41908. bundles,
  41909. lightsNode,
  41910. transparentDoublePass: transparentDoublePassObjects,
  41911. transparent: transparentObjects,
  41912. opaque: opaqueObjects
  41913. } = renderList;
  41914. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  41915. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41916. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41917. // finish render pass
  41918. this.backend.finishRender( renderContext );
  41919. // restore render tree
  41920. nodeFrame.renderId = previousRenderId;
  41921. this._currentRenderContext = previousRenderContext;
  41922. this._currentRenderObjectFunction = previousRenderObjectFunction;
  41923. //
  41924. if ( frameBufferTarget !== null ) {
  41925. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  41926. this._renderOutput( renderTarget );
  41927. }
  41928. //
  41929. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  41930. //
  41931. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  41932. //
  41933. return renderContext;
  41934. }
  41935. _setXRLayerSize( width, height ) {
  41936. // TODO: Find a better solution to resize the canvas when in XR.
  41937. this._canvasTarget._width = width;
  41938. this._canvasTarget._height = height;
  41939. this.setViewport( 0, 0, width, height );
  41940. }
  41941. /**
  41942. * The output pass performs tone mapping and color space conversion.
  41943. *
  41944. * @private
  41945. * @param {RenderTarget} renderTarget - The current render target.
  41946. */
  41947. _renderOutput( renderTarget ) {
  41948. const quad = this._quad;
  41949. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  41950. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  41951. quad.material.needsUpdate = true;
  41952. }
  41953. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  41954. const currentAutoClear = this.autoClear;
  41955. const currentXR = this.xr.enabled;
  41956. this.autoClear = false;
  41957. this.xr.enabled = false;
  41958. this._renderScene( quad, quad.camera, false );
  41959. this.autoClear = currentAutoClear;
  41960. this.xr.enabled = currentXR;
  41961. }
  41962. /**
  41963. * Returns the maximum available anisotropy for texture filtering.
  41964. *
  41965. * @return {number} The maximum available anisotropy.
  41966. */
  41967. getMaxAnisotropy() {
  41968. return this.backend.getMaxAnisotropy();
  41969. }
  41970. /**
  41971. * Returns the active cube face.
  41972. *
  41973. * @return {number} The active cube face.
  41974. */
  41975. getActiveCubeFace() {
  41976. return this._activeCubeFace;
  41977. }
  41978. /**
  41979. * Returns the active mipmap level.
  41980. *
  41981. * @return {number} The active mipmap level.
  41982. */
  41983. getActiveMipmapLevel() {
  41984. return this._activeMipmapLevel;
  41985. }
  41986. /**
  41987. * Applications are advised to always define the animation loop
  41988. * with this method and not manually with `requestAnimationFrame()`
  41989. * for best compatibility.
  41990. *
  41991. * @async
  41992. * @param {?onAnimationCallback} callback - The application's animation loop.
  41993. * @return {Promise} A Promise that resolves when the set has been executed.
  41994. */
  41995. async setAnimationLoop( callback ) {
  41996. if ( this._initialized === false ) await this.init();
  41997. this._animation.setAnimationLoop( callback );
  41998. }
  41999. /**
  42000. * Returns the current animation loop callback.
  42001. *
  42002. * @return {?Function} The current animation loop callback.
  42003. */
  42004. getAnimationLoop() {
  42005. return this._animation.getAnimationLoop();
  42006. }
  42007. /**
  42008. * Can be used to transfer buffer data from a storage buffer attribute
  42009. * from the GPU to the CPU in context of compute shaders.
  42010. *
  42011. * @async
  42012. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42013. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42014. */
  42015. async getArrayBufferAsync( attribute ) {
  42016. return await this.backend.getArrayBufferAsync( attribute );
  42017. }
  42018. /**
  42019. * Returns the rendering context.
  42020. *
  42021. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  42022. */
  42023. getContext() {
  42024. return this.backend.getContext();
  42025. }
  42026. /**
  42027. * Returns the pixel ratio.
  42028. *
  42029. * @return {number} The pixel ratio.
  42030. */
  42031. getPixelRatio() {
  42032. return this._canvasTarget.getPixelRatio();
  42033. }
  42034. /**
  42035. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  42036. *
  42037. * @param {Vector2} target - The method writes the result in this target object.
  42038. * @return {Vector2} The drawing buffer size.
  42039. */
  42040. getDrawingBufferSize( target ) {
  42041. return this._canvasTarget.getDrawingBufferSize( target );
  42042. }
  42043. /**
  42044. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  42045. *
  42046. * @param {Vector2} target - The method writes the result in this target object.
  42047. * @return {Vector2} The renderer's size in logical pixels.
  42048. */
  42049. getSize( target ) {
  42050. return this._canvasTarget.getSize( target );
  42051. }
  42052. /**
  42053. * Sets the given pixel ratio and resizes the canvas if necessary.
  42054. *
  42055. * @param {number} [value=1] - The pixel ratio.
  42056. */
  42057. setPixelRatio( value = 1 ) {
  42058. this._canvasTarget.setPixelRatio( value );
  42059. }
  42060. /**
  42061. * This method allows to define the drawing buffer size by specifying
  42062. * width, height and pixel ratio all at once. The size of the drawing
  42063. * buffer is computed with this formula:
  42064. * ```js
  42065. * size.x = width * pixelRatio;
  42066. * size.y = height * pixelRatio;
  42067. * ```
  42068. *
  42069. * @param {number} width - The width in logical pixels.
  42070. * @param {number} height - The height in logical pixels.
  42071. * @param {number} pixelRatio - The pixel ratio.
  42072. */
  42073. setDrawingBufferSize( width, height, pixelRatio ) {
  42074. // Renderer can't be resized while presenting in XR.
  42075. if ( this.xr && this.xr.isPresenting ) return;
  42076. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  42077. }
  42078. /**
  42079. * Sets the size of the renderer.
  42080. *
  42081. * @param {number} width - The width in logical pixels.
  42082. * @param {number} height - The height in logical pixels.
  42083. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  42084. */
  42085. setSize( width, height, updateStyle = true ) {
  42086. // Renderer can't be resized while presenting in XR.
  42087. if ( this.xr && this.xr.isPresenting ) return;
  42088. this._canvasTarget.setSize( width, height, updateStyle );
  42089. }
  42090. /**
  42091. * Defines a manual sort function for the opaque render list.
  42092. * Pass `null` to use the default sort.
  42093. *
  42094. * @param {Function} method - The sort function.
  42095. */
  42096. setOpaqueSort( method ) {
  42097. this._opaqueSort = method;
  42098. }
  42099. /**
  42100. * Defines a manual sort function for the transparent render list.
  42101. * Pass `null` to use the default sort.
  42102. *
  42103. * @param {Function} method - The sort function.
  42104. */
  42105. setTransparentSort( method ) {
  42106. this._transparentSort = method;
  42107. }
  42108. /**
  42109. * Returns the scissor rectangle.
  42110. *
  42111. * @param {Vector4} target - The method writes the result in this target object.
  42112. * @return {Vector4} The scissor rectangle.
  42113. */
  42114. getScissor( target ) {
  42115. return this._canvasTarget.getScissor( target );
  42116. }
  42117. /**
  42118. * Defines the scissor rectangle.
  42119. *
  42120. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  42121. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  42122. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  42123. * @param {number} width - The width of the scissor box in logical pixel unit.
  42124. * @param {number} height - The height of the scissor box in logical pixel unit.
  42125. */
  42126. setScissor( x, y, width, height ) {
  42127. this._canvasTarget.setScissor( x, y, width, height );
  42128. }
  42129. /**
  42130. * Returns the scissor test value.
  42131. *
  42132. * @return {boolean} Whether the scissor test should be enabled or not.
  42133. */
  42134. getScissorTest() {
  42135. return this._canvasTarget.getScissorTest();
  42136. }
  42137. /**
  42138. * Defines the scissor test.
  42139. *
  42140. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42141. */
  42142. setScissorTest( boolean ) {
  42143. this._canvasTarget.setScissorTest( boolean );
  42144. // TODO: Move it to CanvasTarget event listener.
  42145. this.backend.setScissorTest( boolean );
  42146. }
  42147. /**
  42148. * Returns the viewport definition.
  42149. *
  42150. * @param {Vector4} target - The method writes the result in this target object.
  42151. * @return {Vector4} The viewport definition.
  42152. */
  42153. getViewport( target ) {
  42154. return this._canvasTarget.getViewport( target );
  42155. }
  42156. /**
  42157. * Defines the viewport.
  42158. *
  42159. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  42160. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  42161. * @param {number} width - The width of the viewport in logical pixel unit.
  42162. * @param {number} height - The height of the viewport in logical pixel unit.
  42163. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  42164. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  42165. */
  42166. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  42167. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  42168. }
  42169. /**
  42170. * Returns the clear color.
  42171. *
  42172. * @param {Color} target - The method writes the result in this target object.
  42173. * @return {Color} The clear color.
  42174. */
  42175. getClearColor( target ) {
  42176. return target.copy( this._clearColor );
  42177. }
  42178. /**
  42179. * Defines the clear color and optionally the clear alpha.
  42180. *
  42181. * @param {Color} color - The clear color.
  42182. * @param {number} [alpha=1] - The clear alpha.
  42183. */
  42184. setClearColor( color, alpha = 1 ) {
  42185. this._clearColor.set( color );
  42186. this._clearColor.a = alpha;
  42187. }
  42188. /**
  42189. * Returns the clear alpha.
  42190. *
  42191. * @return {number} The clear alpha.
  42192. */
  42193. getClearAlpha() {
  42194. return this._clearColor.a;
  42195. }
  42196. /**
  42197. * Defines the clear alpha.
  42198. *
  42199. * @param {number} alpha - The clear alpha.
  42200. */
  42201. setClearAlpha( alpha ) {
  42202. this._clearColor.a = alpha;
  42203. }
  42204. /**
  42205. * Returns the clear depth.
  42206. *
  42207. * @return {number} The clear depth.
  42208. */
  42209. getClearDepth() {
  42210. return this._clearDepth;
  42211. }
  42212. /**
  42213. * Defines the clear depth.
  42214. *
  42215. * @param {number} depth - The clear depth.
  42216. */
  42217. setClearDepth( depth ) {
  42218. this._clearDepth = depth;
  42219. }
  42220. /**
  42221. * Returns the clear stencil.
  42222. *
  42223. * @return {number} The clear stencil.
  42224. */
  42225. getClearStencil() {
  42226. return this._clearStencil;
  42227. }
  42228. /**
  42229. * Defines the clear stencil.
  42230. *
  42231. * @param {number} stencil - The clear stencil.
  42232. */
  42233. setClearStencil( stencil ) {
  42234. this._clearStencil = stencil;
  42235. }
  42236. /**
  42237. * This method performs an occlusion query for the given 3D object.
  42238. * It returns `true` if the given 3D object is fully occluded by other
  42239. * 3D objects in the scene.
  42240. *
  42241. * @param {Object3D} object - The 3D object to test.
  42242. * @return {boolean} Whether the 3D object is fully occluded or not.
  42243. */
  42244. isOccluded( object ) {
  42245. const renderContext = this._currentRenderContext;
  42246. return renderContext && this.backend.isOccluded( renderContext, object );
  42247. }
  42248. /**
  42249. * Performs a manual clear operation. This method ignores `autoClear` properties.
  42250. *
  42251. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42252. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42253. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42254. */
  42255. clear( color = true, depth = true, stencil = true ) {
  42256. if ( this._initialized === false ) {
  42257. throw new Error( 'Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42258. }
  42259. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  42260. let renderContext = null;
  42261. if ( renderTarget !== null ) {
  42262. this._textures.updateRenderTarget( renderTarget );
  42263. const renderTargetData = this._textures.get( renderTarget );
  42264. renderContext = this._renderContexts.getForClear( renderTarget );
  42265. renderContext.textures = renderTargetData.textures;
  42266. renderContext.depthTexture = renderTargetData.depthTexture;
  42267. renderContext.width = renderTargetData.width;
  42268. renderContext.height = renderTargetData.height;
  42269. renderContext.renderTarget = renderTarget;
  42270. renderContext.depth = renderTarget.depthBuffer;
  42271. renderContext.stencil = renderTarget.stencilBuffer;
  42272. // #30329
  42273. renderContext.clearColorValue = this.backend.getClearColor();
  42274. renderContext.activeCubeFace = this.getActiveCubeFace();
  42275. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  42276. }
  42277. this.backend.clear( color, depth, stencil, renderContext );
  42278. if ( renderTarget !== null && this._renderTarget === null ) {
  42279. this._renderOutput( renderTarget );
  42280. }
  42281. }
  42282. /**
  42283. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  42284. */
  42285. clearColor() {
  42286. this.clear( true, false, false );
  42287. }
  42288. /**
  42289. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  42290. */
  42291. clearDepth() {
  42292. this.clear( false, true, false );
  42293. }
  42294. /**
  42295. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  42296. */
  42297. clearStencil() {
  42298. this.clear( false, false, true );
  42299. }
  42300. /**
  42301. * Async version of {@link Renderer#clear}.
  42302. *
  42303. * @async
  42304. * @deprecated
  42305. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42306. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42307. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42308. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42309. */
  42310. async clearAsync( color = true, depth = true, stencil = true ) {
  42311. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42312. await this.init();
  42313. this.clear( color, depth, stencil );
  42314. }
  42315. /**
  42316. * Async version of {@link Renderer#clearColor}.
  42317. *
  42318. * @async
  42319. * @deprecated
  42320. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42321. */
  42322. async clearColorAsync() {
  42323. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42324. this.clear( true, false, false );
  42325. }
  42326. /**
  42327. * Async version of {@link Renderer#clearDepth}.
  42328. *
  42329. * @async
  42330. * @deprecated
  42331. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42332. */
  42333. async clearDepthAsync() {
  42334. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42335. this.clear( false, true, false );
  42336. }
  42337. /**
  42338. * Async version of {@link Renderer#clearStencil}.
  42339. *
  42340. * @async
  42341. * @deprecated
  42342. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42343. */
  42344. async clearStencilAsync() {
  42345. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42346. this.clear( false, false, true );
  42347. }
  42348. /**
  42349. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  42350. * If this is the case, the renderer allocates an internal render target for that purpose.
  42351. *
  42352. */
  42353. get needsFrameBufferTarget() {
  42354. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  42355. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  42356. return useToneMapping || useColorSpace;
  42357. }
  42358. /**
  42359. * The number of samples used for multi-sample anti-aliasing (MSAA).
  42360. *
  42361. * @type {number}
  42362. * @default 0
  42363. */
  42364. get samples() {
  42365. return this._samples;
  42366. }
  42367. /**
  42368. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  42369. *
  42370. * When rendering to a custom render target, the number of samples of that render target is used.
  42371. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  42372. * the number of samples is set to 0.
  42373. *
  42374. * @type {number}
  42375. */
  42376. get currentSamples() {
  42377. let samples = this._samples;
  42378. if ( this._renderTarget !== null ) {
  42379. samples = this._renderTarget.samples;
  42380. } else if ( this.needsFrameBufferTarget ) {
  42381. samples = 0;
  42382. }
  42383. return samples;
  42384. }
  42385. /**
  42386. * The current tone mapping of the renderer. When not producing screen output,
  42387. * the tone mapping is always `NoToneMapping`.
  42388. *
  42389. * @type {number}
  42390. */
  42391. get currentToneMapping() {
  42392. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  42393. }
  42394. /**
  42395. * The current color space of the renderer. When not producing screen output,
  42396. * the color space is always the working color space.
  42397. *
  42398. * @type {string}
  42399. */
  42400. get currentColorSpace() {
  42401. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  42402. }
  42403. /**
  42404. * Returns `true` if the rendering settings are set to screen output.
  42405. *
  42406. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  42407. */
  42408. get isOutputTarget() {
  42409. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  42410. }
  42411. /**
  42412. * Frees all internal resources of the renderer. Call this method if the renderer
  42413. * is no longer in use by your app.
  42414. */
  42415. dispose() {
  42416. if ( this._initialized === true ) {
  42417. this.info.dispose();
  42418. this.backend.dispose();
  42419. this._animation.dispose();
  42420. this._objects.dispose();
  42421. this._geometries.dispose();
  42422. this._pipelines.dispose();
  42423. this._nodes.dispose();
  42424. this._bindings.dispose();
  42425. this._renderLists.dispose();
  42426. this._renderContexts.dispose();
  42427. this._textures.dispose();
  42428. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  42429. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  42430. if ( queryPool !== null ) queryPool.dispose();
  42431. } );
  42432. }
  42433. this.setRenderTarget( null );
  42434. this.setAnimationLoop( null );
  42435. }
  42436. /**
  42437. * Sets the given render target. Calling this method means the renderer does not
  42438. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  42439. * Use `null` as the first argument to reset the state.
  42440. *
  42441. * @param {?RenderTarget} renderTarget - The render target to set.
  42442. * @param {number} [activeCubeFace=0] - The active cube face.
  42443. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  42444. */
  42445. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  42446. this._renderTarget = renderTarget;
  42447. this._activeCubeFace = activeCubeFace;
  42448. this._activeMipmapLevel = activeMipmapLevel;
  42449. }
  42450. /**
  42451. * Returns the current render target.
  42452. *
  42453. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  42454. */
  42455. getRenderTarget() {
  42456. return this._renderTarget;
  42457. }
  42458. /**
  42459. * Sets the output render target for the renderer.
  42460. *
  42461. * @param {Object} renderTarget - The render target to set as the output target.
  42462. */
  42463. setOutputRenderTarget( renderTarget ) {
  42464. this._outputRenderTarget = renderTarget;
  42465. }
  42466. /**
  42467. * Returns the current output target.
  42468. *
  42469. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  42470. */
  42471. getOutputRenderTarget() {
  42472. return this._outputRenderTarget;
  42473. }
  42474. /**
  42475. * Sets the canvas target. The canvas target manages the HTML canvas
  42476. * or the offscreen canvas the renderer draws into.
  42477. *
  42478. * @param {CanvasTarget} canvasTarget - The canvas target.
  42479. */
  42480. setCanvasTarget( canvasTarget ) {
  42481. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  42482. this._canvasTarget = canvasTarget;
  42483. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  42484. }
  42485. /**
  42486. * Returns the current canvas target.
  42487. *
  42488. * @return {CanvasTarget} The current canvas target.
  42489. */
  42490. getCanvasTarget() {
  42491. return this._canvasTarget;
  42492. }
  42493. /**
  42494. * Resets the renderer to the initial state before WebXR started.
  42495. *
  42496. * @private
  42497. */
  42498. _resetXRState() {
  42499. this.backend.setXRTarget( null );
  42500. this.setOutputRenderTarget( null );
  42501. this.setRenderTarget( null );
  42502. this._frameBufferTarget.dispose();
  42503. this._frameBufferTarget = null;
  42504. }
  42505. /**
  42506. * Callback for {@link Renderer#setRenderObjectFunction}.
  42507. *
  42508. * @callback renderObjectFunction
  42509. * @param {Object3D} object - The 3D object.
  42510. * @param {Scene} scene - The scene the 3D object belongs to.
  42511. * @param {Camera} camera - The camera the object should be rendered with.
  42512. * @param {BufferGeometry} geometry - The object's geometry.
  42513. * @param {Material} material - The object's material.
  42514. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42515. * @param {LightsNode} lightsNode - The current lights node.
  42516. * @param {ClippingContext} clippingContext - The clipping context.
  42517. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42518. */
  42519. /**
  42520. * Sets the given render object function. Calling this method overwrites the default implementation
  42521. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  42522. * if you want to modify the way objects are rendered. For example you can define things like "every
  42523. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  42524. * The custom function must always call `renderObject()` in its implementation.
  42525. *
  42526. * Use `null` as the first argument to reset the state.
  42527. *
  42528. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  42529. */
  42530. setRenderObjectFunction( renderObjectFunction ) {
  42531. this._renderObjectFunction = renderObjectFunction;
  42532. }
  42533. /**
  42534. * Returns the current render object function.
  42535. *
  42536. * @return {?Function} The current render object function. Returns `null` if no function is set.
  42537. */
  42538. getRenderObjectFunction() {
  42539. return this._renderObjectFunction;
  42540. }
  42541. /**
  42542. * Execute a single or an array of compute nodes. This method can only be called
  42543. * if the renderer has been initialized.
  42544. *
  42545. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  42546. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  42547. * - A single number representing count, or
  42548. * - An array [x, y, z] representing dispatch size, or
  42549. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  42550. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  42551. */
  42552. compute( computeNodes, dispatchSize = null ) {
  42553. if ( this._isDeviceLost === true ) return;
  42554. if ( this._initialized === false ) {
  42555. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  42556. return this.computeAsync( computeNodes, dispatchSize );
  42557. }
  42558. //
  42559. const nodeFrame = this._nodes.nodeFrame;
  42560. const previousRenderId = nodeFrame.renderId;
  42561. //
  42562. this.info.calls ++;
  42563. this.info.compute.calls ++;
  42564. this.info.compute.frameCalls ++;
  42565. nodeFrame.renderId = this.info.calls;
  42566. //
  42567. this.backend.updateTimeStampUID( computeNodes );
  42568. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  42569. //
  42570. const backend = this.backend;
  42571. const pipelines = this._pipelines;
  42572. const bindings = this._bindings;
  42573. const nodes = this._nodes;
  42574. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  42575. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  42576. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  42577. }
  42578. backend.beginCompute( computeNodes );
  42579. for ( const computeNode of computeList ) {
  42580. // onInit
  42581. if ( pipelines.has( computeNode ) === false ) {
  42582. const dispose = () => {
  42583. computeNode.removeEventListener( 'dispose', dispose );
  42584. pipelines.delete( computeNode );
  42585. bindings.deleteForCompute( computeNode );
  42586. nodes.delete( computeNode );
  42587. };
  42588. computeNode.addEventListener( 'dispose', dispose );
  42589. //
  42590. const onInitFn = computeNode.onInitFunction;
  42591. if ( onInitFn !== null ) {
  42592. onInitFn.call( computeNode, { renderer: this } );
  42593. }
  42594. }
  42595. nodes.updateForCompute( computeNode );
  42596. bindings.updateForCompute( computeNode );
  42597. const computeBindings = bindings.getForCompute( computeNode );
  42598. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  42599. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSize );
  42600. }
  42601. backend.finishCompute( computeNodes );
  42602. //
  42603. nodeFrame.renderId = previousRenderId;
  42604. //
  42605. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  42606. }
  42607. /**
  42608. * Execute a single or an array of compute nodes.
  42609. *
  42610. * @async
  42611. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  42612. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  42613. * - A single number representing count, or
  42614. * - An array [x, y, z] representing dispatch size, or
  42615. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  42616. * @return {Promise} A Promise that resolve when the compute has finished.
  42617. */
  42618. async computeAsync( computeNodes, dispatchSize = null ) {
  42619. if ( this._initialized === false ) await this.init();
  42620. this.compute( computeNodes, dispatchSize );
  42621. }
  42622. /**
  42623. * Checks if the given feature is supported by the selected backend.
  42624. *
  42625. * @async
  42626. * @deprecated
  42627. * @param {string} name - The feature's name.
  42628. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  42629. */
  42630. async hasFeatureAsync( name ) {
  42631. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42632. await this.init();
  42633. return this.hasFeature( name );
  42634. }
  42635. async resolveTimestampsAsync( type = 'render' ) {
  42636. if ( this._initialized === false ) await this.init();
  42637. return this.backend.resolveTimestampsAsync( type );
  42638. }
  42639. /**
  42640. * Checks if the given feature is supported by the selected backend. If the
  42641. * renderer has not been initialized, this method always returns `false`.
  42642. *
  42643. * @param {string} name - The feature's name.
  42644. * @return {boolean} Whether the feature is supported or not.
  42645. */
  42646. hasFeature( name ) {
  42647. if ( this._initialized === false ) {
  42648. throw new Error( 'Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42649. }
  42650. return this.backend.hasFeature( name );
  42651. }
  42652. /**
  42653. * Returns `true` when the renderer has been initialized.
  42654. *
  42655. * @return {boolean} Whether the renderer has been initialized or not.
  42656. */
  42657. hasInitialized() {
  42658. return this._initialized;
  42659. }
  42660. /**
  42661. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  42662. * (which can cause noticeable lags due to decode and GPU upload overhead).
  42663. *
  42664. * @async
  42665. * @deprecated
  42666. * @param {Texture} texture - The texture.
  42667. * @return {Promise} A Promise that resolves when the texture has been initialized.
  42668. */
  42669. async initTextureAsync( texture ) {
  42670. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42671. await this.init();
  42672. this.initTexture( texture );
  42673. }
  42674. /**
  42675. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  42676. * (which can cause noticeable lags due to decode and GPU upload overhead).
  42677. *
  42678. * This method can only be used if the renderer has been initialized.
  42679. *
  42680. * @param {Texture} texture - The texture.
  42681. */
  42682. initTexture( texture ) {
  42683. if ( this._initialized === false ) {
  42684. throw new Error( 'Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42685. }
  42686. this._textures.updateTexture( texture );
  42687. }
  42688. /**
  42689. * Copies the current bound framebuffer into the given texture.
  42690. *
  42691. * @param {FramebufferTexture} framebufferTexture - The texture.
  42692. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  42693. */
  42694. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  42695. if ( rectangle !== null ) {
  42696. if ( rectangle.isVector2 ) {
  42697. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  42698. } else if ( rectangle.isVector4 ) {
  42699. rectangle = _vector4.copy( rectangle ).floor();
  42700. } else {
  42701. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  42702. return;
  42703. }
  42704. } else {
  42705. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  42706. }
  42707. //
  42708. let renderContext = this._currentRenderContext;
  42709. let renderTarget;
  42710. if ( renderContext !== null ) {
  42711. renderTarget = renderContext.renderTarget;
  42712. } else {
  42713. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  42714. if ( renderTarget !== null ) {
  42715. this._textures.updateRenderTarget( renderTarget );
  42716. renderContext = this._textures.get( renderTarget );
  42717. }
  42718. }
  42719. //
  42720. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  42721. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  42722. this._inspector.copyFramebufferToTexture( framebufferTexture );
  42723. }
  42724. /**
  42725. * Copies data of the given source texture into a destination texture.
  42726. *
  42727. * @param {Texture} srcTexture - The source texture.
  42728. * @param {Texture} dstTexture - The destination texture.
  42729. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  42730. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  42731. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42732. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42733. */
  42734. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  42735. this._textures.updateTexture( srcTexture );
  42736. this._textures.updateTexture( dstTexture );
  42737. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  42738. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  42739. }
  42740. /**
  42741. * Reads pixel data from the given render target.
  42742. *
  42743. * @async
  42744. * @param {RenderTarget} renderTarget - The render target to read from.
  42745. * @param {number} x - The `x` coordinate of the copy region's origin.
  42746. * @param {number} y - The `y` coordinate of the copy region's origin.
  42747. * @param {number} width - The width of the copy region.
  42748. * @param {number} height - The height of the copy region.
  42749. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  42750. * @param {number} [faceIndex=0] - The active cube face index.
  42751. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  42752. */
  42753. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  42754. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  42755. }
  42756. /**
  42757. * Analyzes the given 3D object's hierarchy and builds render lists from the
  42758. * processed hierarchy.
  42759. *
  42760. * @private
  42761. * @param {Object3D} object - The 3D object to process (usually a scene).
  42762. * @param {Camera} camera - The camera the object is rendered with.
  42763. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  42764. * @param {RenderList} renderList - The current render list.
  42765. * @param {ClippingContext} clippingContext - The current clipping context.
  42766. */
  42767. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  42768. if ( object.visible === false ) return;
  42769. const visible = object.layers.test( camera.layers );
  42770. if ( visible ) {
  42771. if ( object.isGroup ) {
  42772. groupOrder = object.renderOrder;
  42773. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  42774. } else if ( object.isLOD ) {
  42775. if ( object.autoUpdate === true ) object.update( camera );
  42776. } else if ( object.isLight ) {
  42777. renderList.pushLight( object );
  42778. } else if ( object.isSprite ) {
  42779. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42780. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  42781. if ( this.sortObjects === true ) {
  42782. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  42783. }
  42784. const { geometry, material } = object;
  42785. if ( material.visible ) {
  42786. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  42787. }
  42788. }
  42789. } else if ( object.isLineLoop ) {
  42790. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  42791. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  42792. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42793. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  42794. const { geometry, material } = object;
  42795. if ( this.sortObjects === true ) {
  42796. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  42797. _vector4
  42798. .copy( geometry.boundingSphere.center )
  42799. .applyMatrix4( object.matrixWorld )
  42800. .applyMatrix4( _projScreenMatrix );
  42801. }
  42802. if ( Array.isArray( material ) ) {
  42803. const groups = geometry.groups;
  42804. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  42805. const group = groups[ i ];
  42806. const groupMaterial = material[ group.materialIndex ];
  42807. if ( groupMaterial && groupMaterial.visible ) {
  42808. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  42809. }
  42810. }
  42811. } else if ( material.visible ) {
  42812. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  42813. }
  42814. }
  42815. }
  42816. }
  42817. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  42818. const baseRenderList = renderList;
  42819. // replace render list
  42820. renderList = this._renderLists.get( object, camera );
  42821. renderList.begin();
  42822. baseRenderList.pushBundle( {
  42823. bundleGroup: object,
  42824. camera,
  42825. renderList,
  42826. } );
  42827. renderList.finish();
  42828. }
  42829. const children = object.children;
  42830. for ( let i = 0, l = children.length; i < l; i ++ ) {
  42831. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  42832. }
  42833. }
  42834. /**
  42835. * Renders the given render bundles.
  42836. *
  42837. * @private
  42838. * @param {Array<Object>} bundles - Array with render bundle data.
  42839. * @param {Scene} sceneRef - The scene the render bundles belong to.
  42840. * @param {LightsNode} lightsNode - The current lights node.
  42841. */
  42842. _renderBundles( bundles, sceneRef, lightsNode ) {
  42843. for ( const bundle of bundles ) {
  42844. this._renderBundle( bundle, sceneRef, lightsNode );
  42845. }
  42846. }
  42847. /**
  42848. * Renders the transparent objects from the given render lists.
  42849. *
  42850. * @private
  42851. * @param {Array<Object>} renderList - The transparent render list.
  42852. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  42853. * @param {Camera} camera - The camera the render list should be rendered with.
  42854. * @param {Scene} scene - The scene the render list belongs to.
  42855. * @param {LightsNode} lightsNode - The current lights node.
  42856. */
  42857. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  42858. if ( doublePassList.length > 0 ) {
  42859. // render back side
  42860. for ( const { material } of doublePassList ) {
  42861. material.side = BackSide;
  42862. }
  42863. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  42864. // render front side
  42865. for ( const { material } of doublePassList ) {
  42866. material.side = FrontSide;
  42867. }
  42868. this._renderObjects( renderList, camera, scene, lightsNode );
  42869. // restore
  42870. for ( const { material } of doublePassList ) {
  42871. material.side = DoubleSide;
  42872. }
  42873. } else {
  42874. this._renderObjects( renderList, camera, scene, lightsNode );
  42875. }
  42876. }
  42877. /**
  42878. * Renders the objects from the given render list.
  42879. *
  42880. * @private
  42881. * @param {Array<Object>} renderList - The render list.
  42882. * @param {Camera} camera - The camera the render list should be rendered with.
  42883. * @param {Scene} scene - The scene the render list belongs to.
  42884. * @param {LightsNode} lightsNode - The current lights node.
  42885. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42886. */
  42887. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  42888. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  42889. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  42890. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  42891. }
  42892. }
  42893. /**
  42894. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  42895. * The result is cached per material and updated when the material's version changes.
  42896. *
  42897. * @private
  42898. * @param {Material} material
  42899. * @returns {Object} - The shadow nodes for the material.
  42900. */
  42901. _getShadowNodes( material ) {
  42902. const version = material.version;
  42903. let cache = this._cacheShadowNodes.get( material );
  42904. if ( cache === undefined || cache.version !== version ) {
  42905. const hasMap = material.map !== null;
  42906. const hasColorNode = material.colorNode && material.colorNode.isNode;
  42907. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  42908. let positionNode = null;
  42909. let colorNode = null;
  42910. let depthNode = null;
  42911. if ( hasMap || hasColorNode || hasCastShadowNode ) {
  42912. let shadowRGB;
  42913. let shadowAlpha;
  42914. if ( hasCastShadowNode ) {
  42915. shadowRGB = material.castShadowNode.rgb;
  42916. shadowAlpha = material.castShadowNode.a;
  42917. } else {
  42918. shadowRGB = vec3( 0 );
  42919. shadowAlpha = float( 1 );
  42920. }
  42921. if ( hasMap ) {
  42922. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  42923. }
  42924. if ( hasColorNode ) {
  42925. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  42926. }
  42927. colorNode = vec4( shadowRGB, shadowAlpha );
  42928. }
  42929. if ( material.depthNode && material.depthNode.isNode ) {
  42930. depthNode = material.depthNode;
  42931. }
  42932. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  42933. positionNode = material.castShadowPositionNode;
  42934. } else if ( material.positionNode && material.positionNode.isNode ) {
  42935. positionNode = material.positionNode;
  42936. }
  42937. cache = {
  42938. version,
  42939. colorNode,
  42940. depthNode,
  42941. positionNode
  42942. };
  42943. this._cacheShadowNodes.set( material, cache );
  42944. }
  42945. return cache;
  42946. }
  42947. /**
  42948. * This method represents the default render object function that manages the render lifecycle
  42949. * of the object.
  42950. *
  42951. * @param {Object3D} object - The 3D object.
  42952. * @param {Scene} scene - The scene the 3D object belongs to.
  42953. * @param {Camera} camera - The camera the object should be rendered with.
  42954. * @param {BufferGeometry} geometry - The object's geometry.
  42955. * @param {Material} material - The object's material.
  42956. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42957. * @param {LightsNode} lightsNode - The current lights node.
  42958. * @param {?ClippingContext} clippingContext - The clipping context.
  42959. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42960. */
  42961. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  42962. let materialOverride = false;
  42963. let materialColorNode;
  42964. let materialDepthNode;
  42965. let materialPositionNode;
  42966. let materialSide;
  42967. //
  42968. object.onBeforeRender( this, scene, camera, geometry, material, group );
  42969. //
  42970. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  42971. const overrideMaterial = scene.overrideMaterial;
  42972. materialOverride = true;
  42973. // store original nodes
  42974. materialColorNode = scene.overrideMaterial.colorNode;
  42975. materialDepthNode = scene.overrideMaterial.depthNode;
  42976. materialPositionNode = scene.overrideMaterial.positionNode;
  42977. materialSide = scene.overrideMaterial.side;
  42978. if ( material.positionNode && material.positionNode.isNode ) {
  42979. overrideMaterial.positionNode = material.positionNode;
  42980. }
  42981. overrideMaterial.alphaTest = material.alphaTest;
  42982. overrideMaterial.alphaMap = material.alphaMap;
  42983. overrideMaterial.transparent = material.transparent || material.transmission > 0 ||
  42984. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  42985. ( material.backdropNode && material.backdropNode.isNode );
  42986. if ( overrideMaterial.isShadowPassMaterial ) {
  42987. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  42988. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  42989. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  42990. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  42991. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  42992. }
  42993. material = overrideMaterial;
  42994. }
  42995. //
  42996. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  42997. material.side = BackSide;
  42998. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  42999. material.side = FrontSide;
  43000. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  43001. material.side = DoubleSide;
  43002. } else {
  43003. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  43004. }
  43005. //
  43006. if ( materialOverride ) {
  43007. scene.overrideMaterial.colorNode = materialColorNode;
  43008. scene.overrideMaterial.depthNode = materialDepthNode;
  43009. scene.overrideMaterial.positionNode = materialPositionNode;
  43010. scene.overrideMaterial.side = materialSide;
  43011. }
  43012. //
  43013. object.onAfterRender( this, scene, camera, geometry, material, group );
  43014. }
  43015. /**
  43016. * This method represents the default `_handleObjectFunction` implementation which creates
  43017. * a render object from the given data and performs the draw command with the selected backend.
  43018. *
  43019. * @private
  43020. * @param {Object3D} object - The 3D object.
  43021. * @param {Material} material - The object's material.
  43022. * @param {Scene} scene - The scene the 3D object belongs to.
  43023. * @param {Camera} camera - The camera the object should be rendered with.
  43024. * @param {LightsNode} lightsNode - The current lights node.
  43025. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43026. * @param {ClippingContext} clippingContext - The clipping context.
  43027. * @param {string} [passId] - An optional ID for identifying the pass.
  43028. */
  43029. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  43030. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  43031. renderObject.drawRange = object.geometry.drawRange;
  43032. renderObject.group = group;
  43033. //
  43034. const needsRefresh = this._nodes.needsRefresh( renderObject );
  43035. if ( needsRefresh ) {
  43036. this._nodes.updateBefore( renderObject );
  43037. this._geometries.updateForRender( renderObject );
  43038. this._nodes.updateForRender( renderObject );
  43039. this._bindings.updateForRender( renderObject );
  43040. }
  43041. this._pipelines.updateForRender( renderObject );
  43042. //
  43043. if ( this._currentRenderBundle !== null ) {
  43044. const renderBundleData = this.backend.get( this._currentRenderBundle );
  43045. renderBundleData.renderObjects.push( renderObject );
  43046. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  43047. }
  43048. this.backend.draw( renderObject, this.info );
  43049. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  43050. }
  43051. /**
  43052. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  43053. * Used in `compileAsync()`.
  43054. *
  43055. * @private
  43056. * @param {Object3D} object - The 3D object.
  43057. * @param {Material} material - The object's material.
  43058. * @param {Scene} scene - The scene the 3D object belongs to.
  43059. * @param {Camera} camera - The camera the object should be rendered with.
  43060. * @param {LightsNode} lightsNode - The current lights node.
  43061. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43062. * @param {ClippingContext} clippingContext - The clipping context.
  43063. * @param {string} [passId] - An optional ID for identifying the pass.
  43064. */
  43065. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  43066. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  43067. renderObject.drawRange = object.geometry.drawRange;
  43068. renderObject.group = group;
  43069. //
  43070. this._nodes.updateBefore( renderObject );
  43071. this._geometries.updateForRender( renderObject );
  43072. this._nodes.updateForRender( renderObject );
  43073. this._bindings.updateForRender( renderObject );
  43074. this._pipelines.getForRender( renderObject, this._compilationPromises );
  43075. this._nodes.updateAfter( renderObject );
  43076. }
  43077. /**
  43078. * Callback when the canvas has been resized.
  43079. *
  43080. * @private
  43081. */
  43082. _onCanvasTargetResize() {
  43083. if ( this._initialized ) this.backend.updateSize();
  43084. }
  43085. /**
  43086. * Alias for `compileAsync()`.
  43087. *
  43088. * @method
  43089. * @param {Object3D} scene - The scene or 3D object to precompile.
  43090. * @param {Camera} camera - The camera that is used to render the scene.
  43091. * @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.
  43092. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  43093. */
  43094. get compile() {
  43095. return this.compileAsync;
  43096. }
  43097. }
  43098. /**
  43099. * A binding represents the connection between a resource (like a texture, sampler
  43100. * or uniform buffer) and the resource definition in a shader stage.
  43101. *
  43102. * This module is an abstract base class for all concrete bindings types.
  43103. *
  43104. * @abstract
  43105. * @private
  43106. */
  43107. class Binding {
  43108. /**
  43109. * Constructs a new binding.
  43110. *
  43111. * @param {string} [name=''] - The binding's name.
  43112. */
  43113. constructor( name = '' ) {
  43114. /**
  43115. * The binding's name.
  43116. *
  43117. * @type {string}
  43118. */
  43119. this.name = name;
  43120. /**
  43121. * A bitmask that defines in what shader stages the
  43122. * binding's resource is accessible.
  43123. *
  43124. * @type {number}
  43125. */
  43126. this.visibility = 0;
  43127. }
  43128. /**
  43129. * Makes sure binding's resource is visible for the given shader stage.
  43130. *
  43131. * @param {number} visibility - The shader stage.
  43132. */
  43133. setVisibility( visibility ) {
  43134. this.visibility |= visibility;
  43135. }
  43136. /**
  43137. * The shader stages in which the binding's resource is visible.
  43138. *
  43139. * @return {number} The visibility bitmask.
  43140. */
  43141. getVisibility() {
  43142. return this.visibility;
  43143. }
  43144. /**
  43145. * Clones the binding.
  43146. *
  43147. * @return {Binding} The cloned binding.
  43148. */
  43149. clone() {
  43150. return Object.assign( new this.constructor(), this );
  43151. }
  43152. }
  43153. /**
  43154. * This function is usually called with the length in bytes of an array buffer.
  43155. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  43156. *
  43157. * @function
  43158. * @param {number} floatLength - The buffer length.
  43159. * @return {number} The padded length.
  43160. */
  43161. function getFloatLength( floatLength ) {
  43162. // ensure chunk size alignment (STD140 layout)
  43163. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  43164. }
  43165. /**
  43166. * Represents a buffer binding type.
  43167. *
  43168. * @private
  43169. * @abstract
  43170. * @augments Binding
  43171. */
  43172. class Buffer extends Binding {
  43173. /**
  43174. * Constructs a new buffer.
  43175. *
  43176. * @param {string} name - The buffer's name.
  43177. * @param {TypedArray} [buffer=null] - The buffer.
  43178. */
  43179. constructor( name, buffer = null ) {
  43180. super( name );
  43181. /**
  43182. * This flag can be used for type testing.
  43183. *
  43184. * @type {boolean}
  43185. * @readonly
  43186. * @default true
  43187. */
  43188. this.isBuffer = true;
  43189. /**
  43190. * The bytes per element.
  43191. *
  43192. * @type {number}
  43193. */
  43194. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  43195. /**
  43196. * A reference to the internal buffer.
  43197. *
  43198. * @private
  43199. * @type {TypedArray}
  43200. */
  43201. this._buffer = buffer;
  43202. /**
  43203. * An array of update ranges.
  43204. *
  43205. * @private
  43206. * @type {Array<{start: number, count: number}>}
  43207. */
  43208. this._updateRanges = [];
  43209. }
  43210. /**
  43211. * The array of update ranges.
  43212. *
  43213. * @type {Array<{start: number, count: number}>}
  43214. */
  43215. get updateRanges() {
  43216. return this._updateRanges;
  43217. }
  43218. /**
  43219. * Adds an update range.
  43220. *
  43221. * @param {number} start - The start index.
  43222. * @param {number} count - The number of elements.
  43223. */
  43224. addUpdateRange( start, count ) {
  43225. this.updateRanges.push( { start, count } );
  43226. }
  43227. /**
  43228. * Clears all update ranges.
  43229. */
  43230. clearUpdateRanges() {
  43231. this.updateRanges.length = 0;
  43232. }
  43233. /**
  43234. * The buffer's byte length.
  43235. *
  43236. * @type {number}
  43237. * @readonly
  43238. */
  43239. get byteLength() {
  43240. return getFloatLength( this._buffer.byteLength );
  43241. }
  43242. /**
  43243. * A reference to the internal buffer.
  43244. *
  43245. * @type {Float32Array}
  43246. * @readonly
  43247. */
  43248. get buffer() {
  43249. return this._buffer;
  43250. }
  43251. /**
  43252. * Updates the binding.
  43253. *
  43254. * @return {boolean} Whether the buffer has been updated and must be
  43255. * uploaded to the GPU.
  43256. */
  43257. update() {
  43258. return true;
  43259. }
  43260. }
  43261. /**
  43262. * Represents a uniform buffer binding type.
  43263. *
  43264. * @private
  43265. * @augments Buffer
  43266. */
  43267. class UniformBuffer extends Buffer {
  43268. /**
  43269. * Constructs a new uniform buffer.
  43270. *
  43271. * @param {string} name - The buffer's name.
  43272. * @param {TypedArray} [buffer=null] - The buffer.
  43273. */
  43274. constructor( name, buffer = null ) {
  43275. super( name, buffer );
  43276. /**
  43277. * This flag can be used for type testing.
  43278. *
  43279. * @type {boolean}
  43280. * @readonly
  43281. * @default true
  43282. */
  43283. this.isUniformBuffer = true;
  43284. }
  43285. }
  43286. let _id$4 = 0;
  43287. /**
  43288. * A special form of uniform buffer binding type.
  43289. * It's buffer value is managed by a node object.
  43290. *
  43291. * @private
  43292. * @augments UniformBuffer
  43293. */
  43294. class NodeUniformBuffer extends UniformBuffer {
  43295. /**
  43296. * Constructs a new node-based uniform buffer.
  43297. *
  43298. * @param {BufferNode} nodeUniform - The uniform buffer node.
  43299. * @param {UniformGroupNode} groupNode - The uniform group node.
  43300. */
  43301. constructor( nodeUniform, groupNode ) {
  43302. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  43303. /**
  43304. * The uniform buffer node.
  43305. *
  43306. * @type {BufferNode}
  43307. */
  43308. this.nodeUniform = nodeUniform;
  43309. /**
  43310. * The uniform group node.
  43311. *
  43312. * @type {UniformGroupNode}
  43313. */
  43314. this.groupNode = groupNode;
  43315. /**
  43316. * This flag can be used for type testing.
  43317. *
  43318. * @type {boolean}
  43319. * @readonly
  43320. * @default true
  43321. */
  43322. this.isNodeUniformBuffer = true;
  43323. }
  43324. /**
  43325. * The array of update ranges.
  43326. *
  43327. * @param {Array<{start: number, count: number}>} value - The update ranges.
  43328. */
  43329. set updateRanges( value ) {
  43330. this.nodeUniform.updateRanges = value;
  43331. }
  43332. /**
  43333. * The array of update ranges.
  43334. *
  43335. * @type {Array<{start: number, count: number}>}
  43336. */
  43337. get updateRanges() {
  43338. return this.nodeUniform.updateRanges;
  43339. }
  43340. /**
  43341. * Adds a range of data in the data array to be updated on the GPU.
  43342. *
  43343. * @param {number} start - Position at which to start update.
  43344. * @param {number} count - The number of components to update.
  43345. */
  43346. addUpdateRange( start, count ) {
  43347. this.nodeUniform.addUpdateRange( start, count );
  43348. }
  43349. /**
  43350. * Clears all update ranges.
  43351. */
  43352. clearUpdateRanges() {
  43353. this.nodeUniform.clearUpdateRanges();
  43354. }
  43355. /**
  43356. * The uniform buffer.
  43357. *
  43358. * @type {Float32Array}
  43359. */
  43360. get buffer() {
  43361. return this.nodeUniform.value;
  43362. }
  43363. }
  43364. /**
  43365. * This class represents a uniform buffer binding but with
  43366. * an API that allows to maintain individual uniform objects.
  43367. *
  43368. * @private
  43369. * @augments UniformBuffer
  43370. */
  43371. class UniformsGroup extends UniformBuffer {
  43372. /**
  43373. * Constructs a new uniforms group.
  43374. *
  43375. * @param {string} name - The group's name.
  43376. */
  43377. constructor( name ) {
  43378. super( name );
  43379. /**
  43380. * This flag can be used for type testing.
  43381. *
  43382. * @type {boolean}
  43383. * @readonly
  43384. * @default true
  43385. */
  43386. this.isUniformsGroup = true;
  43387. /**
  43388. * An array with the raw uniform values.
  43389. *
  43390. * @private
  43391. * @type {?Array<number>}
  43392. * @default null
  43393. */
  43394. this._values = null;
  43395. /**
  43396. * An array of uniform objects.
  43397. *
  43398. * The order of uniforms in this array must match the order of uniforms in the shader.
  43399. *
  43400. * @type {Array<Uniform>}
  43401. */
  43402. this.uniforms = [];
  43403. }
  43404. /**
  43405. * Adds a uniform to this group.
  43406. *
  43407. * @param {Uniform} uniform - The uniform to add.
  43408. * @return {UniformsGroup} A reference to this group.
  43409. */
  43410. addUniform( uniform ) {
  43411. this.uniforms.push( uniform );
  43412. return this;
  43413. }
  43414. /**
  43415. * Removes a uniform from this group.
  43416. *
  43417. * @param {Uniform} uniform - The uniform to remove.
  43418. * @return {UniformsGroup} A reference to this group.
  43419. */
  43420. removeUniform( uniform ) {
  43421. const index = this.uniforms.indexOf( uniform );
  43422. if ( index !== -1 ) {
  43423. this.uniforms.splice( index, 1 );
  43424. }
  43425. return this;
  43426. }
  43427. /**
  43428. * An array with the raw uniform values.
  43429. *
  43430. * @type {Array<number>}
  43431. */
  43432. get values() {
  43433. if ( this._values === null ) {
  43434. this._values = Array.from( this.buffer );
  43435. }
  43436. return this._values;
  43437. }
  43438. /**
  43439. * A Float32 array buffer with the uniform values.
  43440. *
  43441. * @type {Float32Array}
  43442. */
  43443. get buffer() {
  43444. let buffer = this._buffer;
  43445. if ( buffer === null ) {
  43446. const byteLength = this.byteLength;
  43447. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  43448. this._buffer = buffer;
  43449. }
  43450. return buffer;
  43451. }
  43452. /**
  43453. * The byte length of the buffer with correct buffer alignment.
  43454. *
  43455. * @type {number}
  43456. */
  43457. get byteLength() {
  43458. const bytesPerElement = this.bytesPerElement;
  43459. let offset = 0; // global buffer offset in bytes
  43460. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  43461. const uniform = this.uniforms[ i ];
  43462. const boundary = uniform.boundary;
  43463. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  43464. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  43465. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  43466. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  43467. offset += chunkPadding;
  43468. // Check for chunk overflow
  43469. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  43470. // Add padding to the end of the chunk
  43471. offset += ( GPU_CHUNK_BYTES - chunkStart );
  43472. }
  43473. uniform.offset = offset / bytesPerElement;
  43474. offset += itemSize;
  43475. }
  43476. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  43477. }
  43478. /**
  43479. * Updates this group by updating each uniform object of
  43480. * the internal uniform list. The uniform objects check if their
  43481. * values has actually changed so this method only returns
  43482. * `true` if there is a real value change.
  43483. *
  43484. * @return {boolean} Whether the uniforms have been updated and
  43485. * must be uploaded to the GPU.
  43486. */
  43487. update() {
  43488. let updated = false;
  43489. for ( const uniform of this.uniforms ) {
  43490. if ( this.updateByType( uniform ) === true ) {
  43491. updated = true;
  43492. }
  43493. }
  43494. return updated;
  43495. }
  43496. /**
  43497. * Updates a given uniform by calling an update method matching
  43498. * the uniforms type.
  43499. *
  43500. * @param {Uniform} uniform - The uniform to update.
  43501. * @return {boolean} Whether the uniform has been updated or not.
  43502. */
  43503. updateByType( uniform ) {
  43504. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  43505. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  43506. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  43507. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  43508. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  43509. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  43510. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  43511. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  43512. }
  43513. /**
  43514. * Updates a given Number uniform.
  43515. *
  43516. * @param {NumberUniform} uniform - The Number uniform.
  43517. * @return {boolean} Whether the uniform has been updated or not.
  43518. */
  43519. updateNumber( uniform ) {
  43520. let updated = false;
  43521. const a = this.values;
  43522. const v = uniform.getValue();
  43523. const offset = uniform.offset;
  43524. const type = uniform.getType();
  43525. if ( a[ offset ] !== v ) {
  43526. const b = this._getBufferForType( type );
  43527. b[ offset ] = a[ offset ] = v;
  43528. updated = true;
  43529. }
  43530. return updated;
  43531. }
  43532. /**
  43533. * Updates a given Vector2 uniform.
  43534. *
  43535. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  43536. * @return {boolean} Whether the uniform has been updated or not.
  43537. */
  43538. updateVector2( uniform ) {
  43539. let updated = false;
  43540. const a = this.values;
  43541. const v = uniform.getValue();
  43542. const offset = uniform.offset;
  43543. const type = uniform.getType();
  43544. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  43545. const b = this._getBufferForType( type );
  43546. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43547. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43548. updated = true;
  43549. }
  43550. return updated;
  43551. }
  43552. /**
  43553. * Updates a given Vector3 uniform.
  43554. *
  43555. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  43556. * @return {boolean} Whether the uniform has been updated or not.
  43557. */
  43558. updateVector3( uniform ) {
  43559. let updated = false;
  43560. const a = this.values;
  43561. const v = uniform.getValue();
  43562. const offset = uniform.offset;
  43563. const type = uniform.getType();
  43564. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  43565. const b = this._getBufferForType( type );
  43566. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43567. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43568. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  43569. updated = true;
  43570. }
  43571. return updated;
  43572. }
  43573. /**
  43574. * Updates a given Vector4 uniform.
  43575. *
  43576. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  43577. * @return {boolean} Whether the uniform has been updated or not.
  43578. */
  43579. updateVector4( uniform ) {
  43580. let updated = false;
  43581. const a = this.values;
  43582. const v = uniform.getValue();
  43583. const offset = uniform.offset;
  43584. const type = uniform.getType();
  43585. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  43586. const b = this._getBufferForType( type );
  43587. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43588. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43589. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  43590. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  43591. updated = true;
  43592. }
  43593. return updated;
  43594. }
  43595. /**
  43596. * Updates a given Color uniform.
  43597. *
  43598. * @param {ColorUniform} uniform - The Color uniform.
  43599. * @return {boolean} Whether the uniform has been updated or not.
  43600. */
  43601. updateColor( uniform ) {
  43602. let updated = false;
  43603. const a = this.values;
  43604. const c = uniform.getValue();
  43605. const offset = uniform.offset;
  43606. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  43607. const b = this.buffer;
  43608. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  43609. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  43610. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  43611. updated = true;
  43612. }
  43613. return updated;
  43614. }
  43615. /**
  43616. * Updates a given Matrix3 uniform.
  43617. *
  43618. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  43619. * @return {boolean} Whether the uniform has been updated or not.
  43620. */
  43621. updateMatrix3( uniform ) {
  43622. let updated = false;
  43623. const a = this.values;
  43624. const e = uniform.getValue().elements;
  43625. const offset = uniform.offset;
  43626. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  43627. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  43628. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  43629. const b = this.buffer;
  43630. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  43631. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  43632. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  43633. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  43634. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  43635. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  43636. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  43637. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  43638. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  43639. updated = true;
  43640. }
  43641. return updated;
  43642. }
  43643. /**
  43644. * Updates a given Matrix4 uniform.
  43645. *
  43646. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  43647. * @return {boolean} Whether the uniform has been updated or not.
  43648. */
  43649. updateMatrix4( uniform ) {
  43650. let updated = false;
  43651. const a = this.values;
  43652. const e = uniform.getValue().elements;
  43653. const offset = uniform.offset;
  43654. if ( arraysEqual( a, e, offset ) === false ) {
  43655. const b = this.buffer;
  43656. b.set( e, offset );
  43657. setArray( a, e, offset );
  43658. updated = true;
  43659. }
  43660. return updated;
  43661. }
  43662. /**
  43663. * Returns a typed array that matches the given data type.
  43664. *
  43665. * @private
  43666. * @param {string} type - The data type.
  43667. * @return {TypedArray} The typed array.
  43668. */
  43669. _getBufferForType( type ) {
  43670. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  43671. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  43672. return this.buffer;
  43673. }
  43674. }
  43675. /**
  43676. * Sets the values of the second array to the first array.
  43677. *
  43678. * @private
  43679. * @param {TypedArray} a - The first array.
  43680. * @param {TypedArray} b - The second array.
  43681. * @param {number} offset - An index offset for the first array.
  43682. */
  43683. function setArray( a, b, offset ) {
  43684. for ( let i = 0, l = b.length; i < l; i ++ ) {
  43685. a[ offset + i ] = b[ i ];
  43686. }
  43687. }
  43688. /**
  43689. * Returns `true` if the given arrays are equal.
  43690. *
  43691. * @private
  43692. * @param {TypedArray} a - The first array.
  43693. * @param {TypedArray} b - The second array.
  43694. * @param {number} offset - An index offset for the first array.
  43695. * @return {boolean} Whether the given arrays are equal or not.
  43696. */
  43697. function arraysEqual( a, b, offset ) {
  43698. for ( let i = 0, l = b.length; i < l; i ++ ) {
  43699. if ( a[ offset + i ] !== b[ i ] ) return false;
  43700. }
  43701. return true;
  43702. }
  43703. let _id$3 = 0;
  43704. /**
  43705. * A special form of uniforms group that represents
  43706. * the individual uniforms as node-based uniforms.
  43707. *
  43708. * @private
  43709. * @augments UniformsGroup
  43710. */
  43711. class NodeUniformsGroup extends UniformsGroup {
  43712. /**
  43713. * Constructs a new node-based uniforms group.
  43714. *
  43715. * @param {string} name - The group's name.
  43716. * @param {UniformGroupNode} groupNode - The uniform group node.
  43717. */
  43718. constructor( name, groupNode ) {
  43719. super( name );
  43720. /**
  43721. * The group's ID.
  43722. *
  43723. * @type {number}
  43724. */
  43725. this.id = _id$3 ++;
  43726. /**
  43727. * The uniform group node.
  43728. *
  43729. * @type {UniformGroupNode}
  43730. */
  43731. this.groupNode = groupNode;
  43732. /**
  43733. * This flag can be used for type testing.
  43734. *
  43735. * @type {boolean}
  43736. * @readonly
  43737. * @default true
  43738. */
  43739. this.isNodeUniformsGroup = true;
  43740. }
  43741. }
  43742. /**
  43743. * Represents a sampler binding type.
  43744. *
  43745. * @private
  43746. * @augments Binding
  43747. */
  43748. class Sampler extends Binding {
  43749. /**
  43750. * Constructs a new sampler.
  43751. *
  43752. * @param {string} name - The samplers's name.
  43753. * @param {?Texture} texture - The texture this binding is referring to.
  43754. */
  43755. constructor( name, texture ) {
  43756. super( name );
  43757. /**
  43758. * The texture the sampler is referring to.
  43759. *
  43760. * @private
  43761. * @type {?Texture}
  43762. */
  43763. this._texture = null;
  43764. /**
  43765. * An event listener which is added to {@link texture}'s dispose event.
  43766. *
  43767. * @private
  43768. * @type {Function}
  43769. */
  43770. this._onTextureDispose = () => {
  43771. this.generation = null;
  43772. this.version = 0;
  43773. };
  43774. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  43775. this.texture = texture;
  43776. /**
  43777. * The binding's version.
  43778. *
  43779. * @type {number}
  43780. */
  43781. this.version = texture ? texture.version : 0;
  43782. /**
  43783. * The binding's generation which is an additional version
  43784. * qualifier.
  43785. *
  43786. * @type {?number}
  43787. * @default null
  43788. */
  43789. this.generation = null;
  43790. /**
  43791. * The binding's sampler key.
  43792. *
  43793. * @type {string}
  43794. * @default ''
  43795. */
  43796. this.samplerKey = '';
  43797. /**
  43798. * This flag can be used for type testing.
  43799. *
  43800. * @type {boolean}
  43801. * @readonly
  43802. * @default true
  43803. */
  43804. this.isSampler = true;
  43805. }
  43806. /**
  43807. * Sets the texture of this sampler.
  43808. *
  43809. * @param {Texture} value - The texture to set.
  43810. */
  43811. set texture( value ) {
  43812. if ( this._texture === value ) return;
  43813. if ( this._texture ) {
  43814. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  43815. }
  43816. this._texture = value;
  43817. this.generation = null;
  43818. this.version = 0;
  43819. if ( this._texture ) {
  43820. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  43821. }
  43822. }
  43823. /**
  43824. * Gets the texture of this sampler.
  43825. * @return {?Texture} The texture.
  43826. */
  43827. get texture() {
  43828. return this._texture;
  43829. }
  43830. /**
  43831. * Updates the binding.
  43832. *
  43833. * @return {boolean} Whether the texture has been updated and must be
  43834. * uploaded to the GPU.
  43835. */
  43836. update() {
  43837. const { texture, version } = this;
  43838. if ( version !== texture.version ) {
  43839. this.version = texture.version;
  43840. return true;
  43841. }
  43842. return false;
  43843. }
  43844. clone() {
  43845. const clonedSampler = super.clone();
  43846. // fix dispose handler for cloned instances
  43847. // TODO: Find better solution, see #31747
  43848. clonedSampler._texture = null;
  43849. clonedSampler._onTextureDispose = () => {
  43850. clonedSampler.generation = null;
  43851. clonedSampler.version = 0;
  43852. };
  43853. clonedSampler.texture = this.texture;
  43854. return clonedSampler;
  43855. }
  43856. }
  43857. let _id$2 = 0;
  43858. /**
  43859. * Represents a sampled texture binding type.
  43860. *
  43861. * @private
  43862. * @augments Sampler
  43863. */
  43864. class SampledTexture extends Sampler {
  43865. /**
  43866. * Constructs a new sampled texture.
  43867. *
  43868. * @param {string} name - The sampled texture's name.
  43869. * @param {?Texture} texture - The texture this binding is referring to.
  43870. */
  43871. constructor( name, texture ) {
  43872. super( name, texture );
  43873. /**
  43874. * This identifier.
  43875. *
  43876. * @type {number}
  43877. */
  43878. this.id = _id$2 ++;
  43879. /**
  43880. * Whether the texture is a storage texture or not.
  43881. *
  43882. * @type {boolean}
  43883. * @default false
  43884. */
  43885. this.store = false;
  43886. /**
  43887. * The mip level to bind for storage textures.
  43888. *
  43889. * @type {number}
  43890. * @default 0
  43891. */
  43892. this.mipLevel = 0;
  43893. /**
  43894. * This flag can be used for type testing.
  43895. *
  43896. * @type {boolean}
  43897. * @readonly
  43898. * @default true
  43899. */
  43900. this.isSampledTexture = true;
  43901. }
  43902. }
  43903. /**
  43904. * A special form of sampled texture binding type.
  43905. * It's texture value is managed by a node object.
  43906. *
  43907. * @private
  43908. * @augments SampledTexture
  43909. */
  43910. class NodeSampledTexture extends SampledTexture {
  43911. /**
  43912. * Constructs a new node-based sampled texture.
  43913. *
  43914. * @param {string} name - The textures's name.
  43915. * @param {TextureNode} textureNode - The texture node.
  43916. * @param {UniformGroupNode} groupNode - The uniform group node.
  43917. * @param {?string} [access=null] - The access type.
  43918. */
  43919. constructor( name, textureNode, groupNode, access = null ) {
  43920. super( name, textureNode ? textureNode.value : null );
  43921. /**
  43922. * The texture node.
  43923. *
  43924. * @type {TextureNode}
  43925. */
  43926. this.textureNode = textureNode;
  43927. /**
  43928. * The uniform group node.
  43929. *
  43930. * @type {UniformGroupNode}
  43931. */
  43932. this.groupNode = groupNode;
  43933. /**
  43934. * The access type.
  43935. *
  43936. * @type {?string}
  43937. * @default null
  43938. */
  43939. this.access = access;
  43940. }
  43941. /**
  43942. * Updates the binding.
  43943. *
  43944. * @return {boolean} Whether the texture has been updated and must be
  43945. * uploaded to the GPU.
  43946. */
  43947. update() {
  43948. const { textureNode } = this;
  43949. if ( this.texture !== textureNode.value ) {
  43950. this.texture = textureNode.value;
  43951. return true;
  43952. }
  43953. return super.update();
  43954. }
  43955. }
  43956. /**
  43957. * A special form of sampled cube texture binding type.
  43958. * It's texture value is managed by a node object.
  43959. *
  43960. * @private
  43961. * @augments NodeSampledTexture
  43962. */
  43963. class NodeSampledCubeTexture extends NodeSampledTexture {
  43964. /**
  43965. * Constructs a new node-based sampled cube texture.
  43966. *
  43967. * @param {string} name - The textures's name.
  43968. * @param {TextureNode} textureNode - The texture node.
  43969. * @param {UniformGroupNode} groupNode - The uniform group node.
  43970. * @param {?string} [access=null] - The access type.
  43971. */
  43972. constructor( name, textureNode, groupNode, access = null ) {
  43973. super( name, textureNode, groupNode, access );
  43974. /**
  43975. * This flag can be used for type testing.
  43976. *
  43977. * @type {boolean}
  43978. * @readonly
  43979. * @default true
  43980. */
  43981. this.isSampledCubeTexture = true;
  43982. }
  43983. }
  43984. /**
  43985. * A special form of sampled 3D texture binding type.
  43986. * It's texture value is managed by a node object.
  43987. *
  43988. * @private
  43989. * @augments NodeSampledTexture
  43990. */
  43991. class NodeSampledTexture3D extends NodeSampledTexture {
  43992. /**
  43993. * Constructs a new node-based sampled 3D texture.
  43994. *
  43995. * @param {string} name - The textures's name.
  43996. * @param {TextureNode} textureNode - The texture node.
  43997. * @param {UniformGroupNode} groupNode - The uniform group node.
  43998. * @param {?string} [access=null] - The access type.
  43999. */
  44000. constructor( name, textureNode, groupNode, access = null ) {
  44001. super( name, textureNode, groupNode, access );
  44002. /**
  44003. * This flag can be used for type testing.
  44004. *
  44005. * @type {boolean}
  44006. * @readonly
  44007. * @default true
  44008. */
  44009. this.isSampledTexture3D = true;
  44010. }
  44011. }
  44012. const glslPolyfills = {
  44013. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' ),
  44014. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }' )
  44015. };
  44016. const glslMethods = {
  44017. textureDimensions: 'textureSize',
  44018. equals: 'equal',
  44019. bitcast_float_int: 'floatBitsToInt',
  44020. bitcast_int_float: 'intBitsToFloat',
  44021. bitcast_uint_float: 'uintBitsToFloat',
  44022. bitcast_float_uint: 'floatBitsToUint',
  44023. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  44024. bitcast_int_uint: 'tsl_bitcast_int_to_uint',
  44025. floatpack_snorm_2x16: 'packSnorm2x16',
  44026. floatpack_unorm_2x16: 'packUnorm2x16',
  44027. floatpack_float16_2x16: 'packHalf2x16',
  44028. floatunpack_snorm_2x16: 'unpackSnorm2x16',
  44029. floatunpack_unorm_2x16: 'unpackUnorm2x16',
  44030. floatunpack_float16_2x16: 'unpackHalf2x16'
  44031. };
  44032. const precisionLib = {
  44033. low: 'lowp',
  44034. medium: 'mediump',
  44035. high: 'highp'
  44036. };
  44037. const supports$1 = {
  44038. swizzleAssign: true,
  44039. storageBuffer: false
  44040. };
  44041. const interpolationTypeMap = {
  44042. perspective: 'smooth',
  44043. linear: 'noperspective'
  44044. };
  44045. const interpolationModeMap = {
  44046. 'centroid': 'centroid'
  44047. };
  44048. const defaultPrecisions = `
  44049. precision highp float;
  44050. precision highp int;
  44051. precision highp sampler2D;
  44052. precision highp sampler3D;
  44053. precision highp samplerCube;
  44054. precision highp sampler2DArray;
  44055. precision highp usampler2D;
  44056. precision highp usampler3D;
  44057. precision highp usamplerCube;
  44058. precision highp usampler2DArray;
  44059. precision highp isampler2D;
  44060. precision highp isampler3D;
  44061. precision highp isamplerCube;
  44062. precision highp isampler2DArray;
  44063. precision lowp sampler2DShadow;
  44064. precision lowp sampler2DArrayShadow;
  44065. precision lowp samplerCubeShadow;
  44066. `;
  44067. /**
  44068. * A node builder targeting GLSL.
  44069. *
  44070. * This module generates GLSL shader code from node materials and also
  44071. * generates the respective bindings and vertex buffer definitions. These
  44072. * data are later used by the renderer to create render and compute pipelines
  44073. * for render objects.
  44074. *
  44075. * @augments NodeBuilder
  44076. */
  44077. class GLSLNodeBuilder extends NodeBuilder {
  44078. /**
  44079. * Constructs a new GLSL node builder renderer.
  44080. *
  44081. * @param {Object3D} object - The 3D object.
  44082. * @param {Renderer} renderer - The renderer.
  44083. */
  44084. constructor( object, renderer ) {
  44085. super( object, renderer, new GLSLNodeParser() );
  44086. /**
  44087. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  44088. * another dictionary which manages UBOs per group ('render','frame','object').
  44089. *
  44090. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  44091. */
  44092. this.uniformGroups = {};
  44093. /**
  44094. * An array that holds objects defining the varying and attribute data in
  44095. * context of Transform Feedback.
  44096. *
  44097. * @type {Array<Object<string,AttributeNode|string>>}
  44098. */
  44099. this.transforms = [];
  44100. /**
  44101. * A dictionary that holds for each shader stage a Map of used extensions.
  44102. *
  44103. * @type {Object<string,Map<string,Object>>}
  44104. */
  44105. this.extensions = {};
  44106. /**
  44107. * A dictionary that holds for each shader stage an Array of used builtins.
  44108. *
  44109. * @type {Object<string,Array<string>>}
  44110. */
  44111. this.builtins = { vertex: [], fragment: [], compute: [] };
  44112. }
  44113. /**
  44114. * Checks if the given texture requires a manual conversion to the working color space.
  44115. *
  44116. * @param {Texture} texture - The texture to check.
  44117. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  44118. */
  44119. needsToWorkingColorSpace( texture ) {
  44120. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  44121. }
  44122. /**
  44123. * Includes the given method name into the current
  44124. * function node.
  44125. *
  44126. * @private
  44127. * @param {string} name - The method name to include.
  44128. * @return {CodeNode} The respective code node.
  44129. */
  44130. _include( name ) {
  44131. const codeNode = glslPolyfills[ name ];
  44132. codeNode.build( this );
  44133. this.addInclude( codeNode );
  44134. return codeNode;
  44135. }
  44136. /**
  44137. * Returns the native shader method name for a given generic name.
  44138. *
  44139. * @param {string} method - The method name to resolve.
  44140. * @return {string} The resolved GLSL method name.
  44141. */
  44142. getMethod( method ) {
  44143. if ( glslPolyfills[ method ] !== undefined ) {
  44144. this._include( method );
  44145. }
  44146. return glslMethods[ method ] || method;
  44147. }
  44148. /**
  44149. * Returns the bitcast method name for a given input and outputType.
  44150. *
  44151. * @param {string} type - The output type to bitcast to.
  44152. * @param {string} inputType - The input type of the.
  44153. * @return {string} The resolved WGSL bitcast invocation.
  44154. */
  44155. getBitcastMethod( type, inputType ) {
  44156. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  44157. }
  44158. /**
  44159. * Returns the float packing method name for a given numeric encoding.
  44160. *
  44161. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  44162. * @returns {string} The resolved GLSL float packing method name.
  44163. */
  44164. getFloatPackingMethod( encoding ) {
  44165. return this.getMethod( `floatpack_${ encoding }_2x16` );
  44166. }
  44167. /**
  44168. * Returns the float unpacking method name for a given numeric encoding.
  44169. *
  44170. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  44171. * @returns {string} The resolved GLSL float unpacking method name.
  44172. */
  44173. getFloatUnpackingMethod( encoding ) {
  44174. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  44175. }
  44176. /**
  44177. * Returns the native snippet for a ternary operation.
  44178. *
  44179. * @param {string} condSnippet - The condition determining which expression gets resolved.
  44180. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  44181. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  44182. * @return {string} The resolved method name.
  44183. */
  44184. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  44185. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  44186. }
  44187. /**
  44188. * Returns the output struct name. Not relevant for GLSL.
  44189. *
  44190. * @return {string}
  44191. */
  44192. getOutputStructName() {
  44193. return '';
  44194. }
  44195. /**
  44196. * Builds the given shader node.
  44197. *
  44198. * @param {ShaderNodeInternal} shaderNode - The shader node.
  44199. * @return {string} The GLSL function code.
  44200. */
  44201. buildFunctionCode( shaderNode ) {
  44202. const layout = shaderNode.layout;
  44203. const flowData = this.flowShaderNode( shaderNode );
  44204. const parameters = [];
  44205. for ( const input of layout.inputs ) {
  44206. parameters.push( this.getType( input.type ) + ' ' + input.name );
  44207. }
  44208. //
  44209. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  44210. ${ flowData.vars }
  44211. ${ flowData.code }
  44212. return ${ flowData.result };
  44213. }`;
  44214. //
  44215. return code;
  44216. }
  44217. /**
  44218. * Setups the Pixel Buffer Object (PBO) for the given storage
  44219. * buffer node.
  44220. *
  44221. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  44222. */
  44223. setupPBO( storageBufferNode ) {
  44224. const attribute = storageBufferNode.value;
  44225. if ( attribute.pbo === undefined ) {
  44226. const originalArray = attribute.array;
  44227. const numElements = attribute.count * attribute.itemSize;
  44228. const { itemSize } = attribute;
  44229. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  44230. let format = isInteger ? RedIntegerFormat : RedFormat;
  44231. if ( itemSize === 2 ) {
  44232. format = isInteger ? RGIntegerFormat : RGFormat;
  44233. } else if ( itemSize === 3 ) {
  44234. format = isInteger ? RGBIntegerFormat : RGBFormat;
  44235. } else if ( itemSize === 4 ) {
  44236. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  44237. }
  44238. const typeMap = {
  44239. Float32Array: FloatType,
  44240. Uint8Array: UnsignedByteType,
  44241. Uint16Array: UnsignedShortType,
  44242. Uint32Array: UnsignedIntType,
  44243. Int8Array: ByteType,
  44244. Int16Array: ShortType,
  44245. Int32Array: IntType,
  44246. Uint8ClampedArray: UnsignedByteType,
  44247. };
  44248. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  44249. let height = Math.ceil( ( numElements / itemSize ) / width );
  44250. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  44251. const newSize = width * height * itemSize;
  44252. const newArray = new originalArray.constructor( newSize );
  44253. newArray.set( originalArray, 0 );
  44254. attribute.array = newArray;
  44255. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  44256. pboTexture.needsUpdate = true;
  44257. pboTexture.isPBOTexture = true;
  44258. const pbo = new TextureNode( pboTexture, null, null );
  44259. pbo.setPrecision( 'high' );
  44260. attribute.pboNode = pbo;
  44261. attribute.pbo = pbo.value;
  44262. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  44263. }
  44264. }
  44265. /**
  44266. * Returns a GLSL snippet that represents the property name of the given node.
  44267. *
  44268. * @param {Node} node - The node.
  44269. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44270. * @return {string} The property name.
  44271. */
  44272. getPropertyName( node, shaderStage = this.shaderStage ) {
  44273. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  44274. return shaderStage.charAt( 0 ) + '_' + node.name;
  44275. }
  44276. return super.getPropertyName( node, shaderStage );
  44277. }
  44278. /**
  44279. * Setups the Pixel Buffer Object (PBO) for the given storage
  44280. * buffer node.
  44281. *
  44282. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  44283. * @return {string} The property name.
  44284. */
  44285. generatePBO( storageArrayElementNode ) {
  44286. const { node, indexNode } = storageArrayElementNode;
  44287. const attribute = node.value;
  44288. if ( this.renderer.backend.has( attribute ) ) {
  44289. const attributeData = this.renderer.backend.get( attribute );
  44290. attributeData.pbo = attribute.pbo;
  44291. }
  44292. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  44293. const textureName = this.getPropertyName( nodeUniform );
  44294. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  44295. const indexSnippet = indexNode.build( this, 'uint' );
  44296. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  44297. let propertyName = elementNodeData.propertyName;
  44298. if ( propertyName === undefined ) {
  44299. // property element
  44300. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  44301. propertyName = this.getPropertyName( nodeVar );
  44302. // property size
  44303. const bufferNodeData = this.getDataFromNode( node );
  44304. let propertySizeName = bufferNodeData.propertySizeName;
  44305. if ( propertySizeName === undefined ) {
  44306. propertySizeName = propertyName + 'Size';
  44307. this.getVarFromNode( node, propertySizeName, 'uint' );
  44308. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  44309. bufferNodeData.propertySizeName = propertySizeName;
  44310. }
  44311. //
  44312. const { itemSize } = attribute;
  44313. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  44314. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  44315. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  44316. //
  44317. let prefix = 'vec4';
  44318. if ( attribute.pbo.type === UnsignedIntType ) {
  44319. prefix = 'uvec4';
  44320. } else if ( attribute.pbo.type === IntType ) {
  44321. prefix = 'ivec4';
  44322. }
  44323. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  44324. elementNodeData.propertyName = propertyName;
  44325. }
  44326. return propertyName;
  44327. }
  44328. /**
  44329. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  44330. *
  44331. * @param {?Texture} texture - The texture.
  44332. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44333. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44334. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44335. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  44336. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44337. * @return {string} The GLSL snippet.
  44338. */
  44339. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  44340. if ( levelSnippet === null ) levelSnippet = '0';
  44341. let snippet;
  44342. if ( depthSnippet ) {
  44343. if ( offsetSnippet ) {
  44344. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  44345. } else {
  44346. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  44347. }
  44348. } else {
  44349. if ( offsetSnippet ) {
  44350. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  44351. } else {
  44352. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  44353. }
  44354. }
  44355. if ( texture !== null && texture.isDepthTexture ) {
  44356. snippet += '.x';
  44357. }
  44358. return snippet;
  44359. }
  44360. /**
  44361. * Generates the GLSL snippet for sampling/loading the given texture.
  44362. *
  44363. * @param {Texture} texture - The texture.
  44364. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44365. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44366. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  44367. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44368. * @return {string} The GLSL snippet.
  44369. */
  44370. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  44371. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  44372. if ( texture.isDepthTexture ) {
  44373. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  44374. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  44375. }
  44376. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  44377. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  44378. }
  44379. /**
  44380. * Generates the GLSL snippet when sampling textures with explicit mip level.
  44381. *
  44382. * @param {Texture} texture - The texture.
  44383. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44384. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44385. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44386. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44387. * @return {string} The GLSL snippet.
  44388. */
  44389. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  44390. if ( offsetSnippet ) {
  44391. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  44392. }
  44393. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  44394. }
  44395. /**
  44396. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  44397. *
  44398. * @param {Texture} texture - The texture.
  44399. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44400. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44401. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  44402. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44403. * @return {string} The GLSL snippet.
  44404. */
  44405. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  44406. if ( offsetSnippet ) {
  44407. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  44408. }
  44409. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  44410. }
  44411. /**
  44412. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  44413. *
  44414. * @param {Texture} texture - The texture.
  44415. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44416. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44417. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  44418. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44419. * @return {string} The GLSL snippet.
  44420. */
  44421. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  44422. if ( offsetSnippet ) {
  44423. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  44424. }
  44425. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  44426. }
  44427. /**
  44428. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  44429. * against a reference value.
  44430. *
  44431. * @param {Texture} texture - The texture.
  44432. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44433. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44434. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  44435. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  44436. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44437. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44438. * @return {string} The GLSL snippet.
  44439. */
  44440. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  44441. if ( shaderStage === 'fragment' ) {
  44442. if ( depthSnippet ) {
  44443. if ( offsetSnippet ) {
  44444. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  44445. }
  44446. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  44447. }
  44448. if ( offsetSnippet ) {
  44449. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  44450. }
  44451. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  44452. } else {
  44453. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  44454. }
  44455. }
  44456. /**
  44457. * Returns the variables of the given shader stage as a GLSL string.
  44458. *
  44459. * @param {string} shaderStage - The shader stage.
  44460. * @return {string} The GLSL snippet that defines the variables.
  44461. */
  44462. getVars( shaderStage ) {
  44463. const snippets = [];
  44464. const vars = this.vars[ shaderStage ];
  44465. if ( vars !== undefined ) {
  44466. for ( const variable of vars ) {
  44467. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  44468. }
  44469. }
  44470. return snippets.join( '\n\t' );
  44471. }
  44472. /**
  44473. * Returns the uniforms of the given shader stage as a GLSL string.
  44474. *
  44475. * @param {string} shaderStage - The shader stage.
  44476. * @return {string} The GLSL snippet that defines the uniforms.
  44477. */
  44478. getUniforms( shaderStage ) {
  44479. const uniforms = this.uniforms[ shaderStage ];
  44480. const bindingSnippets = [];
  44481. const uniformGroups = {};
  44482. for ( const uniform of uniforms ) {
  44483. let snippet = null;
  44484. let group = false;
  44485. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  44486. const texture = uniform.node.value;
  44487. let typePrefix = '';
  44488. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  44489. if ( texture.type === UnsignedIntType ) {
  44490. typePrefix = 'u';
  44491. } else if ( texture.type === IntType ) {
  44492. typePrefix = 'i';
  44493. }
  44494. }
  44495. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  44496. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  44497. } else if ( texture.compareFunction ) {
  44498. if ( texture.isArrayTexture === true ) {
  44499. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  44500. } else {
  44501. snippet = `sampler2DShadow ${ uniform.name };`;
  44502. }
  44503. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  44504. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  44505. } else {
  44506. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  44507. }
  44508. } else if ( uniform.type === 'cubeTexture' ) {
  44509. snippet = `samplerCube ${ uniform.name };`;
  44510. } else if ( uniform.type === 'buffer' ) {
  44511. const bufferNode = uniform.node;
  44512. const bufferType = this.getType( bufferNode.bufferType );
  44513. const bufferCount = bufferNode.bufferCount;
  44514. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  44515. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  44516. } else {
  44517. const vectorType = this.getVectorType( uniform.type );
  44518. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  44519. group = true;
  44520. }
  44521. const precision = uniform.node.precision;
  44522. if ( precision !== null ) {
  44523. snippet = precisionLib[ precision ] + ' ' + snippet;
  44524. }
  44525. if ( group ) {
  44526. snippet = '\t' + snippet;
  44527. const groupName = uniform.groupNode.name;
  44528. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  44529. groupSnippets.push( snippet );
  44530. } else {
  44531. snippet = 'uniform ' + snippet;
  44532. bindingSnippets.push( snippet );
  44533. }
  44534. }
  44535. let output = '';
  44536. for ( const name in uniformGroups ) {
  44537. const groupSnippets = uniformGroups[ name ];
  44538. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  44539. }
  44540. output += bindingSnippets.join( '\n' );
  44541. return output;
  44542. }
  44543. /**
  44544. * Returns the type for a given buffer attribute.
  44545. *
  44546. * @param {BufferAttribute} attribute - The buffer attribute.
  44547. * @return {string} The type.
  44548. */
  44549. getTypeFromAttribute( attribute ) {
  44550. let nodeType = super.getTypeFromAttribute( attribute );
  44551. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  44552. let dataAttribute = attribute;
  44553. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  44554. const array = dataAttribute.array;
  44555. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  44556. nodeType = nodeType.slice( 1 );
  44557. }
  44558. }
  44559. return nodeType;
  44560. }
  44561. /**
  44562. * Returns the shader attributes of the given shader stage as a GLSL string.
  44563. *
  44564. * @param {string} shaderStage - The shader stage.
  44565. * @return {string} The GLSL snippet that defines the shader attributes.
  44566. */
  44567. getAttributes( shaderStage ) {
  44568. let snippet = '';
  44569. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44570. const attributes = this.getAttributesArray();
  44571. let location = 0;
  44572. for ( const attribute of attributes ) {
  44573. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  44574. }
  44575. }
  44576. return snippet;
  44577. }
  44578. /**
  44579. * Returns the members of the given struct type node as a GLSL string.
  44580. *
  44581. * @param {StructTypeNode} struct - The struct type node.
  44582. * @return {string} The GLSL snippet that defines the struct members.
  44583. */
  44584. getStructMembers( struct ) {
  44585. const snippets = [];
  44586. for ( const member of struct.members ) {
  44587. snippets.push( `\t${ member.type } ${ member.name };` );
  44588. }
  44589. return snippets.join( '\n' );
  44590. }
  44591. /**
  44592. * Returns the structs of the given shader stage as a GLSL string.
  44593. *
  44594. * @param {string} shaderStage - The shader stage.
  44595. * @return {string} The GLSL snippet that defines the structs.
  44596. */
  44597. getStructs( shaderStage ) {
  44598. const snippets = [];
  44599. const structs = this.structs[ shaderStage ];
  44600. const outputSnippet = [];
  44601. for ( const struct of structs ) {
  44602. if ( struct.output ) {
  44603. for ( const member of struct.members ) {
  44604. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  44605. }
  44606. } else {
  44607. let snippet = 'struct ' + struct.name + ' {\n';
  44608. snippet += this.getStructMembers( struct );
  44609. snippet += '\n};\n';
  44610. snippets.push( snippet );
  44611. }
  44612. }
  44613. if ( outputSnippet.length === 0 ) {
  44614. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  44615. }
  44616. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  44617. }
  44618. /**
  44619. * Returns the varyings of the given shader stage as a GLSL string.
  44620. *
  44621. * @param {string} shaderStage - The shader stage.
  44622. * @return {string} The GLSL snippet that defines the varyings.
  44623. */
  44624. getVaryings( shaderStage ) {
  44625. let snippet = '';
  44626. const varyings = this.varyings;
  44627. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44628. for ( const varying of varyings ) {
  44629. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  44630. const type = this.getType( varying.type );
  44631. if ( varying.needsInterpolation ) {
  44632. if ( varying.interpolationType ) {
  44633. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  44634. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  44635. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  44636. } else {
  44637. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  44638. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  44639. }
  44640. } else {
  44641. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  44642. }
  44643. }
  44644. } else if ( shaderStage === 'fragment' ) {
  44645. for ( const varying of varyings ) {
  44646. if ( varying.needsInterpolation ) {
  44647. const type = this.getType( varying.type );
  44648. if ( varying.interpolationType ) {
  44649. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  44650. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  44651. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  44652. } else {
  44653. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  44654. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  44655. }
  44656. }
  44657. }
  44658. }
  44659. for ( const builtin of this.builtins[ shaderStage ] ) {
  44660. snippet += `${builtin};\n`;
  44661. }
  44662. return snippet;
  44663. }
  44664. /**
  44665. * Returns the vertex index builtin.
  44666. *
  44667. * @return {string} The vertex index.
  44668. */
  44669. getVertexIndex() {
  44670. return 'uint( gl_VertexID )';
  44671. }
  44672. /**
  44673. * Contextually returns either the vertex stage instance index builtin
  44674. * or the linearized index of an compute invocation within a grid of workgroups.
  44675. *
  44676. * @return {string} The instance index.
  44677. */
  44678. getInstanceIndex() {
  44679. return 'uint( gl_InstanceID )';
  44680. }
  44681. /**
  44682. * Returns a builtin representing the index of an invocation within its workgroup.
  44683. *
  44684. * @return {string} The invocation local index.
  44685. */
  44686. getInvocationLocalIndex() {
  44687. const workgroupSize = this.object.workgroupSize;
  44688. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  44689. return `uint( gl_InstanceID ) % ${size}u`;
  44690. }
  44691. /**
  44692. * Returns a builtin representing the size of a subgroup within the current shader.
  44693. */
  44694. getSubgroupSize() {
  44695. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  44696. }
  44697. /**
  44698. * Returns a builtin representing the index of an invocation within its subgroup.
  44699. */
  44700. getInvocationSubgroupIndex() {
  44701. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  44702. }
  44703. /**
  44704. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  44705. */
  44706. getSubgroupIndex() {
  44707. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  44708. }
  44709. /**
  44710. * Returns the draw index builtin.
  44711. *
  44712. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  44713. */
  44714. getDrawIndex() {
  44715. const extensions = this.renderer.backend.extensions;
  44716. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  44717. return 'uint( gl_DrawID )';
  44718. }
  44719. return null;
  44720. }
  44721. /**
  44722. * Returns the front facing builtin.
  44723. *
  44724. * @return {string} The front facing builtin.
  44725. */
  44726. getFrontFacing() {
  44727. return 'gl_FrontFacing';
  44728. }
  44729. /**
  44730. * Returns the frag coord builtin.
  44731. *
  44732. * @return {string} The frag coord builtin.
  44733. */
  44734. getFragCoord() {
  44735. return 'gl_FragCoord.xy';
  44736. }
  44737. /**
  44738. * Returns the frag depth builtin.
  44739. *
  44740. * @return {string} The frag depth builtin.
  44741. */
  44742. getFragDepth() {
  44743. return 'gl_FragDepth';
  44744. }
  44745. /**
  44746. * Enables the given extension.
  44747. *
  44748. * @param {string} name - The extension name.
  44749. * @param {string} behavior - The extension behavior.
  44750. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  44751. */
  44752. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  44753. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  44754. if ( map.has( name ) === false ) {
  44755. map.set( name, {
  44756. name,
  44757. behavior
  44758. } );
  44759. }
  44760. }
  44761. /**
  44762. * Returns the enabled extensions of the given shader stage as a GLSL string.
  44763. *
  44764. * @param {string} shaderStage - The shader stage.
  44765. * @return {string} The GLSL snippet that defines the enabled extensions.
  44766. */
  44767. getExtensions( shaderStage ) {
  44768. const snippets = [];
  44769. if ( shaderStage === 'vertex' ) {
  44770. const ext = this.renderer.backend.extensions;
  44771. const isBatchedMesh = this.object.isBatchedMesh;
  44772. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  44773. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  44774. }
  44775. }
  44776. const extensions = this.extensions[ shaderStage ];
  44777. if ( extensions !== undefined ) {
  44778. for ( const { name, behavior } of extensions.values() ) {
  44779. snippets.push( `#extension ${name} : ${behavior}` );
  44780. }
  44781. }
  44782. return snippets.join( '\n' );
  44783. }
  44784. /**
  44785. * Returns the clip distances builtin.
  44786. *
  44787. * @return {string} The clip distances builtin.
  44788. */
  44789. getClipDistance() {
  44790. return 'gl_ClipDistance';
  44791. }
  44792. /**
  44793. * Whether the requested feature is available or not.
  44794. *
  44795. * @param {string} name - The requested feature.
  44796. * @return {boolean} Whether the requested feature is supported or not.
  44797. */
  44798. isAvailable( name ) {
  44799. let result = supports$1[ name ];
  44800. if ( result === undefined ) {
  44801. let extensionName;
  44802. result = false;
  44803. switch ( name ) {
  44804. case 'float32Filterable':
  44805. extensionName = 'OES_texture_float_linear';
  44806. break;
  44807. case 'clipDistance':
  44808. extensionName = 'WEBGL_clip_cull_distance';
  44809. break;
  44810. }
  44811. if ( extensionName !== undefined ) {
  44812. const extensions = this.renderer.backend.extensions;
  44813. if ( extensions.has( extensionName ) ) {
  44814. extensions.get( extensionName );
  44815. result = true;
  44816. }
  44817. }
  44818. supports$1[ name ] = result;
  44819. }
  44820. return result;
  44821. }
  44822. /**
  44823. * Whether to flip texture data along its vertical axis or not.
  44824. *
  44825. * @return {boolean} Returns always `true` in context of GLSL.
  44826. */
  44827. isFlipY() {
  44828. return true;
  44829. }
  44830. /**
  44831. * Enables hardware clipping.
  44832. *
  44833. * @param {string} planeCount - The clipping plane count.
  44834. */
  44835. enableHardwareClipping( planeCount ) {
  44836. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  44837. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  44838. }
  44839. /**
  44840. * Enables multiview.
  44841. */
  44842. enableMultiview() {
  44843. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  44844. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  44845. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  44846. }
  44847. /**
  44848. * Registers a transform in context of Transform Feedback.
  44849. *
  44850. * @param {string} varyingName - The varying name.
  44851. * @param {AttributeNode} attributeNode - The attribute node.
  44852. */
  44853. registerTransform( varyingName, attributeNode ) {
  44854. this.transforms.push( { varyingName, attributeNode } );
  44855. }
  44856. /**
  44857. * Returns the transforms of the given shader stage as a GLSL string.
  44858. *
  44859. * @param {string} shaderStage - The shader stage.
  44860. * @return {string} The GLSL snippet that defines the transforms.
  44861. */
  44862. getTransforms( /* shaderStage */ ) {
  44863. const transforms = this.transforms;
  44864. let snippet = '';
  44865. for ( let i = 0; i < transforms.length; i ++ ) {
  44866. const transform = transforms[ i ];
  44867. const attributeName = this.getPropertyName( transform.attributeNode );
  44868. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  44869. }
  44870. return snippet;
  44871. }
  44872. /**
  44873. * Returns a GLSL struct based on the given name and variables.
  44874. *
  44875. * @private
  44876. * @param {string} name - The struct name.
  44877. * @param {string} vars - The struct variables.
  44878. * @return {string} The GLSL snippet representing a struct.
  44879. */
  44880. _getGLSLUniformStruct( name, vars ) {
  44881. return `
  44882. layout( std140 ) uniform ${name} {
  44883. ${vars}
  44884. };`;
  44885. }
  44886. /**
  44887. * Returns a GLSL vertex shader based on the given shader data.
  44888. *
  44889. * @private
  44890. * @param {Object} shaderData - The shader data.
  44891. * @return {string} The vertex shader.
  44892. */
  44893. _getGLSLVertexCode( shaderData ) {
  44894. return `#version 300 es
  44895. ${ this.getSignature() }
  44896. // extensions
  44897. ${shaderData.extensions}
  44898. // precision
  44899. ${ defaultPrecisions }
  44900. // uniforms
  44901. ${shaderData.uniforms}
  44902. // varyings
  44903. ${shaderData.varyings}
  44904. // attributes
  44905. ${shaderData.attributes}
  44906. // codes
  44907. ${shaderData.codes}
  44908. void main() {
  44909. // vars
  44910. ${shaderData.vars}
  44911. // transforms
  44912. ${shaderData.transforms}
  44913. // flow
  44914. ${shaderData.flow}
  44915. gl_PointSize = 1.0;
  44916. }
  44917. `;
  44918. }
  44919. /**
  44920. * Returns a GLSL fragment shader based on the given shader data.
  44921. *
  44922. * @private
  44923. * @param {Object} shaderData - The shader data.
  44924. * @return {string} The vertex shader.
  44925. */
  44926. _getGLSLFragmentCode( shaderData ) {
  44927. return `#version 300 es
  44928. ${ this.getSignature() }
  44929. // extensions
  44930. ${shaderData.extensions}
  44931. // precision
  44932. ${ defaultPrecisions }
  44933. // structs
  44934. ${shaderData.structs}
  44935. // uniforms
  44936. ${shaderData.uniforms}
  44937. // varyings
  44938. ${shaderData.varyings}
  44939. // codes
  44940. ${shaderData.codes}
  44941. void main() {
  44942. // vars
  44943. ${shaderData.vars}
  44944. // flow
  44945. ${shaderData.flow}
  44946. }
  44947. `;
  44948. }
  44949. /**
  44950. * Controls the code build of the shader stages.
  44951. */
  44952. buildCode() {
  44953. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  44954. this.sortBindingGroups();
  44955. for ( const shaderStage in shadersData ) {
  44956. let flow = '// code\n\n';
  44957. flow += this.flowCode[ shaderStage ];
  44958. const flowNodes = this.flowNodes[ shaderStage ];
  44959. const mainNode = flowNodes[ flowNodes.length - 1 ];
  44960. for ( const node of flowNodes ) {
  44961. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  44962. const slotName = node.name;
  44963. if ( slotName ) {
  44964. if ( flow.length > 0 ) flow += '\n';
  44965. flow += `\t// flow -> ${ slotName }\n\t`;
  44966. }
  44967. flow += `${ flowSlotData.code }\n\t`;
  44968. if ( node === mainNode && shaderStage !== 'compute' ) {
  44969. flow += '// result\n\t';
  44970. if ( shaderStage === 'vertex' ) {
  44971. flow += 'gl_Position = ';
  44972. flow += `${ flowSlotData.result };`;
  44973. } else if ( shaderStage === 'fragment' ) {
  44974. if ( ! node.outputNode.isOutputStructNode ) {
  44975. flow += 'fragColor = ';
  44976. flow += `${ flowSlotData.result };`;
  44977. }
  44978. }
  44979. }
  44980. }
  44981. const stageData = shadersData[ shaderStage ];
  44982. stageData.extensions = this.getExtensions( shaderStage );
  44983. stageData.uniforms = this.getUniforms( shaderStage );
  44984. stageData.attributes = this.getAttributes( shaderStage );
  44985. stageData.varyings = this.getVaryings( shaderStage );
  44986. stageData.vars = this.getVars( shaderStage );
  44987. stageData.structs = this.getStructs( shaderStage );
  44988. stageData.codes = this.getCodes( shaderStage );
  44989. stageData.transforms = this.getTransforms( shaderStage );
  44990. stageData.flow = flow;
  44991. }
  44992. if ( this.material !== null ) {
  44993. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  44994. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  44995. } else {
  44996. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  44997. }
  44998. }
  44999. /**
  45000. * This method is one of the more important ones since it's responsible
  45001. * for generating a matching binding instance for the given uniform node.
  45002. *
  45003. * These bindings are later used in the renderer to create bind groups
  45004. * and layouts.
  45005. *
  45006. * @param {UniformNode} node - The uniform node.
  45007. * @param {string} type - The node data type.
  45008. * @param {string} shaderStage - The shader stage.
  45009. * @param {?string} [name=null] - An optional uniform name.
  45010. * @return {NodeUniform} The node uniform object.
  45011. */
  45012. getUniformFromNode( node, type, shaderStage, name = null ) {
  45013. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  45014. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  45015. let uniformGPU = nodeData.uniformGPU;
  45016. if ( uniformGPU === undefined ) {
  45017. const group = node.groupNode;
  45018. const groupName = group.name;
  45019. const bindings = this.getBindGroupArray( groupName, shaderStage );
  45020. if ( type === 'texture' ) {
  45021. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  45022. bindings.push( uniformGPU );
  45023. } else if ( type === 'cubeTexture' ) {
  45024. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  45025. bindings.push( uniformGPU );
  45026. } else if ( type === 'texture3D' ) {
  45027. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  45028. bindings.push( uniformGPU );
  45029. } else if ( type === 'buffer' ) {
  45030. uniformNode.name = `buffer${ node.id }`;
  45031. const sharedData = this.getSharedDataFromNode( node );
  45032. let buffer = sharedData.buffer;
  45033. if ( buffer === undefined ) {
  45034. node.name = `NodeBuffer_${ node.id }`;
  45035. buffer = new NodeUniformBuffer( node, group );
  45036. buffer.name = node.name;
  45037. sharedData.buffer = buffer;
  45038. }
  45039. bindings.push( buffer );
  45040. uniformGPU = buffer;
  45041. } else {
  45042. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  45043. let uniformsGroup = uniformsStage[ groupName ];
  45044. if ( uniformsGroup === undefined ) {
  45045. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  45046. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45047. uniformsStage[ groupName ] = uniformsGroup;
  45048. bindings.push( uniformsGroup );
  45049. }
  45050. uniformGPU = this.getNodeUniform( uniformNode, type );
  45051. uniformsGroup.addUniform( uniformGPU );
  45052. }
  45053. nodeData.uniformGPU = uniformGPU;
  45054. }
  45055. return uniformNode;
  45056. }
  45057. }
  45058. let _vector2 = null;
  45059. let _color4 = null;
  45060. /**
  45061. * Most of the rendering related logic is implemented in the
  45062. * {@link Renderer} module and related management components.
  45063. * Sometimes it is required though to execute commands which are
  45064. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  45065. * This abstract base class defines an interface that encapsulates
  45066. * all backend-related logic. Derived classes for each backend must
  45067. * implement the interface.
  45068. *
  45069. * @abstract
  45070. * @private
  45071. */
  45072. class Backend {
  45073. /**
  45074. * Constructs a new backend.
  45075. *
  45076. * @param {Object} parameters - An object holding parameters for the backend.
  45077. */
  45078. constructor( parameters = {} ) {
  45079. /**
  45080. * The parameters of the backend.
  45081. *
  45082. * @type {Object}
  45083. */
  45084. this.parameters = Object.assign( {}, parameters );
  45085. /**
  45086. * This weak map holds backend-specific data of objects
  45087. * like textures, attributes or render targets.
  45088. *
  45089. * @type {WeakMap<Object, Object>}
  45090. */
  45091. this.data = new WeakMap();
  45092. /**
  45093. * A reference to the renderer.
  45094. *
  45095. * @type {?Renderer}
  45096. * @default null
  45097. */
  45098. this.renderer = null;
  45099. /**
  45100. * A reference to the canvas element the renderer is drawing to.
  45101. *
  45102. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  45103. * @default null
  45104. */
  45105. this.domElement = null;
  45106. /**
  45107. * A reference to the timestamp query pool.
  45108. *
  45109. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  45110. */
  45111. this.timestampQueryPool = {
  45112. [ TimestampQuery.RENDER ]: null,
  45113. [ TimestampQuery.COMPUTE ]: null
  45114. };
  45115. /**
  45116. * Whether to track timestamps with a Timestamp Query API or not.
  45117. *
  45118. * @type {boolean}
  45119. * @default false
  45120. */
  45121. this.trackTimestamp = ( parameters.trackTimestamp === true );
  45122. }
  45123. /**
  45124. * Initializes the backend so it is ready for usage. Concrete backends
  45125. * are supposed to implement their rendering context creation and related
  45126. * operations in this method.
  45127. *
  45128. * @async
  45129. * @param {Renderer} renderer - The renderer.
  45130. * @return {Promise} A Promise that resolves when the backend has been initialized.
  45131. */
  45132. async init( renderer ) {
  45133. this.renderer = renderer;
  45134. }
  45135. /**
  45136. * The coordinate system of the backend.
  45137. *
  45138. * @abstract
  45139. * @type {number}
  45140. * @readonly
  45141. */
  45142. get coordinateSystem() {}
  45143. // render context
  45144. /**
  45145. * This method is executed at the beginning of a render call and
  45146. * can be used by the backend to prepare the state for upcoming
  45147. * draw calls.
  45148. *
  45149. * @abstract
  45150. * @param {RenderContext} renderContext - The render context.
  45151. */
  45152. beginRender( /*renderContext*/ ) {}
  45153. /**
  45154. * This method is executed at the end of a render call and
  45155. * can be used by the backend to finalize work after draw
  45156. * calls.
  45157. *
  45158. * @abstract
  45159. * @param {RenderContext} renderContext - The render context.
  45160. */
  45161. finishRender( /*renderContext*/ ) {}
  45162. /**
  45163. * This method is executed at the beginning of a compute call and
  45164. * can be used by the backend to prepare the state for upcoming
  45165. * compute tasks.
  45166. *
  45167. * @abstract
  45168. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45169. */
  45170. beginCompute( /*computeGroup*/ ) {}
  45171. /**
  45172. * This method is executed at the end of a compute call and
  45173. * can be used by the backend to finalize work after compute
  45174. * tasks.
  45175. *
  45176. * @abstract
  45177. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45178. */
  45179. finishCompute( /*computeGroup*/ ) {}
  45180. // render object
  45181. /**
  45182. * Executes a draw command for the given render object.
  45183. *
  45184. * @abstract
  45185. * @param {RenderObject} renderObject - The render object to draw.
  45186. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  45187. */
  45188. draw( /*renderObject, info*/ ) { }
  45189. // compute node
  45190. /**
  45191. * Executes a compute command for the given compute node.
  45192. *
  45193. * @abstract
  45194. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  45195. * @param {Node} computeNode - The compute node.
  45196. * @param {Array<BindGroup>} bindings - The bindings.
  45197. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45198. */
  45199. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  45200. // program
  45201. /**
  45202. * Creates a shader program from the given programmable stage.
  45203. *
  45204. * @abstract
  45205. * @param {ProgrammableStage} program - The programmable stage.
  45206. */
  45207. createProgram( /*program*/ ) { }
  45208. /**
  45209. * Destroys the shader program of the given programmable stage.
  45210. *
  45211. * @abstract
  45212. * @param {ProgrammableStage} program - The programmable stage.
  45213. */
  45214. destroyProgram( /*program*/ ) { }
  45215. // bindings
  45216. /**
  45217. * Creates bindings from the given bind group definition.
  45218. *
  45219. * @abstract
  45220. * @param {BindGroup} bindGroup - The bind group.
  45221. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45222. * @param {number} cacheIndex - The cache index.
  45223. * @param {number} version - The version.
  45224. */
  45225. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  45226. /**
  45227. * Updates the given bind group definition.
  45228. *
  45229. * @abstract
  45230. * @param {BindGroup} bindGroup - The bind group.
  45231. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45232. * @param {number} cacheIndex - The cache index.
  45233. * @param {number} version - The version.
  45234. */
  45235. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  45236. /**
  45237. * Updates a buffer binding.
  45238. *
  45239. * @abstract
  45240. * @param {Buffer} binding - The buffer binding to update.
  45241. */
  45242. updateBinding( /*binding*/ ) { }
  45243. // pipeline
  45244. /**
  45245. * Creates a render pipeline for the given render object.
  45246. *
  45247. * @abstract
  45248. * @param {RenderObject} renderObject - The render object.
  45249. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  45250. */
  45251. createRenderPipeline( /*renderObject, promises*/ ) { }
  45252. /**
  45253. * Creates a compute pipeline for the given compute node.
  45254. *
  45255. * @abstract
  45256. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45257. * @param {Array<BindGroup>} bindings - The bindings.
  45258. */
  45259. createComputePipeline( /*computePipeline, bindings*/ ) { }
  45260. // cache key
  45261. /**
  45262. * Returns `true` if the render pipeline requires an update.
  45263. *
  45264. * @abstract
  45265. * @param {RenderObject} renderObject - The render object.
  45266. * @return {boolean} Whether the render pipeline requires an update or not.
  45267. */
  45268. needsRenderUpdate( /*renderObject*/ ) { }
  45269. /**
  45270. * Returns a cache key that is used to identify render pipelines.
  45271. *
  45272. * @abstract
  45273. * @param {RenderObject} renderObject - The render object.
  45274. * @return {string} The cache key.
  45275. */
  45276. getRenderCacheKey( /*renderObject*/ ) { }
  45277. // node builder
  45278. /**
  45279. * Returns a node builder for the given render object.
  45280. *
  45281. * @abstract
  45282. * @param {RenderObject} renderObject - The render object.
  45283. * @param {Renderer} renderer - The renderer.
  45284. * @return {NodeBuilder} The node builder.
  45285. */
  45286. createNodeBuilder( /*renderObject, renderer*/ ) { }
  45287. // textures
  45288. /**
  45289. * Updates a GPU sampler for the given texture.
  45290. *
  45291. * @abstract
  45292. * @param {Texture} texture - The texture to update the sampler for.
  45293. * @return {string} The current sampler key.
  45294. */
  45295. updateSampler( /*texture*/ ) { }
  45296. /**
  45297. * Creates a default texture for the given texture that can be used
  45298. * as a placeholder until the actual texture is ready for usage.
  45299. *
  45300. * @abstract
  45301. * @param {Texture} texture - The texture to create a default texture for.
  45302. */
  45303. createDefaultTexture( /*texture*/ ) { }
  45304. /**
  45305. * Defines a texture on the GPU for the given texture object.
  45306. *
  45307. * @abstract
  45308. * @param {Texture} texture - The texture.
  45309. * @param {Object} [options={}] - Optional configuration parameter.
  45310. */
  45311. createTexture( /*texture, options={}*/ ) { }
  45312. /**
  45313. * Uploads the updated texture data to the GPU.
  45314. *
  45315. * @abstract
  45316. * @param {Texture} texture - The texture.
  45317. * @param {Object} [options={}] - Optional configuration parameter.
  45318. */
  45319. updateTexture( /*texture, options = {}*/ ) { }
  45320. /**
  45321. * Generates mipmaps for the given texture.
  45322. *
  45323. * @abstract
  45324. * @param {Texture} texture - The texture.
  45325. */
  45326. generateMipmaps( /*texture*/ ) { }
  45327. /**
  45328. * Destroys the GPU data for the given texture object.
  45329. *
  45330. * @abstract
  45331. * @param {Texture} texture - The texture.
  45332. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  45333. */
  45334. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  45335. /**
  45336. * Returns texture data as a typed array.
  45337. *
  45338. * @abstract
  45339. * @async
  45340. * @param {Texture} texture - The texture to copy.
  45341. * @param {number} x - The x coordinate of the copy origin.
  45342. * @param {number} y - The y coordinate of the copy origin.
  45343. * @param {number} width - The width of the copy.
  45344. * @param {number} height - The height of the copy.
  45345. * @param {number} faceIndex - The face index.
  45346. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45347. */
  45348. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  45349. /**
  45350. * Copies data of the given source texture to the given destination texture.
  45351. *
  45352. * @abstract
  45353. * @param {Texture} srcTexture - The source texture.
  45354. * @param {Texture} dstTexture - The destination texture.
  45355. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  45356. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  45357. * @param {number} [srcLevel=0] - The source mip level to copy from.
  45358. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  45359. */
  45360. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  45361. /**
  45362. * Copies the current bound framebuffer to the given texture.
  45363. *
  45364. * @abstract
  45365. * @param {Texture} texture - The destination texture.
  45366. * @param {RenderContext} renderContext - The render context.
  45367. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  45368. */
  45369. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  45370. // attributes
  45371. /**
  45372. * Creates the GPU buffer of a shader attribute.
  45373. *
  45374. * @abstract
  45375. * @param {BufferAttribute} attribute - The buffer attribute.
  45376. */
  45377. createAttribute( /*attribute*/ ) { }
  45378. /**
  45379. * Creates the GPU buffer of an indexed shader attribute.
  45380. *
  45381. * @abstract
  45382. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  45383. */
  45384. createIndexAttribute( /*attribute*/ ) { }
  45385. /**
  45386. * Creates the GPU buffer of a storage attribute.
  45387. *
  45388. * @abstract
  45389. * @param {BufferAttribute} attribute - The buffer attribute.
  45390. */
  45391. createStorageAttribute( /*attribute*/ ) { }
  45392. /**
  45393. * Updates the GPU buffer of a shader attribute.
  45394. *
  45395. * @abstract
  45396. * @param {BufferAttribute} attribute - The buffer attribute to update.
  45397. */
  45398. updateAttribute( /*attribute*/ ) { }
  45399. /**
  45400. * Destroys the GPU buffer of a shader attribute.
  45401. *
  45402. * @abstract
  45403. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  45404. */
  45405. destroyAttribute( /*attribute*/ ) { }
  45406. // canvas
  45407. /**
  45408. * Returns the backend's rendering context.
  45409. *
  45410. * @abstract
  45411. * @return {Object} The rendering context.
  45412. */
  45413. getContext() { }
  45414. /**
  45415. * Backends can use this method if they have to run
  45416. * logic when the renderer gets resized.
  45417. *
  45418. * @abstract
  45419. */
  45420. updateSize() { }
  45421. /**
  45422. * Updates the viewport with the values from the given render context.
  45423. *
  45424. * @abstract
  45425. * @param {RenderContext} renderContext - The render context.
  45426. */
  45427. updateViewport( /*renderContext*/ ) {}
  45428. // utils
  45429. /**
  45430. * Updates a unique identifier for the given render context that can be used
  45431. * to allocate resources like occlusion queries or timestamp queries.
  45432. *
  45433. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  45434. */
  45435. updateTimeStampUID( abstractRenderContext ) {
  45436. const contextData = this.get( abstractRenderContext );
  45437. const frame = this.renderer.info.frame;
  45438. let prefix;
  45439. if ( abstractRenderContext.isComputeNode === true ) {
  45440. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  45441. } else {
  45442. prefix = 'r:' + this.renderer.info.render.frameCalls;
  45443. }
  45444. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  45445. }
  45446. /**
  45447. * Returns a unique identifier for the given render context that can be used
  45448. * to allocate resources like occlusion queries or timestamp queries.
  45449. *
  45450. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  45451. * @return {string} The unique identifier.
  45452. */
  45453. getTimestampUID( abstractRenderContext ) {
  45454. return this.get( abstractRenderContext ).timestampUID;
  45455. }
  45456. /**
  45457. * Returns all timestamp frames for the given type.
  45458. *
  45459. * @param {string} type - The type of the time stamp.
  45460. * @return {Array<number>} The timestamp frames.
  45461. */
  45462. getTimestampFrames( type ) {
  45463. const queryPool = this.timestampQueryPool[ type ];
  45464. return queryPool ? queryPool.getTimestampFrames() : [];
  45465. }
  45466. /**
  45467. * Returns the query pool for the given uid.
  45468. *
  45469. * @param {string} uid - The unique identifier.
  45470. * @return {TimestampQueryPool} The query pool.
  45471. */
  45472. _getQueryPool( uid ) {
  45473. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  45474. const queryPool = this.timestampQueryPool[ type ];
  45475. return queryPool;
  45476. }
  45477. /**
  45478. * Returns the timestamp for the given uid.
  45479. *
  45480. * @param {string} uid - The unique identifier.
  45481. * @return {number} The timestamp.
  45482. */
  45483. getTimestamp( uid ) {
  45484. const queryPool = this._getQueryPool( uid );
  45485. return queryPool.getTimestamp( uid );
  45486. }
  45487. /**
  45488. * Returns `true` if a timestamp for the given uid is available.
  45489. *
  45490. * @param {string} uid - The unique identifier.
  45491. * @return {boolean} Whether the timestamp is available or not.
  45492. */
  45493. hasTimestamp( uid ) {
  45494. const queryPool = this._getQueryPool( uid );
  45495. return queryPool.hasTimestamp( uid );
  45496. }
  45497. /**
  45498. * Returns `true` if the given 3D object is fully occluded by other
  45499. * 3D objects in the scene. Backends must implement this method by using
  45500. * a Occlusion Query API.
  45501. *
  45502. * @abstract
  45503. * @param {RenderContext} renderContext - The render context.
  45504. * @param {Object3D} object - The 3D object to test.
  45505. * @return {boolean} Whether the 3D object is fully occluded or not.
  45506. */
  45507. isOccluded( /*renderContext, object*/ ) {}
  45508. /**
  45509. * Resolves the time stamp for the given render context and type.
  45510. *
  45511. * @async
  45512. * @abstract
  45513. * @param {string} [type='render'] - The type of the time stamp.
  45514. * @return {Promise<number>} A Promise that resolves with the time stamp.
  45515. */
  45516. async resolveTimestampsAsync( type = 'render' ) {
  45517. if ( ! this.trackTimestamp ) {
  45518. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  45519. return;
  45520. }
  45521. const queryPool = this.timestampQueryPool[ type ];
  45522. if ( ! queryPool ) {
  45523. return;
  45524. }
  45525. const duration = await queryPool.resolveQueriesAsync();
  45526. this.renderer.info[ type ].timestamp = duration;
  45527. return duration;
  45528. }
  45529. /**
  45530. * This method performs a readback operation by moving buffer data from
  45531. * a storage buffer attribute from the GPU to the CPU.
  45532. *
  45533. * @async
  45534. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45535. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45536. */
  45537. async getArrayBufferAsync( /* attribute */ ) {}
  45538. /**
  45539. * Checks if the given feature is supported by the backend.
  45540. *
  45541. * @async
  45542. * @abstract
  45543. * @param {string} name - The feature's name.
  45544. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  45545. */
  45546. async hasFeatureAsync( /*name*/ ) { }
  45547. /**
  45548. * Checks if the given feature is supported by the backend.
  45549. *
  45550. * @abstract
  45551. * @param {string} name - The feature's name.
  45552. * @return {boolean} Whether the feature is supported or not.
  45553. */
  45554. hasFeature( /*name*/ ) {}
  45555. /**
  45556. * Returns the maximum anisotropy texture filtering value.
  45557. *
  45558. * @abstract
  45559. * @return {number} The maximum anisotropy texture filtering value.
  45560. */
  45561. getMaxAnisotropy() {}
  45562. /**
  45563. * Returns the drawing buffer size.
  45564. *
  45565. * @return {Vector2} The drawing buffer size.
  45566. */
  45567. getDrawingBufferSize() {
  45568. _vector2 = _vector2 || new Vector2();
  45569. return this.renderer.getDrawingBufferSize( _vector2 );
  45570. }
  45571. /**
  45572. * Defines the scissor test.
  45573. *
  45574. * @abstract
  45575. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  45576. */
  45577. setScissorTest( /*boolean*/ ) { }
  45578. /**
  45579. * Returns the clear color and alpha into a single
  45580. * color object.
  45581. *
  45582. * @return {Color4} The clear color.
  45583. */
  45584. getClearColor() {
  45585. const renderer = this.renderer;
  45586. _color4 = _color4 || new Color4();
  45587. renderer.getClearColor( _color4 );
  45588. _color4.getRGB( _color4 );
  45589. return _color4;
  45590. }
  45591. /**
  45592. * Returns the DOM element. If no DOM element exists, the backend
  45593. * creates a new one.
  45594. *
  45595. * @return {HTMLCanvasElement} The DOM element.
  45596. */
  45597. getDomElement() {
  45598. let domElement = this.domElement;
  45599. if ( domElement === null ) {
  45600. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  45601. // OffscreenCanvas does not have setAttribute, see #22811
  45602. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  45603. this.domElement = domElement;
  45604. }
  45605. return domElement;
  45606. }
  45607. /**
  45608. * Sets a dictionary for the given object into the
  45609. * internal data structure.
  45610. *
  45611. * @param {Object} object - The object.
  45612. * @param {Object} value - The dictionary to set.
  45613. */
  45614. set( object, value ) {
  45615. this.data.set( object, value );
  45616. }
  45617. /**
  45618. * Returns the dictionary for the given object.
  45619. *
  45620. * @param {Object} object - The object.
  45621. * @return {Object} The object's dictionary.
  45622. */
  45623. get( object ) {
  45624. let map = this.data.get( object );
  45625. if ( map === undefined ) {
  45626. map = {};
  45627. this.data.set( object, map );
  45628. }
  45629. return map;
  45630. }
  45631. /**
  45632. * Checks if the given object has a dictionary
  45633. * with data defined.
  45634. *
  45635. * @param {Object} object - The object.
  45636. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  45637. */
  45638. has( object ) {
  45639. return this.data.has( object );
  45640. }
  45641. /**
  45642. * Deletes an object from the internal data structure.
  45643. *
  45644. * @param {Object} object - The object to delete.
  45645. */
  45646. delete( object ) {
  45647. this.data.delete( object );
  45648. }
  45649. /**
  45650. * Frees internal resources.
  45651. *
  45652. * @abstract
  45653. */
  45654. dispose() { }
  45655. }
  45656. let _id$1 = 0;
  45657. /**
  45658. * This module is internally used in context of compute shaders.
  45659. * This type of shader is not natively supported in WebGL 2 and
  45660. * thus implemented via Transform Feedback. `DualAttributeData`
  45661. * manages the related data.
  45662. *
  45663. * @private
  45664. */
  45665. class DualAttributeData {
  45666. constructor( attributeData, dualBuffer ) {
  45667. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  45668. this.type = attributeData.type;
  45669. this.bufferType = attributeData.bufferType;
  45670. this.pbo = attributeData.pbo;
  45671. this.byteLength = attributeData.byteLength;
  45672. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  45673. this.version = attributeData.version;
  45674. this.isInteger = attributeData.isInteger;
  45675. this.activeBufferIndex = 0;
  45676. this.baseId = attributeData.id;
  45677. }
  45678. get id() {
  45679. return `${ this.baseId }|${ this.activeBufferIndex }`;
  45680. }
  45681. get bufferGPU() {
  45682. return this.buffers[ this.activeBufferIndex ];
  45683. }
  45684. get transformBuffer() {
  45685. return this.buffers[ this.activeBufferIndex ^ 1 ];
  45686. }
  45687. switchBuffers() {
  45688. this.activeBufferIndex ^= 1;
  45689. }
  45690. }
  45691. /**
  45692. * A WebGL 2 backend utility module for managing shader attributes.
  45693. *
  45694. * @private
  45695. */
  45696. class WebGLAttributeUtils {
  45697. /**
  45698. * Constructs a new utility object.
  45699. *
  45700. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45701. */
  45702. constructor( backend ) {
  45703. /**
  45704. * A reference to the WebGL 2 backend.
  45705. *
  45706. * @type {WebGLBackend}
  45707. */
  45708. this.backend = backend;
  45709. }
  45710. /**
  45711. * Creates the GPU buffer for the given buffer attribute.
  45712. *
  45713. * @param {BufferAttribute} attribute - The buffer attribute.
  45714. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  45715. */
  45716. createAttribute( attribute, bufferType ) {
  45717. const backend = this.backend;
  45718. const { gl } = backend;
  45719. const array = attribute.array;
  45720. const usage = attribute.usage || gl.STATIC_DRAW;
  45721. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  45722. const bufferData = backend.get( bufferAttribute );
  45723. let bufferGPU = bufferData.bufferGPU;
  45724. if ( bufferGPU === undefined ) {
  45725. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  45726. bufferData.bufferGPU = bufferGPU;
  45727. bufferData.bufferType = bufferType;
  45728. bufferData.version = bufferAttribute.version;
  45729. }
  45730. //attribute.onUploadCallback();
  45731. let type;
  45732. if ( array instanceof Float32Array ) {
  45733. type = gl.FLOAT;
  45734. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  45735. type = gl.HALF_FLOAT;
  45736. } else if ( array instanceof Uint16Array ) {
  45737. if ( attribute.isFloat16BufferAttribute ) {
  45738. type = gl.HALF_FLOAT;
  45739. } else {
  45740. type = gl.UNSIGNED_SHORT;
  45741. }
  45742. } else if ( array instanceof Int16Array ) {
  45743. type = gl.SHORT;
  45744. } else if ( array instanceof Uint32Array ) {
  45745. type = gl.UNSIGNED_INT;
  45746. } else if ( array instanceof Int32Array ) {
  45747. type = gl.INT;
  45748. } else if ( array instanceof Int8Array ) {
  45749. type = gl.BYTE;
  45750. } else if ( array instanceof Uint8Array ) {
  45751. type = gl.UNSIGNED_BYTE;
  45752. } else if ( array instanceof Uint8ClampedArray ) {
  45753. type = gl.UNSIGNED_BYTE;
  45754. } else {
  45755. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  45756. }
  45757. let attributeData = {
  45758. bufferGPU,
  45759. bufferType,
  45760. type,
  45761. byteLength: array.byteLength,
  45762. bytesPerElement: array.BYTES_PER_ELEMENT,
  45763. version: attribute.version,
  45764. pbo: attribute.pbo,
  45765. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  45766. id: _id$1 ++
  45767. };
  45768. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  45769. // create buffer for transform feedback use
  45770. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  45771. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  45772. }
  45773. backend.set( attribute, attributeData );
  45774. }
  45775. /**
  45776. * Updates the GPU buffer of the given buffer attribute.
  45777. *
  45778. * @param {BufferAttribute} attribute - The buffer attribute.
  45779. */
  45780. updateAttribute( attribute ) {
  45781. const backend = this.backend;
  45782. const { gl } = backend;
  45783. const array = attribute.array;
  45784. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  45785. const bufferData = backend.get( bufferAttribute );
  45786. const bufferType = bufferData.bufferType;
  45787. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  45788. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  45789. if ( updateRanges.length === 0 ) {
  45790. // Not using update ranges
  45791. gl.bufferSubData( bufferType, 0, array );
  45792. } else {
  45793. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  45794. const range = updateRanges[ i ];
  45795. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  45796. array, range.start, range.count );
  45797. }
  45798. bufferAttribute.clearUpdateRanges();
  45799. }
  45800. gl.bindBuffer( bufferType, null );
  45801. bufferData.version = bufferAttribute.version;
  45802. }
  45803. /**
  45804. * Destroys the GPU buffer of the given buffer attribute.
  45805. *
  45806. * @param {BufferAttribute} attribute - The buffer attribute.
  45807. */
  45808. destroyAttribute( attribute ) {
  45809. const backend = this.backend;
  45810. const { gl } = backend;
  45811. if ( attribute.isInterleavedBufferAttribute ) {
  45812. backend.delete( attribute.data );
  45813. }
  45814. const attributeData = backend.get( attribute );
  45815. gl.deleteBuffer( attributeData.bufferGPU );
  45816. backend.delete( attribute );
  45817. }
  45818. /**
  45819. * This method performs a readback operation by moving buffer data from
  45820. * a storage buffer attribute from the GPU to the CPU.
  45821. *
  45822. * @async
  45823. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45824. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45825. */
  45826. async getArrayBufferAsync( attribute ) {
  45827. const backend = this.backend;
  45828. const { gl } = backend;
  45829. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  45830. const { bufferGPU } = backend.get( bufferAttribute );
  45831. const array = attribute.array;
  45832. const byteLength = array.byteLength;
  45833. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  45834. const writeBuffer = gl.createBuffer();
  45835. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  45836. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  45837. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  45838. await backend.utils._clientWaitAsync();
  45839. const dstBuffer = new attribute.array.constructor( array.length );
  45840. // Ensure the buffer is bound before reading
  45841. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  45842. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  45843. gl.deleteBuffer( writeBuffer );
  45844. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  45845. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  45846. return dstBuffer.buffer;
  45847. }
  45848. /**
  45849. * Creates a WebGL buffer with the given data.
  45850. *
  45851. * @private
  45852. * @param {WebGL2RenderingContext} gl - The rendering context.
  45853. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  45854. * @param {TypedArray} array - The array of the buffer attribute.
  45855. * @param {GLenum} usage - The usage.
  45856. * @return {WebGLBuffer} The WebGL buffer.
  45857. */
  45858. _createBuffer( gl, bufferType, array, usage ) {
  45859. const bufferGPU = gl.createBuffer();
  45860. gl.bindBuffer( bufferType, bufferGPU );
  45861. gl.bufferData( bufferType, array, usage );
  45862. gl.bindBuffer( bufferType, null );
  45863. return bufferGPU;
  45864. }
  45865. }
  45866. let equationToGL, factorToGL;
  45867. /**
  45868. * A WebGL 2 backend utility module for managing the WebGL state.
  45869. *
  45870. * The major goal of this module is to reduce the number of state changes
  45871. * by caching the WEbGL state with a series of variables. In this way, the
  45872. * renderer only executes state change commands when necessary which
  45873. * improves the overall performance.
  45874. *
  45875. * @private
  45876. */
  45877. class WebGLState {
  45878. /**
  45879. * Constructs a new utility object.
  45880. *
  45881. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45882. */
  45883. constructor( backend ) {
  45884. /**
  45885. * A reference to the WebGL 2 backend.
  45886. *
  45887. * @type {WebGLBackend}
  45888. */
  45889. this.backend = backend;
  45890. /**
  45891. * A reference to the rendering context.
  45892. *
  45893. * @type {WebGL2RenderingContext}
  45894. */
  45895. this.gl = this.backend.gl;
  45896. // Below properties are intended to cache
  45897. // the WebGL state and are not explicitly
  45898. // documented for convenience reasons.
  45899. this.enabled = {};
  45900. this.currentFlipSided = null;
  45901. this.currentCullFace = null;
  45902. this.currentProgram = null;
  45903. this.currentBlendingEnabled = false;
  45904. this.currentBlending = null;
  45905. this.currentBlendSrc = null;
  45906. this.currentBlendDst = null;
  45907. this.currentBlendSrcAlpha = null;
  45908. this.currentBlendDstAlpha = null;
  45909. this.currentPremultipledAlpha = null;
  45910. this.currentPolygonOffsetFactor = null;
  45911. this.currentPolygonOffsetUnits = null;
  45912. this.currentColorMask = null;
  45913. this.currentDepthFunc = null;
  45914. this.currentDepthMask = null;
  45915. this.currentStencilFunc = null;
  45916. this.currentStencilRef = null;
  45917. this.currentStencilFuncMask = null;
  45918. this.currentStencilFail = null;
  45919. this.currentStencilZFail = null;
  45920. this.currentStencilZPass = null;
  45921. this.currentStencilMask = null;
  45922. this.currentLineWidth = null;
  45923. this.currentClippingPlanes = 0;
  45924. this.currentVAO = null;
  45925. this.currentIndex = null;
  45926. this.currentBoundFramebuffers = {};
  45927. this.currentDrawbuffers = new WeakMap();
  45928. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  45929. this.currentTextureSlot = null;
  45930. this.currentBoundTextures = {};
  45931. this.currentBoundBufferBases = {};
  45932. this._init();
  45933. }
  45934. /**
  45935. * Inits the state of the utility.
  45936. *
  45937. * @private
  45938. */
  45939. _init() {
  45940. const gl = this.gl;
  45941. // Store only WebGL constants here.
  45942. equationToGL = {
  45943. [ AddEquation ]: gl.FUNC_ADD,
  45944. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  45945. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  45946. };
  45947. factorToGL = {
  45948. [ ZeroFactor ]: gl.ZERO,
  45949. [ OneFactor ]: gl.ONE,
  45950. [ SrcColorFactor ]: gl.SRC_COLOR,
  45951. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  45952. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  45953. [ DstColorFactor ]: gl.DST_COLOR,
  45954. [ DstAlphaFactor ]: gl.DST_ALPHA,
  45955. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  45956. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  45957. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  45958. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  45959. };
  45960. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  45961. const viewportParam = gl.getParameter( gl.VIEWPORT );
  45962. this.currentScissor = new Vector4().fromArray( scissorParam );
  45963. this.currentViewport = new Vector4().fromArray( viewportParam );
  45964. this._tempVec4 = new Vector4();
  45965. }
  45966. /**
  45967. * Enables the given WebGL capability.
  45968. *
  45969. * This method caches the capability state so
  45970. * `gl.enable()` is only called when necessary.
  45971. *
  45972. * @param {GLenum} id - The capability to enable.
  45973. */
  45974. enable( id ) {
  45975. const { enabled } = this;
  45976. if ( enabled[ id ] !== true ) {
  45977. this.gl.enable( id );
  45978. enabled[ id ] = true;
  45979. }
  45980. }
  45981. /**
  45982. * Disables the given WebGL capability.
  45983. *
  45984. * This method caches the capability state so
  45985. * `gl.disable()` is only called when necessary.
  45986. *
  45987. * @param {GLenum} id - The capability to enable.
  45988. */
  45989. disable( id ) {
  45990. const { enabled } = this;
  45991. if ( enabled[ id ] !== false ) {
  45992. this.gl.disable( id );
  45993. enabled[ id ] = false;
  45994. }
  45995. }
  45996. /**
  45997. * Specifies whether polygons are front- or back-facing
  45998. * by setting the winding orientation.
  45999. *
  46000. * This method caches the state so `gl.frontFace()` is only
  46001. * called when necessary.
  46002. *
  46003. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  46004. */
  46005. setFlipSided( flipSided ) {
  46006. if ( this.currentFlipSided !== flipSided ) {
  46007. const { gl } = this;
  46008. if ( flipSided ) {
  46009. gl.frontFace( gl.CW );
  46010. } else {
  46011. gl.frontFace( gl.CCW );
  46012. }
  46013. this.currentFlipSided = flipSided;
  46014. }
  46015. }
  46016. /**
  46017. * Specifies whether or not front- and/or back-facing
  46018. * polygons can be culled.
  46019. *
  46020. * This method caches the state so `gl.cullFace()` is only
  46021. * called when necessary.
  46022. *
  46023. * @param {number} cullFace - Defines which polygons are candidates for culling.
  46024. */
  46025. setCullFace( cullFace ) {
  46026. const { gl } = this;
  46027. if ( cullFace !== CullFaceNone ) {
  46028. this.enable( gl.CULL_FACE );
  46029. if ( cullFace !== this.currentCullFace ) {
  46030. if ( cullFace === CullFaceBack ) {
  46031. gl.cullFace( gl.BACK );
  46032. } else if ( cullFace === CullFaceFront ) {
  46033. gl.cullFace( gl.FRONT );
  46034. } else {
  46035. gl.cullFace( gl.FRONT_AND_BACK );
  46036. }
  46037. }
  46038. } else {
  46039. this.disable( gl.CULL_FACE );
  46040. }
  46041. this.currentCullFace = cullFace;
  46042. }
  46043. /**
  46044. * Specifies the width of line primitives.
  46045. *
  46046. * This method caches the state so `gl.lineWidth()` is only
  46047. * called when necessary.
  46048. *
  46049. * @param {number} width - The line width.
  46050. */
  46051. setLineWidth( width ) {
  46052. const { currentLineWidth, gl } = this;
  46053. if ( width !== currentLineWidth ) {
  46054. gl.lineWidth( width );
  46055. this.currentLineWidth = width;
  46056. }
  46057. }
  46058. setMRTBlending( textures ) {
  46059. const gl = this.gl;
  46060. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  46061. if ( ! drawBuffersIndexedExt ) return;
  46062. for ( let i = 1; i < textures.length; i ++ ) {
  46063. // use opaque blending for additional render targets
  46064. drawBuffersIndexedExt.blendFuncSeparateiOES( i, gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  46065. }
  46066. }
  46067. /**
  46068. * Defines the blending.
  46069. *
  46070. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  46071. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  46072. *
  46073. * @param {number} blending - The blending type.
  46074. * @param {number} blendEquation - The blending equation.
  46075. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  46076. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  46077. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  46078. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  46079. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  46080. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  46081. */
  46082. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  46083. const { gl } = this;
  46084. if ( blending === NoBlending ) {
  46085. if ( this.currentBlendingEnabled === true ) {
  46086. this.disable( gl.BLEND );
  46087. this.currentBlendingEnabled = false;
  46088. }
  46089. return;
  46090. }
  46091. if ( this.currentBlendingEnabled === false ) {
  46092. this.enable( gl.BLEND );
  46093. this.currentBlendingEnabled = true;
  46094. }
  46095. if ( blending !== CustomBlending ) {
  46096. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  46097. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  46098. gl.blendEquation( gl.FUNC_ADD );
  46099. this.currentBlendEquation = AddEquation;
  46100. this.currentBlendEquationAlpha = AddEquation;
  46101. }
  46102. if ( premultipliedAlpha ) {
  46103. switch ( blending ) {
  46104. case NormalBlending:
  46105. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46106. break;
  46107. case AdditiveBlending:
  46108. gl.blendFunc( gl.ONE, gl.ONE );
  46109. break;
  46110. case SubtractiveBlending:
  46111. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  46112. break;
  46113. case MultiplyBlending:
  46114. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  46115. break;
  46116. default:
  46117. error( 'WebGLState: Invalid blending: ', blending );
  46118. break;
  46119. }
  46120. } else {
  46121. switch ( blending ) {
  46122. case NormalBlending:
  46123. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46124. break;
  46125. case AdditiveBlending:
  46126. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  46127. break;
  46128. case SubtractiveBlending:
  46129. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  46130. break;
  46131. case MultiplyBlending:
  46132. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  46133. break;
  46134. default:
  46135. error( 'WebGLState: Invalid blending: ', blending );
  46136. break;
  46137. }
  46138. }
  46139. this.currentBlendSrc = null;
  46140. this.currentBlendDst = null;
  46141. this.currentBlendSrcAlpha = null;
  46142. this.currentBlendDstAlpha = null;
  46143. this.currentBlending = blending;
  46144. this.currentPremultipledAlpha = premultipliedAlpha;
  46145. }
  46146. return;
  46147. }
  46148. // custom blending
  46149. blendEquationAlpha = blendEquationAlpha || blendEquation;
  46150. blendSrcAlpha = blendSrcAlpha || blendSrc;
  46151. blendDstAlpha = blendDstAlpha || blendDst;
  46152. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  46153. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  46154. this.currentBlendEquation = blendEquation;
  46155. this.currentBlendEquationAlpha = blendEquationAlpha;
  46156. }
  46157. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  46158. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  46159. this.currentBlendSrc = blendSrc;
  46160. this.currentBlendDst = blendDst;
  46161. this.currentBlendSrcAlpha = blendSrcAlpha;
  46162. this.currentBlendDstAlpha = blendDstAlpha;
  46163. }
  46164. this.currentBlending = blending;
  46165. this.currentPremultipledAlpha = false;
  46166. }
  46167. /**
  46168. * Specifies whether colors can be written when rendering
  46169. * into a framebuffer or not.
  46170. *
  46171. * This method caches the state so `gl.colorMask()` is only
  46172. * called when necessary.
  46173. *
  46174. * @param {boolean} colorMask - The color mask.
  46175. */
  46176. setColorMask( colorMask ) {
  46177. if ( this.currentColorMask !== colorMask ) {
  46178. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  46179. this.currentColorMask = colorMask;
  46180. }
  46181. }
  46182. /**
  46183. * Specifies whether the depth test is enabled or not.
  46184. *
  46185. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  46186. */
  46187. setDepthTest( depthTest ) {
  46188. const { gl } = this;
  46189. if ( depthTest ) {
  46190. this.enable( gl.DEPTH_TEST );
  46191. } else {
  46192. this.disable( gl.DEPTH_TEST );
  46193. }
  46194. }
  46195. /**
  46196. * Specifies whether depth values can be written when rendering
  46197. * into a framebuffer or not.
  46198. *
  46199. * This method caches the state so `gl.depthMask()` is only
  46200. * called when necessary.
  46201. *
  46202. * @param {boolean} depthMask - The depth mask.
  46203. */
  46204. setDepthMask( depthMask ) {
  46205. if ( this.currentDepthMask !== depthMask ) {
  46206. this.gl.depthMask( depthMask );
  46207. this.currentDepthMask = depthMask;
  46208. }
  46209. }
  46210. /**
  46211. * Specifies the depth compare function.
  46212. *
  46213. * This method caches the state so `gl.depthFunc()` is only
  46214. * called when necessary.
  46215. *
  46216. * @param {number} depthFunc - The depth compare function.
  46217. */
  46218. setDepthFunc( depthFunc ) {
  46219. if ( this.currentDepthFunc !== depthFunc ) {
  46220. const { gl } = this;
  46221. switch ( depthFunc ) {
  46222. case NeverDepth:
  46223. gl.depthFunc( gl.NEVER );
  46224. break;
  46225. case AlwaysDepth:
  46226. gl.depthFunc( gl.ALWAYS );
  46227. break;
  46228. case LessDepth:
  46229. gl.depthFunc( gl.LESS );
  46230. break;
  46231. case LessEqualDepth:
  46232. gl.depthFunc( gl.LEQUAL );
  46233. break;
  46234. case EqualDepth:
  46235. gl.depthFunc( gl.EQUAL );
  46236. break;
  46237. case GreaterEqualDepth:
  46238. gl.depthFunc( gl.GEQUAL );
  46239. break;
  46240. case GreaterDepth:
  46241. gl.depthFunc( gl.GREATER );
  46242. break;
  46243. case NotEqualDepth:
  46244. gl.depthFunc( gl.NOTEQUAL );
  46245. break;
  46246. default:
  46247. gl.depthFunc( gl.LEQUAL );
  46248. }
  46249. this.currentDepthFunc = depthFunc;
  46250. }
  46251. }
  46252. /**
  46253. * Specifies the scissor box.
  46254. *
  46255. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  46256. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  46257. * @param {number} width - The width of the viewport.
  46258. * @param {number} height - The height of the viewport.
  46259. *
  46260. */
  46261. scissor( x, y, width, height ) {
  46262. const scissor = this._tempVec4.set( x, y, width, height );
  46263. if ( this.currentScissor.equals( scissor ) === false ) {
  46264. const { gl } = this;
  46265. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  46266. this.currentScissor.copy( scissor );
  46267. }
  46268. }
  46269. /**
  46270. * Specifies the viewport.
  46271. *
  46272. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  46273. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  46274. * @param {number} width - The width of the viewport.
  46275. * @param {number} height - The height of the viewport.
  46276. *
  46277. */
  46278. viewport( x, y, width, height ) {
  46279. const viewport = this._tempVec4.set( x, y, width, height );
  46280. if ( this.currentViewport.equals( viewport ) === false ) {
  46281. const { gl } = this;
  46282. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  46283. this.currentViewport.copy( viewport );
  46284. }
  46285. }
  46286. /**
  46287. * Defines the scissor test.
  46288. *
  46289. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  46290. */
  46291. setScissorTest( boolean ) {
  46292. const gl = this.gl;
  46293. if ( boolean ) {
  46294. gl.enable( gl.SCISSOR_TEST );
  46295. } else {
  46296. gl.disable( gl.SCISSOR_TEST );
  46297. }
  46298. }
  46299. /**
  46300. * Specifies whether the stencil test is enabled or not.
  46301. *
  46302. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  46303. */
  46304. setStencilTest( stencilTest ) {
  46305. const { gl } = this;
  46306. if ( stencilTest ) {
  46307. this.enable( gl.STENCIL_TEST );
  46308. } else {
  46309. this.disable( gl.STENCIL_TEST );
  46310. }
  46311. }
  46312. /**
  46313. * Specifies whether stencil values can be written when rendering
  46314. * into a framebuffer or not.
  46315. *
  46316. * This method caches the state so `gl.stencilMask()` is only
  46317. * called when necessary.
  46318. *
  46319. * @param {boolean} stencilMask - The stencil mask.
  46320. */
  46321. setStencilMask( stencilMask ) {
  46322. if ( this.currentStencilMask !== stencilMask ) {
  46323. this.gl.stencilMask( stencilMask );
  46324. this.currentStencilMask = stencilMask;
  46325. }
  46326. }
  46327. /**
  46328. * Specifies whether the stencil test functions.
  46329. *
  46330. * This method caches the state so `gl.stencilFunc()` is only
  46331. * called when necessary.
  46332. *
  46333. * @param {number} stencilFunc - The stencil compare function.
  46334. * @param {number} stencilRef - The reference value for the stencil test.
  46335. * @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.
  46336. */
  46337. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  46338. if ( this.currentStencilFunc !== stencilFunc ||
  46339. this.currentStencilRef !== stencilRef ||
  46340. this.currentStencilFuncMask !== stencilMask ) {
  46341. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  46342. this.currentStencilFunc = stencilFunc;
  46343. this.currentStencilRef = stencilRef;
  46344. this.currentStencilFuncMask = stencilMask;
  46345. }
  46346. }
  46347. /**
  46348. * Specifies whether the stencil test operation.
  46349. *
  46350. * This method caches the state so `gl.stencilOp()` is only
  46351. * called when necessary.
  46352. *
  46353. * @param {number} stencilFail - The function to use when the stencil test fails.
  46354. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  46355. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  46356. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  46357. */
  46358. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  46359. if ( this.currentStencilFail !== stencilFail ||
  46360. this.currentStencilZFail !== stencilZFail ||
  46361. this.currentStencilZPass !== stencilZPass ) {
  46362. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  46363. this.currentStencilFail = stencilFail;
  46364. this.currentStencilZFail = stencilZFail;
  46365. this.currentStencilZPass = stencilZPass;
  46366. }
  46367. }
  46368. /**
  46369. * Configures the WebGL state for the given material.
  46370. *
  46371. * @param {Material} material - The material to configure the state for.
  46372. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  46373. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  46374. */
  46375. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  46376. const { gl } = this;
  46377. material.side === DoubleSide
  46378. ? this.disable( gl.CULL_FACE )
  46379. : this.enable( gl.CULL_FACE );
  46380. let flipSided = ( material.side === BackSide );
  46381. if ( frontFaceCW ) flipSided = ! flipSided;
  46382. this.setFlipSided( flipSided );
  46383. ( material.blending === NormalBlending && material.transparent === false )
  46384. ? this.setBlending( NoBlending )
  46385. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  46386. this.setDepthFunc( material.depthFunc );
  46387. this.setDepthTest( material.depthTest );
  46388. this.setDepthMask( material.depthWrite );
  46389. this.setColorMask( material.colorWrite );
  46390. const stencilWrite = material.stencilWrite;
  46391. this.setStencilTest( stencilWrite );
  46392. if ( stencilWrite ) {
  46393. this.setStencilMask( material.stencilWriteMask );
  46394. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  46395. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  46396. }
  46397. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  46398. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  46399. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  46400. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  46401. if ( hardwareClippingPlanes > 0 ) {
  46402. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  46403. const CLIP_DISTANCE0_WEBGL = 0x3000;
  46404. for ( let i = 0; i < 8; i ++ ) {
  46405. if ( i < hardwareClippingPlanes ) {
  46406. this.enable( CLIP_DISTANCE0_WEBGL + i );
  46407. } else {
  46408. this.disable( CLIP_DISTANCE0_WEBGL + i );
  46409. }
  46410. }
  46411. }
  46412. }
  46413. }
  46414. /**
  46415. * Specifies the polygon offset.
  46416. *
  46417. * This method caches the state so `gl.polygonOffset()` is only
  46418. * called when necessary.
  46419. *
  46420. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  46421. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  46422. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  46423. */
  46424. setPolygonOffset( polygonOffset, factor, units ) {
  46425. const { gl } = this;
  46426. if ( polygonOffset ) {
  46427. this.enable( gl.POLYGON_OFFSET_FILL );
  46428. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  46429. gl.polygonOffset( factor, units );
  46430. this.currentPolygonOffsetFactor = factor;
  46431. this.currentPolygonOffsetUnits = units;
  46432. }
  46433. } else {
  46434. this.disable( gl.POLYGON_OFFSET_FILL );
  46435. }
  46436. }
  46437. /**
  46438. * Defines the usage of the given WebGL program.
  46439. *
  46440. * This method caches the state so `gl.useProgram()` is only
  46441. * called when necessary.
  46442. *
  46443. * @param {WebGLProgram} program - The WebGL program to use.
  46444. * @return {boolean} Whether a program change has been executed or not.
  46445. */
  46446. useProgram( program ) {
  46447. if ( this.currentProgram !== program ) {
  46448. this.gl.useProgram( program );
  46449. this.currentProgram = program;
  46450. return true;
  46451. }
  46452. return false;
  46453. }
  46454. /**
  46455. * Sets the vertex state by binding the given VAO and element buffer.
  46456. *
  46457. * @param {WebGLVertexArrayObject} vao - The VAO.
  46458. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  46459. * @return {boolean} Whether a vertex state has been changed or not.
  46460. */
  46461. setVertexState( vao, indexBuffer = null ) {
  46462. const gl = this.gl;
  46463. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  46464. gl.bindVertexArray( vao );
  46465. if ( indexBuffer !== null ) {
  46466. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  46467. }
  46468. this.currentVAO = vao;
  46469. this.currentIndex = indexBuffer;
  46470. return true;
  46471. }
  46472. return false;
  46473. }
  46474. /**
  46475. * Resets the vertex array state by resetting the VAO and element buffer.
  46476. */
  46477. resetVertexState() {
  46478. const gl = this.gl;
  46479. gl.bindVertexArray( null );
  46480. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  46481. this.currentVAO = null;
  46482. this.currentIndex = null;
  46483. }
  46484. // framebuffer
  46485. /**
  46486. * Binds the given framebuffer.
  46487. *
  46488. * This method caches the state so `gl.bindFramebuffer()` is only
  46489. * called when necessary.
  46490. *
  46491. * @param {number} target - The binding point (target).
  46492. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  46493. * @return {boolean} Whether a bind has been executed or not.
  46494. */
  46495. bindFramebuffer( target, framebuffer ) {
  46496. const { gl, currentBoundFramebuffers } = this;
  46497. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  46498. gl.bindFramebuffer( target, framebuffer );
  46499. currentBoundFramebuffers[ target ] = framebuffer;
  46500. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  46501. if ( target === gl.DRAW_FRAMEBUFFER ) {
  46502. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  46503. }
  46504. if ( target === gl.FRAMEBUFFER ) {
  46505. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  46506. }
  46507. return true;
  46508. }
  46509. return false;
  46510. }
  46511. /**
  46512. * Defines draw buffers to which fragment colors are written into.
  46513. * Configures the MRT setup of custom framebuffers.
  46514. *
  46515. * This method caches the state so `gl.drawBuffers()` is only
  46516. * called when necessary.
  46517. *
  46518. * @param {RenderContext} renderContext - The render context.
  46519. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  46520. */
  46521. drawBuffers( renderContext, framebuffer ) {
  46522. const { gl } = this;
  46523. let drawBuffers = [];
  46524. let needsUpdate = false;
  46525. if ( renderContext.textures !== null ) {
  46526. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  46527. if ( drawBuffers === undefined ) {
  46528. drawBuffers = [];
  46529. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  46530. }
  46531. const textures = renderContext.textures;
  46532. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  46533. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  46534. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  46535. }
  46536. drawBuffers.length = textures.length;
  46537. needsUpdate = true;
  46538. }
  46539. } else {
  46540. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  46541. drawBuffers[ 0 ] = gl.BACK;
  46542. needsUpdate = true;
  46543. }
  46544. }
  46545. if ( needsUpdate ) {
  46546. gl.drawBuffers( drawBuffers );
  46547. }
  46548. }
  46549. // texture
  46550. /**
  46551. * Makes the given texture unit active.
  46552. *
  46553. * This method caches the state so `gl.activeTexture()` is only
  46554. * called when necessary.
  46555. *
  46556. * @param {number} webglSlot - The texture unit to make active.
  46557. */
  46558. activeTexture( webglSlot ) {
  46559. const { gl, currentTextureSlot, maxTextures } = this;
  46560. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  46561. if ( currentTextureSlot !== webglSlot ) {
  46562. gl.activeTexture( webglSlot );
  46563. this.currentTextureSlot = webglSlot;
  46564. }
  46565. }
  46566. /**
  46567. * Binds the given WebGL texture to a target.
  46568. *
  46569. * This method caches the state so `gl.bindTexture()` is only
  46570. * called when necessary.
  46571. *
  46572. * @param {number} webglType - The binding point (target).
  46573. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  46574. * @param {number} webglSlot - The texture.
  46575. */
  46576. bindTexture( webglType, webglTexture, webglSlot ) {
  46577. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  46578. if ( webglSlot === undefined ) {
  46579. if ( currentTextureSlot === null ) {
  46580. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  46581. } else {
  46582. webglSlot = currentTextureSlot;
  46583. }
  46584. }
  46585. let boundTexture = currentBoundTextures[ webglSlot ];
  46586. if ( boundTexture === undefined ) {
  46587. boundTexture = { type: undefined, texture: undefined };
  46588. currentBoundTextures[ webglSlot ] = boundTexture;
  46589. }
  46590. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  46591. if ( currentTextureSlot !== webglSlot ) {
  46592. gl.activeTexture( webglSlot );
  46593. this.currentTextureSlot = webglSlot;
  46594. }
  46595. gl.bindTexture( webglType, webglTexture );
  46596. boundTexture.type = webglType;
  46597. boundTexture.texture = webglTexture;
  46598. }
  46599. }
  46600. /**
  46601. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  46602. *
  46603. * This method caches the state so `gl.bindBufferBase()` is only
  46604. * called when necessary.
  46605. *
  46606. * @param {number} target - The target for the bind operation.
  46607. * @param {number} index - The index of the target.
  46608. * @param {WebGLBuffer} buffer - The WebGL buffer.
  46609. * @return {boolean} Whether a bind has been executed or not.
  46610. */
  46611. bindBufferBase( target, index, buffer ) {
  46612. const { gl } = this;
  46613. const key = `${target}-${index}`;
  46614. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  46615. gl.bindBufferBase( target, index, buffer );
  46616. this.currentBoundBufferBases[ key ] = buffer;
  46617. return true;
  46618. }
  46619. return false;
  46620. }
  46621. /**
  46622. * Unbinds the current bound texture.
  46623. *
  46624. * This method caches the state so `gl.bindTexture()` is only
  46625. * called when necessary.
  46626. */
  46627. unbindTexture() {
  46628. const { gl, currentTextureSlot, currentBoundTextures } = this;
  46629. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  46630. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  46631. gl.bindTexture( boundTexture.type, null );
  46632. boundTexture.type = undefined;
  46633. boundTexture.texture = undefined;
  46634. }
  46635. }
  46636. }
  46637. /**
  46638. * A WebGL 2 backend utility module with common helpers.
  46639. *
  46640. * @private
  46641. */
  46642. class WebGLUtils {
  46643. /**
  46644. * Constructs a new utility object.
  46645. *
  46646. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46647. */
  46648. constructor( backend ) {
  46649. /**
  46650. * A reference to the WebGL 2 backend.
  46651. *
  46652. * @type {WebGLBackend}
  46653. */
  46654. this.backend = backend;
  46655. /**
  46656. * A reference to the rendering context.
  46657. *
  46658. * @type {WebGL2RenderingContext}
  46659. */
  46660. this.gl = this.backend.gl;
  46661. /**
  46662. * A reference to a backend module holding extension-related
  46663. * utility functions.
  46664. *
  46665. * @type {WebGLExtensions}
  46666. */
  46667. this.extensions = backend.extensions;
  46668. }
  46669. /**
  46670. * Converts the given three.js constant into a WebGL constant.
  46671. * The method currently supports the conversion of texture formats
  46672. * and types.
  46673. *
  46674. * @param {number} p - The three.js constant.
  46675. * @param {string} [colorSpace=NoColorSpace] - The color space.
  46676. * @return {?number} The corresponding WebGL constant.
  46677. */
  46678. convert( p, colorSpace = NoColorSpace ) {
  46679. const { gl, extensions } = this;
  46680. let extension;
  46681. const transfer = ColorManagement.getTransfer( colorSpace );
  46682. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  46683. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  46684. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  46685. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  46686. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  46687. if ( p === ByteType ) return gl.BYTE;
  46688. if ( p === ShortType ) return gl.SHORT;
  46689. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  46690. if ( p === IntType ) return gl.INT;
  46691. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  46692. if ( p === FloatType ) return gl.FLOAT;
  46693. if ( p === HalfFloatType ) {
  46694. return gl.HALF_FLOAT;
  46695. }
  46696. if ( p === AlphaFormat ) return gl.ALPHA;
  46697. if ( p === RGBFormat ) return gl.RGB;
  46698. if ( p === RGBAFormat ) return gl.RGBA;
  46699. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  46700. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  46701. // WebGL2 formats.
  46702. if ( p === RedFormat ) return gl.RED;
  46703. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  46704. if ( p === RGFormat ) return gl.RG;
  46705. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  46706. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  46707. // S3TC
  46708. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  46709. if ( transfer === SRGBTransfer ) {
  46710. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  46711. if ( extension !== null ) {
  46712. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  46713. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  46714. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  46715. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  46716. } else {
  46717. return null;
  46718. }
  46719. } else {
  46720. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  46721. if ( extension !== null ) {
  46722. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  46723. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  46724. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  46725. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  46726. } else {
  46727. return null;
  46728. }
  46729. }
  46730. }
  46731. // PVRTC
  46732. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  46733. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  46734. if ( extension !== null ) {
  46735. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  46736. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  46737. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  46738. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  46739. } else {
  46740. return null;
  46741. }
  46742. }
  46743. // ETC
  46744. 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 ) {
  46745. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  46746. if ( extension !== null ) {
  46747. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  46748. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  46749. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  46750. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  46751. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  46752. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  46753. } else {
  46754. return null;
  46755. }
  46756. }
  46757. // ASTC
  46758. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  46759. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  46760. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  46761. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  46762. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  46763. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  46764. if ( extension !== null ) {
  46765. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  46766. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  46767. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  46768. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  46769. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  46770. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  46771. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  46772. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  46773. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  46774. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  46775. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  46776. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  46777. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  46778. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  46779. } else {
  46780. return null;
  46781. }
  46782. }
  46783. // BPTC
  46784. if ( p === RGBA_BPTC_Format ) {
  46785. extension = extensions.get( 'EXT_texture_compression_bptc' );
  46786. if ( extension !== null ) {
  46787. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  46788. } else {
  46789. return null;
  46790. }
  46791. }
  46792. // RGTC
  46793. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  46794. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  46795. if ( extension !== null ) {
  46796. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  46797. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  46798. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  46799. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  46800. } else {
  46801. return null;
  46802. }
  46803. }
  46804. //
  46805. if ( p === UnsignedInt248Type ) {
  46806. return gl.UNSIGNED_INT_24_8;
  46807. }
  46808. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  46809. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  46810. }
  46811. /**
  46812. * This method can be used to synchronize the CPU with the GPU by waiting until
  46813. * ongoing GPU commands have been completed.
  46814. *
  46815. * @private
  46816. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  46817. */
  46818. _clientWaitAsync() {
  46819. const { gl } = this;
  46820. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  46821. gl.flush();
  46822. return new Promise( ( resolve, reject ) => {
  46823. function test() {
  46824. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  46825. if ( res === gl.WAIT_FAILED ) {
  46826. gl.deleteSync( sync );
  46827. reject();
  46828. return;
  46829. }
  46830. if ( res === gl.TIMEOUT_EXPIRED ) {
  46831. requestAnimationFrame( test );
  46832. return;
  46833. }
  46834. gl.deleteSync( sync );
  46835. resolve();
  46836. }
  46837. test();
  46838. } );
  46839. }
  46840. }
  46841. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  46842. /**
  46843. * A WebGL 2 backend utility module for managing textures.
  46844. *
  46845. * @private
  46846. */
  46847. class WebGLTextureUtils {
  46848. /**
  46849. * Constructs a new utility object.
  46850. *
  46851. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46852. */
  46853. constructor( backend ) {
  46854. /**
  46855. * A reference to the WebGL 2 backend.
  46856. *
  46857. * @type {WebGLBackend}
  46858. */
  46859. this.backend = backend;
  46860. /**
  46861. * A reference to the rendering context.
  46862. *
  46863. * @type {WebGL2RenderingContext}
  46864. */
  46865. this.gl = backend.gl;
  46866. /**
  46867. * A reference to a backend module holding extension-related
  46868. * utility functions.
  46869. *
  46870. * @type {WebGLExtensions}
  46871. */
  46872. this.extensions = backend.extensions;
  46873. /**
  46874. * A dictionary for managing default textures. The key
  46875. * is the binding point (target), the value the WEbGL texture object.
  46876. *
  46877. * @type {Object<GLenum,WebGLTexture>}
  46878. */
  46879. this.defaultTextures = {};
  46880. /**
  46881. * A scratch framebuffer used for attaching the source texture in
  46882. * {@link copyTextureToTexture}.
  46883. *
  46884. * @private
  46885. * @type {?WebGLFramebuffer}
  46886. */
  46887. this._srcFramebuffer = null;
  46888. /**
  46889. * A scratch framebuffer used for attaching the destination texture in
  46890. * {@link copyTextureToTexture}.
  46891. *
  46892. * @private
  46893. * @type {?WebGLFramebuffer}
  46894. */
  46895. this._dstFramebuffer = null;
  46896. if ( initialized === false ) {
  46897. this._init();
  46898. initialized = true;
  46899. }
  46900. }
  46901. /**
  46902. * Inits the state of the utility.
  46903. *
  46904. * @private
  46905. */
  46906. _init() {
  46907. const gl = this.gl;
  46908. // Store only WebGL constants here.
  46909. wrappingToGL = {
  46910. [ RepeatWrapping ]: gl.REPEAT,
  46911. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  46912. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  46913. };
  46914. filterToGL = {
  46915. [ NearestFilter ]: gl.NEAREST,
  46916. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  46917. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  46918. [ LinearFilter ]: gl.LINEAR,
  46919. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  46920. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  46921. };
  46922. compareToGL = {
  46923. [ NeverCompare ]: gl.NEVER,
  46924. [ AlwaysCompare ]: gl.ALWAYS,
  46925. [ LessCompare ]: gl.LESS,
  46926. [ LessEqualCompare ]: gl.LEQUAL,
  46927. [ EqualCompare ]: gl.EQUAL,
  46928. [ GreaterEqualCompare ]: gl.GEQUAL,
  46929. [ GreaterCompare ]: gl.GREATER,
  46930. [ NotEqualCompare ]: gl.NOTEQUAL
  46931. };
  46932. }
  46933. /**
  46934. * Returns the native texture type for the given texture.
  46935. *
  46936. * @param {Texture} texture - The texture.
  46937. * @return {GLenum} The native texture type.
  46938. */
  46939. getGLTextureType( texture ) {
  46940. const { gl } = this;
  46941. let glTextureType;
  46942. if ( texture.isCubeTexture === true ) {
  46943. glTextureType = gl.TEXTURE_CUBE_MAP;
  46944. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  46945. glTextureType = gl.TEXTURE_2D_ARRAY;
  46946. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  46947. glTextureType = gl.TEXTURE_3D;
  46948. } else {
  46949. glTextureType = gl.TEXTURE_2D;
  46950. }
  46951. return glTextureType;
  46952. }
  46953. /**
  46954. * Returns the native texture type for the given texture.
  46955. *
  46956. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  46957. * @param {GLenum} glFormat - The WebGL format.
  46958. * @param {GLenum} glType - The WebGL type.
  46959. * @param {string} colorSpace - The texture's color space.
  46960. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  46961. * @return {GLenum} The internal format.
  46962. */
  46963. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  46964. const { gl, extensions } = this;
  46965. if ( internalFormatName !== null ) {
  46966. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  46967. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  46968. }
  46969. let internalFormat = glFormat;
  46970. if ( glFormat === gl.RED ) {
  46971. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  46972. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  46973. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  46974. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  46975. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  46976. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  46977. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  46978. if ( glType === gl.INT ) internalFormat = gl.R32I;
  46979. }
  46980. if ( glFormat === gl.RED_INTEGER ) {
  46981. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  46982. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  46983. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  46984. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  46985. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  46986. if ( glType === gl.INT ) internalFormat = gl.R32I;
  46987. }
  46988. if ( glFormat === gl.RG ) {
  46989. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  46990. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  46991. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  46992. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  46993. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  46994. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  46995. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  46996. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  46997. }
  46998. if ( glFormat === gl.RG_INTEGER ) {
  46999. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  47000. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  47001. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  47002. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  47003. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  47004. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  47005. }
  47006. if ( glFormat === gl.RGB ) {
  47007. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  47008. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  47009. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  47010. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  47011. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  47012. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  47013. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  47014. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  47015. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  47016. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  47017. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  47018. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  47019. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  47020. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  47021. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  47022. }
  47023. if ( glFormat === gl.RGB_INTEGER ) {
  47024. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  47025. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  47026. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  47027. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  47028. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  47029. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  47030. }
  47031. if ( glFormat === gl.RGBA ) {
  47032. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  47033. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  47034. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  47035. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  47036. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  47037. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  47038. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  47039. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  47040. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  47041. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  47042. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  47043. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  47044. }
  47045. if ( glFormat === gl.RGBA_INTEGER ) {
  47046. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  47047. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  47048. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  47049. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  47050. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  47051. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  47052. }
  47053. if ( glFormat === gl.DEPTH_COMPONENT ) {
  47054. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  47055. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  47056. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  47057. }
  47058. if ( glFormat === gl.DEPTH_STENCIL ) {
  47059. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  47060. }
  47061. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  47062. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  47063. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  47064. extensions.get( 'EXT_color_buffer_float' );
  47065. }
  47066. return internalFormat;
  47067. }
  47068. /**
  47069. * Sets the texture parameters for the given texture.
  47070. *
  47071. * @param {GLenum} textureType - The texture type.
  47072. * @param {Texture} texture - The texture.
  47073. */
  47074. setTextureParameters( textureType, texture ) {
  47075. const { gl, extensions, backend } = this;
  47076. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  47077. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  47078. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  47079. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  47080. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  47081. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  47082. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  47083. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  47084. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  47085. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  47086. // WebGL 2 does not support wrapping for depth 2D array textures
  47087. if ( ! texture.isArrayTexture ) {
  47088. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  47089. }
  47090. }
  47091. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  47092. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  47093. // follow WebGPU backend mapping for texture filtering
  47094. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  47095. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  47096. if ( texture.compareFunction ) {
  47097. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  47098. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  47099. }
  47100. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  47101. if ( texture.magFilter === NearestFilter ) return;
  47102. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  47103. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  47104. if ( texture.anisotropy > 1 ) {
  47105. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  47106. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  47107. }
  47108. }
  47109. }
  47110. /**
  47111. * Creates a default texture for the given texture that can be used
  47112. * as a placeholder until the actual texture is ready for usage.
  47113. *
  47114. * @param {Texture} texture - The texture to create a default texture for.
  47115. */
  47116. createDefaultTexture( texture ) {
  47117. const { gl, backend, defaultTextures } = this;
  47118. const glTextureType = this.getGLTextureType( texture );
  47119. let textureGPU = defaultTextures[ glTextureType ];
  47120. if ( textureGPU === undefined ) {
  47121. textureGPU = gl.createTexture();
  47122. backend.state.bindTexture( glTextureType, textureGPU );
  47123. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  47124. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  47125. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  47126. defaultTextures[ glTextureType ] = textureGPU;
  47127. }
  47128. backend.set( texture, {
  47129. textureGPU,
  47130. glTextureType
  47131. } );
  47132. }
  47133. /**
  47134. * Defines a texture on the GPU for the given texture object.
  47135. *
  47136. * @param {Texture} texture - The texture.
  47137. * @param {Object} [options={}] - Optional configuration parameter.
  47138. * @return {undefined}
  47139. */
  47140. createTexture( texture, options ) {
  47141. const { gl, backend } = this;
  47142. const { levels, width, height, depth } = options;
  47143. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  47144. const glType = backend.utils.convert( texture.type );
  47145. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  47146. const textureGPU = gl.createTexture();
  47147. const glTextureType = this.getGLTextureType( texture );
  47148. backend.state.bindTexture( glTextureType, textureGPU );
  47149. this.setTextureParameters( glTextureType, texture );
  47150. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  47151. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  47152. } else if ( texture.isData3DTexture ) {
  47153. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  47154. } else if ( ! texture.isVideoTexture ) {
  47155. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  47156. }
  47157. backend.set( texture, {
  47158. textureGPU,
  47159. glTextureType,
  47160. glFormat,
  47161. glType,
  47162. glInternalFormat
  47163. } );
  47164. }
  47165. /**
  47166. * Uploads texture buffer data to the GPU memory.
  47167. *
  47168. * @param {WebGLBuffer} buffer - The buffer data.
  47169. * @param {Texture} texture - The texture,
  47170. */
  47171. copyBufferToTexture( buffer, texture ) {
  47172. const { gl, backend } = this;
  47173. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  47174. const { width, height } = texture.source.data;
  47175. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  47176. backend.state.bindTexture( glTextureType, textureGPU );
  47177. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  47178. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  47179. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  47180. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  47181. backend.state.unbindTexture();
  47182. // debug
  47183. // const framebuffer = gl.createFramebuffer();
  47184. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  47185. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  47186. // const readout = new Float32Array( width * height * 4 );
  47187. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  47188. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  47189. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  47190. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  47191. // log( readout );
  47192. }
  47193. /**
  47194. * Uploads the updated texture data to the GPU.
  47195. *
  47196. * @param {Texture} texture - The texture.
  47197. * @param {Object} [options={}] - Optional configuration parameter.
  47198. */
  47199. updateTexture( texture, options ) {
  47200. const { gl } = this;
  47201. const { width, height } = options;
  47202. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  47203. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  47204. return;
  47205. this.backend.state.bindTexture( glTextureType, textureGPU );
  47206. this.setTextureParameters( glTextureType, texture );
  47207. if ( texture.isCompressedTexture ) {
  47208. const mipmaps = texture.mipmaps;
  47209. const image = options.image;
  47210. for ( let i = 0; i < mipmaps.length; i ++ ) {
  47211. const mipmap = mipmaps[ i ];
  47212. if ( texture.isCompressedArrayTexture ) {
  47213. if ( texture.format !== gl.RGBA ) {
  47214. if ( glFormat !== null ) {
  47215. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  47216. } else {
  47217. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  47218. }
  47219. } else {
  47220. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  47221. }
  47222. } else {
  47223. if ( glFormat !== null ) {
  47224. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  47225. } else {
  47226. warn( 'WebGLBackend: Unsupported compressed texture format' );
  47227. }
  47228. }
  47229. }
  47230. } else if ( texture.isCubeTexture ) {
  47231. const images = options.images;
  47232. const mipmaps = texture.mipmaps;
  47233. for ( let i = 0; i < 6; i ++ ) {
  47234. const image = getImage( images[ i ] );
  47235. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  47236. for ( let j = 0; j < mipmaps.length; j ++ ) {
  47237. const mipmap = mipmaps[ j ];
  47238. const image = getImage( mipmap.images[ i ] );
  47239. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  47240. }
  47241. }
  47242. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  47243. const image = options.image;
  47244. if ( texture.layerUpdates.size > 0 ) {
  47245. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  47246. for ( const layerIndex of texture.layerUpdates ) {
  47247. const layerData = image.data.subarray(
  47248. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  47249. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  47250. );
  47251. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  47252. }
  47253. texture.clearLayerUpdates();
  47254. } else {
  47255. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  47256. }
  47257. } else if ( texture.isData3DTexture ) {
  47258. const image = options.image;
  47259. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  47260. } else if ( texture.isVideoTexture ) {
  47261. texture.update();
  47262. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  47263. } else {
  47264. const mipmaps = texture.mipmaps;
  47265. if ( mipmaps.length > 0 ) {
  47266. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  47267. const mipmap = mipmaps[ i ];
  47268. const image = getImage( mipmap );
  47269. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  47270. }
  47271. } else {
  47272. const image = getImage( options.image );
  47273. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  47274. }
  47275. }
  47276. }
  47277. /**
  47278. * Generates mipmaps for the given texture.
  47279. *
  47280. * @param {Texture} texture - The texture.
  47281. */
  47282. generateMipmaps( texture ) {
  47283. const { gl, backend } = this;
  47284. const { textureGPU, glTextureType } = backend.get( texture );
  47285. backend.state.bindTexture( glTextureType, textureGPU );
  47286. gl.generateMipmap( glTextureType );
  47287. }
  47288. /**
  47289. * Deallocates the render buffers of the given render target.
  47290. *
  47291. * @param {RenderTarget} renderTarget - The render target.
  47292. */
  47293. deallocateRenderBuffers( renderTarget ) {
  47294. const { gl, backend } = this;
  47295. // remove framebuffer reference
  47296. if ( renderTarget ) {
  47297. const renderContextData = backend.get( renderTarget );
  47298. renderContextData.renderBufferStorageSetup = undefined;
  47299. if ( renderContextData.framebuffers ) {
  47300. for ( const cacheKey in renderContextData.framebuffers ) {
  47301. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  47302. }
  47303. delete renderContextData.framebuffers;
  47304. }
  47305. if ( renderContextData.depthRenderbuffer ) {
  47306. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  47307. delete renderContextData.depthRenderbuffer;
  47308. }
  47309. if ( renderContextData.stencilRenderbuffer ) {
  47310. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  47311. delete renderContextData.stencilRenderbuffer;
  47312. }
  47313. if ( renderContextData.msaaFrameBuffer ) {
  47314. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  47315. delete renderContextData.msaaFrameBuffer;
  47316. }
  47317. if ( renderContextData.msaaRenderbuffers ) {
  47318. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  47319. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  47320. }
  47321. delete renderContextData.msaaRenderbuffers;
  47322. }
  47323. }
  47324. }
  47325. /**
  47326. * Destroys the GPU data for the given texture object.
  47327. *
  47328. * @param {Texture} texture - The texture.
  47329. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  47330. */
  47331. destroyTexture( texture, isDefaultTexture = false ) {
  47332. const { gl, backend } = this;
  47333. const { textureGPU, renderTarget } = backend.get( texture );
  47334. this.deallocateRenderBuffers( renderTarget );
  47335. if ( isDefaultTexture === false ) {
  47336. gl.deleteTexture( textureGPU );
  47337. }
  47338. backend.delete( texture );
  47339. }
  47340. /**
  47341. * Copies data of the given source texture to the given destination texture.
  47342. *
  47343. * @param {Texture} srcTexture - The source texture.
  47344. * @param {Texture} dstTexture - The destination texture.
  47345. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  47346. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  47347. * @param {number} [srcLevel=0] - The source mip level to copy from.
  47348. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  47349. */
  47350. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  47351. const { gl, backend } = this;
  47352. const { state } = this.backend;
  47353. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  47354. state.bindTexture( glTextureType, dstTextureGPU );
  47355. // gather the necessary dimensions to copy
  47356. let width, height, depth, minX, minY, minZ;
  47357. let dstX, dstY, dstZ;
  47358. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  47359. if ( srcRegion !== null ) {
  47360. width = srcRegion.max.x - srcRegion.min.x;
  47361. height = srcRegion.max.y - srcRegion.min.y;
  47362. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  47363. minX = srcRegion.min.x;
  47364. minY = srcRegion.min.y;
  47365. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  47366. } else {
  47367. const levelScale = Math.pow( 2, - srcLevel );
  47368. width = Math.floor( image.width * levelScale );
  47369. height = Math.floor( image.height * levelScale );
  47370. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  47371. depth = image.depth;
  47372. } else if ( srcTexture.isData3DTexture ) {
  47373. depth = Math.floor( image.depth * levelScale );
  47374. } else {
  47375. depth = 1;
  47376. }
  47377. minX = 0;
  47378. minY = 0;
  47379. minZ = 0;
  47380. }
  47381. if ( dstPosition !== null ) {
  47382. dstX = dstPosition.x;
  47383. dstY = dstPosition.y;
  47384. dstZ = dstPosition.z;
  47385. } else {
  47386. dstX = 0;
  47387. dstY = 0;
  47388. dstZ = 0;
  47389. }
  47390. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  47391. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  47392. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  47393. // used for copying data from cpu
  47394. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  47395. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  47396. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  47397. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  47398. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  47399. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  47400. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  47401. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  47402. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  47403. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  47404. // set up the src texture
  47405. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  47406. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  47407. if ( srcTexture.isDepthTexture ) {
  47408. const srcTextureData = backend.get( srcTexture );
  47409. const dstTextureData = backend.get( dstTexture );
  47410. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  47411. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  47412. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  47413. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  47414. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  47415. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  47416. for ( let i = 0; i < depth; i ++ ) {
  47417. // if the source or destination are a 3d target then a layer needs to be bound
  47418. if ( isSrc3D ) {
  47419. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  47420. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  47421. }
  47422. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  47423. }
  47424. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47425. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47426. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  47427. // get the appropriate frame buffers
  47428. const srcTextureData = backend.get( srcTexture );
  47429. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  47430. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  47431. // bind the frame buffer targets
  47432. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  47433. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  47434. for ( let i = 0; i < depth; i ++ ) {
  47435. // assign the correct layers and mip maps to the frame buffers
  47436. if ( isSrc3D ) {
  47437. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  47438. } else {
  47439. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  47440. }
  47441. if ( isDst3D ) {
  47442. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  47443. } else {
  47444. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  47445. }
  47446. // copy the data using the fastest function that can achieve the copy
  47447. if ( srcLevel !== 0 ) {
  47448. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  47449. } else if ( isDst3D ) {
  47450. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  47451. } else {
  47452. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  47453. }
  47454. }
  47455. // unbind read, draw buffers
  47456. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47457. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47458. } else {
  47459. if ( isDst3D ) {
  47460. // copy data into the 3d texture
  47461. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  47462. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  47463. } else if ( dstTexture.isCompressedArrayTexture ) {
  47464. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  47465. } else {
  47466. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  47467. }
  47468. } else {
  47469. // copy data into the 2d texture
  47470. if ( srcTexture.isDataTexture ) {
  47471. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  47472. } else if ( srcTexture.isCompressedTexture ) {
  47473. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  47474. } else {
  47475. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  47476. }
  47477. }
  47478. }
  47479. // reset values
  47480. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  47481. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  47482. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  47483. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  47484. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  47485. // Generate mipmaps only when copying level 0
  47486. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  47487. gl.generateMipmap( glTextureType );
  47488. }
  47489. state.unbindTexture();
  47490. }
  47491. /**
  47492. * Copies the current bound framebuffer to the given texture.
  47493. *
  47494. * @param {Texture} texture - The destination texture.
  47495. * @param {RenderContext} renderContext - The render context.
  47496. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  47497. */
  47498. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  47499. const { gl } = this;
  47500. const { state } = this.backend;
  47501. const { textureGPU } = this.backend.get( texture );
  47502. const { x, y, z: width, w: height } = rectangle;
  47503. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  47504. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  47505. if ( requireDrawFrameBuffer ) {
  47506. const partial = ( x !== 0 || y !== 0 );
  47507. let mask;
  47508. let attachment;
  47509. if ( texture.isDepthTexture === true ) {
  47510. mask = gl.DEPTH_BUFFER_BIT;
  47511. attachment = gl.DEPTH_ATTACHMENT;
  47512. if ( renderContext.stencil ) {
  47513. mask |= gl.STENCIL_BUFFER_BIT;
  47514. }
  47515. } else {
  47516. mask = gl.COLOR_BUFFER_BIT;
  47517. attachment = gl.COLOR_ATTACHMENT0;
  47518. }
  47519. if ( partial ) {
  47520. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  47521. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  47522. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  47523. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47524. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  47525. const flippedY = srcHeight - y - height;
  47526. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  47527. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  47528. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  47529. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  47530. state.unbindTexture();
  47531. } else {
  47532. const fb = gl.createFramebuffer();
  47533. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47534. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  47535. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  47536. gl.deleteFramebuffer( fb );
  47537. }
  47538. } else {
  47539. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  47540. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  47541. state.unbindTexture();
  47542. }
  47543. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  47544. this.backend._setFramebuffer( renderContext );
  47545. }
  47546. /**
  47547. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  47548. *
  47549. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  47550. * @param {RenderContext} renderContext - The render context.
  47551. * @param {number} samples - The MSAA sample count.
  47552. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  47553. */
  47554. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  47555. const { gl } = this;
  47556. const renderTarget = renderContext.renderTarget;
  47557. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  47558. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  47559. if ( depthBuffer && ! stencilBuffer ) {
  47560. let glInternalFormat = gl.DEPTH_COMPONENT24;
  47561. if ( useMultisampledRTT === true ) {
  47562. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  47563. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  47564. } else if ( samples > 0 ) {
  47565. if ( depthTexture && depthTexture.isDepthTexture ) {
  47566. if ( depthTexture.type === gl.FLOAT ) {
  47567. glInternalFormat = gl.DEPTH_COMPONENT32F;
  47568. }
  47569. }
  47570. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  47571. } else {
  47572. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  47573. }
  47574. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  47575. } else if ( depthBuffer && stencilBuffer ) {
  47576. if ( samples > 0 ) {
  47577. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  47578. } else {
  47579. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  47580. }
  47581. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  47582. }
  47583. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  47584. }
  47585. /**
  47586. * Returns texture data as a typed array.
  47587. *
  47588. * @async
  47589. * @param {Texture} texture - The texture to copy.
  47590. * @param {number} x - The x coordinate of the copy origin.
  47591. * @param {number} y - The y coordinate of the copy origin.
  47592. * @param {number} width - The width of the copy.
  47593. * @param {number} height - The height of the copy.
  47594. * @param {number} faceIndex - The face index.
  47595. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47596. */
  47597. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47598. const { backend, gl } = this;
  47599. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  47600. const fb = gl.createFramebuffer();
  47601. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  47602. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  47603. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  47604. const typedArrayType = this._getTypedArrayType( glType );
  47605. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  47606. const elementCount = width * height;
  47607. const byteLength = elementCount * bytesPerTexel;
  47608. const buffer = gl.createBuffer();
  47609. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  47610. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  47611. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  47612. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  47613. await backend.utils._clientWaitAsync();
  47614. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  47615. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  47616. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  47617. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  47618. gl.deleteFramebuffer( fb );
  47619. return dstBuffer;
  47620. }
  47621. /**
  47622. * Returns the corresponding typed array type for the given WebGL data type.
  47623. *
  47624. * @private
  47625. * @param {GLenum} glType - The WebGL data type.
  47626. * @return {TypedArray.constructor} The typed array type.
  47627. */
  47628. _getTypedArrayType( glType ) {
  47629. const { gl } = this;
  47630. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  47631. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  47632. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  47633. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  47634. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  47635. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  47636. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  47637. if ( glType === gl.FLOAT ) return Float32Array;
  47638. throw new Error( `Unsupported WebGL type: ${glType}` );
  47639. }
  47640. /**
  47641. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  47642. *
  47643. * @private
  47644. * @param {GLenum} glType - The WebGL data type.
  47645. * @param {GLenum} glFormat - The WebGL texture format.
  47646. * @return {number} The bytes-per-texel.
  47647. */
  47648. _getBytesPerTexel( glType, glFormat ) {
  47649. const { gl } = this;
  47650. let bytesPerComponent = 0;
  47651. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  47652. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  47653. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  47654. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  47655. glType === gl.UNSIGNED_SHORT ||
  47656. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  47657. if ( glType === gl.UNSIGNED_INT ||
  47658. glType === gl.FLOAT ) bytesPerComponent = 4;
  47659. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  47660. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  47661. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  47662. }
  47663. /**
  47664. * Frees the internal resources.
  47665. */
  47666. dispose() {
  47667. const { gl } = this;
  47668. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  47669. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  47670. }
  47671. }
  47672. function getImage( source ) {
  47673. if ( source.isDataTexture ) {
  47674. return source.image.data;
  47675. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  47676. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  47677. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  47678. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  47679. return source;
  47680. }
  47681. return source.data;
  47682. }
  47683. /**
  47684. * A WebGL 2 backend utility module for managing extensions.
  47685. *
  47686. * @private
  47687. */
  47688. class WebGLExtensions {
  47689. /**
  47690. * Constructs a new utility object.
  47691. *
  47692. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47693. */
  47694. constructor( backend ) {
  47695. /**
  47696. * A reference to the WebGL 2 backend.
  47697. *
  47698. * @type {WebGLBackend}
  47699. */
  47700. this.backend = backend;
  47701. /**
  47702. * A reference to the rendering context.
  47703. *
  47704. * @type {WebGL2RenderingContext}
  47705. */
  47706. this.gl = this.backend.gl;
  47707. /**
  47708. * A list with all the supported WebGL extensions.
  47709. *
  47710. * @type {Array<string>}
  47711. */
  47712. this.availableExtensions = this.gl.getSupportedExtensions();
  47713. /**
  47714. * A dictionary with requested WebGL extensions.
  47715. * The key is the name of the extension, the value
  47716. * the requested extension object.
  47717. *
  47718. * @type {Object<string,Object>}
  47719. */
  47720. this.extensions = {};
  47721. }
  47722. /**
  47723. * Returns the extension object for the given extension name.
  47724. *
  47725. * @param {string} name - The extension name.
  47726. * @return {Object} The extension object.
  47727. */
  47728. get( name ) {
  47729. let extension = this.extensions[ name ];
  47730. if ( extension === undefined ) {
  47731. extension = this.gl.getExtension( name );
  47732. this.extensions[ name ] = extension;
  47733. }
  47734. return extension;
  47735. }
  47736. /**
  47737. * Returns `true` if the requested extension is available.
  47738. *
  47739. * @param {string} name - The extension name.
  47740. * @return {boolean} Whether the given extension is available or not.
  47741. */
  47742. has( name ) {
  47743. return this.availableExtensions.includes( name );
  47744. }
  47745. }
  47746. /**
  47747. * A WebGL 2 backend utility module for managing the device's capabilities.
  47748. *
  47749. * @private
  47750. */
  47751. class WebGLCapabilities {
  47752. /**
  47753. * Constructs a new utility object.
  47754. *
  47755. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47756. */
  47757. constructor( backend ) {
  47758. /**
  47759. * A reference to the WebGL 2 backend.
  47760. *
  47761. * @type {WebGLBackend}
  47762. */
  47763. this.backend = backend;
  47764. /**
  47765. * This value holds the cached max anisotropy value.
  47766. *
  47767. * @type {?number}
  47768. * @default null
  47769. */
  47770. this.maxAnisotropy = null;
  47771. }
  47772. /**
  47773. * Returns the maximum anisotropy texture filtering value. This value
  47774. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  47775. * WebGL extension.
  47776. *
  47777. * @return {number} The maximum anisotropy texture filtering value.
  47778. */
  47779. getMaxAnisotropy() {
  47780. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  47781. const gl = this.backend.gl;
  47782. const extensions = this.backend.extensions;
  47783. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  47784. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  47785. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  47786. } else {
  47787. this.maxAnisotropy = 0;
  47788. }
  47789. return this.maxAnisotropy;
  47790. }
  47791. }
  47792. const GLFeatureName = {
  47793. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  47794. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  47795. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  47796. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  47797. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  47798. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  47799. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  47800. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  47801. 'OVR_multiview2': 'OVR_multiview2'
  47802. };
  47803. class WebGLBufferRenderer {
  47804. constructor( backend ) {
  47805. this.gl = backend.gl;
  47806. this.extensions = backend.extensions;
  47807. this.info = backend.renderer.info;
  47808. this.mode = null;
  47809. this.index = 0;
  47810. this.type = null;
  47811. this.object = null;
  47812. }
  47813. render( start, count ) {
  47814. const { gl, mode, object, type, info, index } = this;
  47815. if ( index !== 0 ) {
  47816. gl.drawElements( mode, count, type, start );
  47817. } else {
  47818. gl.drawArrays( mode, start, count );
  47819. }
  47820. info.update( object, count, 1 );
  47821. }
  47822. renderInstances( start, count, primcount ) {
  47823. const { gl, mode, type, index, object, info } = this;
  47824. if ( primcount === 0 ) return;
  47825. if ( index !== 0 ) {
  47826. gl.drawElementsInstanced( mode, count, type, start, primcount );
  47827. } else {
  47828. gl.drawArraysInstanced( mode, start, count, primcount );
  47829. }
  47830. info.update( object, count, primcount );
  47831. }
  47832. renderMultiDraw( starts, counts, drawCount ) {
  47833. const { extensions, mode, object, info } = this;
  47834. if ( drawCount === 0 ) return;
  47835. const extension = extensions.get( 'WEBGL_multi_draw' );
  47836. if ( extension === null ) {
  47837. for ( let i = 0; i < drawCount; i ++ ) {
  47838. this.render( starts[ i ], counts[ i ] );
  47839. }
  47840. } else {
  47841. if ( this.index !== 0 ) {
  47842. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  47843. } else {
  47844. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  47845. }
  47846. let elementCount = 0;
  47847. for ( let i = 0; i < drawCount; i ++ ) {
  47848. elementCount += counts[ i ];
  47849. }
  47850. info.update( object, elementCount, 1 );
  47851. }
  47852. }
  47853. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  47854. const { extensions, mode, object, info } = this;
  47855. if ( drawCount === 0 ) return;
  47856. const extension = extensions.get( 'WEBGL_multi_draw' );
  47857. if ( extension === null ) {
  47858. for ( let i = 0; i < drawCount; i ++ ) {
  47859. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  47860. }
  47861. } else {
  47862. if ( this.index !== 0 ) {
  47863. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  47864. } else {
  47865. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  47866. }
  47867. let elementCount = 0;
  47868. for ( let i = 0; i < drawCount; i ++ ) {
  47869. elementCount += counts[ i ] * primcount[ i ];
  47870. }
  47871. info.update( object, elementCount, 1 );
  47872. }
  47873. }
  47874. //
  47875. }
  47876. /**
  47877. * Abstract base class of a timestamp query pool.
  47878. *
  47879. * @abstract
  47880. */
  47881. class TimestampQueryPool {
  47882. /**
  47883. * Creates a new timestamp query pool.
  47884. *
  47885. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  47886. */
  47887. constructor( maxQueries = 256 ) {
  47888. /**
  47889. * Whether to track timestamps or not.
  47890. *
  47891. * @type {boolean}
  47892. * @default true
  47893. */
  47894. this.trackTimestamp = true;
  47895. /**
  47896. * Maximum number of queries this pool can hold.
  47897. *
  47898. * @type {number}
  47899. * @default 256
  47900. */
  47901. this.maxQueries = maxQueries;
  47902. /**
  47903. * How many queries allocated so far.
  47904. *
  47905. * @type {number}
  47906. * @default 0
  47907. */
  47908. this.currentQueryIndex = 0;
  47909. /**
  47910. * Tracks offsets for different contexts.
  47911. *
  47912. * @type {Map<string, number>}
  47913. */
  47914. this.queryOffsets = new Map();
  47915. /**
  47916. * Whether the pool has been disposed or not.
  47917. *
  47918. * @type {boolean}
  47919. * @default false
  47920. */
  47921. this.isDisposed = false;
  47922. /**
  47923. * TODO
  47924. *
  47925. * @type {number}
  47926. * @default 0
  47927. */
  47928. this.lastValue = 0;
  47929. /**
  47930. * Stores all timestamp frames.
  47931. *
  47932. * @type {Array<number>}
  47933. */
  47934. this.frames = [];
  47935. /**
  47936. * TODO
  47937. *
  47938. * @type {boolean}
  47939. * @default false
  47940. */
  47941. this.pendingResolve = false;
  47942. /**
  47943. * Stores the latest timestamp for each render context.
  47944. *
  47945. * @type {Map<string, number>}
  47946. */
  47947. this.timestamps = new Map();
  47948. }
  47949. /**
  47950. * Returns all timestamp frames.
  47951. *
  47952. * @return {Array<number>} The timestamp frames.
  47953. */
  47954. getTimestampFrames() {
  47955. return this.frames;
  47956. }
  47957. /**
  47958. * Returns the timestamp for a given render context.
  47959. *
  47960. * @param {string} uid - A unique identifier for the render context.
  47961. * @return {?number} The timestamp, or undefined if not available.
  47962. */
  47963. getTimestamp( uid ) {
  47964. let timestamp = this.timestamps.get( uid );
  47965. if ( timestamp === undefined ) {
  47966. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  47967. timestamp = 0;
  47968. }
  47969. return timestamp;
  47970. }
  47971. /**
  47972. * Returns whether a timestamp is available for a given render context.
  47973. *
  47974. * @param {string} uid - A unique identifier for the render context.
  47975. * @return {boolean} True if a timestamp is available, false otherwise.
  47976. */
  47977. hasTimestamp( uid ) {
  47978. return this.timestamps.has( uid );
  47979. }
  47980. /**
  47981. * Allocate queries for a specific uid.
  47982. *
  47983. * @abstract
  47984. * @param {string} uid - A unique identifier for the render context.
  47985. * @param {number} frameId - The current frame identifier.
  47986. * @returns {?number}
  47987. */
  47988. allocateQueriesForContext( /* uid, frameId */ ) {}
  47989. /**
  47990. * Resolve all timestamps and return data (or process them).
  47991. *
  47992. * @abstract
  47993. * @async
  47994. * @returns {Promise<number>|number} The resolved timestamp value.
  47995. */
  47996. async resolveQueriesAsync() {}
  47997. /**
  47998. * Dispose of the query pool.
  47999. *
  48000. * @abstract
  48001. */
  48002. dispose() {}
  48003. }
  48004. /**
  48005. * Manages a pool of WebGL timestamp queries for performance measurement.
  48006. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  48007. *
  48008. * @augments TimestampQueryPool
  48009. */
  48010. class WebGLTimestampQueryPool extends TimestampQueryPool {
  48011. /**
  48012. * Creates a new WebGL timestamp query pool.
  48013. *
  48014. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  48015. * @param {string} type - The type identifier for this query pool.
  48016. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  48017. */
  48018. constructor( gl, type, maxQueries = 2048 ) {
  48019. super( maxQueries );
  48020. this.gl = gl;
  48021. this.type = type;
  48022. // Check for timer query extensions
  48023. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  48024. gl.getExtension( 'EXT_disjoint_timer_query' );
  48025. if ( ! this.ext ) {
  48026. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  48027. this.trackTimestamp = false;
  48028. return;
  48029. }
  48030. // Create query objects
  48031. this.queries = [];
  48032. for ( let i = 0; i < this.maxQueries; i ++ ) {
  48033. this.queries.push( gl.createQuery() );
  48034. }
  48035. this.activeQuery = null;
  48036. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  48037. }
  48038. /**
  48039. * Allocates a pair of queries for a given render context.
  48040. *
  48041. * @param {string} uid - A unique identifier for the render context.
  48042. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  48043. */
  48044. allocateQueriesForContext( uid ) {
  48045. if ( ! this.trackTimestamp ) return null;
  48046. // Check if we have enough space for a new query pair
  48047. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  48048. 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() } ).` );
  48049. return null;
  48050. }
  48051. const baseOffset = this.currentQueryIndex;
  48052. this.currentQueryIndex += 2;
  48053. // Initialize query states
  48054. this.queryStates.set( baseOffset, 'inactive' );
  48055. this.queryOffsets.set( uid, baseOffset );
  48056. return baseOffset;
  48057. }
  48058. /**
  48059. * Begins a timestamp query for the specified render context.
  48060. *
  48061. * @param {string} uid - A unique identifier for the render context.
  48062. */
  48063. beginQuery( uid ) {
  48064. if ( ! this.trackTimestamp || this.isDisposed ) {
  48065. return;
  48066. }
  48067. const baseOffset = this.queryOffsets.get( uid );
  48068. if ( baseOffset == null ) {
  48069. return;
  48070. }
  48071. // Don't start a new query if there's an active one
  48072. if ( this.activeQuery !== null ) {
  48073. return;
  48074. }
  48075. const query = this.queries[ baseOffset ];
  48076. if ( ! query ) {
  48077. return;
  48078. }
  48079. try {
  48080. // Only begin if query is inactive
  48081. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  48082. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  48083. this.activeQuery = baseOffset;
  48084. this.queryStates.set( baseOffset, 'started' );
  48085. }
  48086. } catch ( e ) {
  48087. error( 'Error in beginQuery:', e );
  48088. this.activeQuery = null;
  48089. this.queryStates.set( baseOffset, 'inactive' );
  48090. }
  48091. }
  48092. /**
  48093. * Ends the active timestamp query for the specified render context.
  48094. *
  48095. * @param {string} uid - A unique identifier for the render context.
  48096. */
  48097. endQuery( uid ) {
  48098. if ( ! this.trackTimestamp || this.isDisposed ) {
  48099. return;
  48100. }
  48101. const baseOffset = this.queryOffsets.get( uid );
  48102. if ( baseOffset == null ) {
  48103. return;
  48104. }
  48105. // Only end if this is the active query
  48106. if ( this.activeQuery !== baseOffset ) {
  48107. return;
  48108. }
  48109. try {
  48110. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  48111. this.queryStates.set( baseOffset, 'ended' );
  48112. this.activeQuery = null;
  48113. } catch ( e ) {
  48114. error( 'Error in endQuery:', e );
  48115. // Reset state on error
  48116. this.queryStates.set( baseOffset, 'inactive' );
  48117. this.activeQuery = null;
  48118. }
  48119. }
  48120. /**
  48121. * Asynchronously resolves all completed queries and returns the total duration.
  48122. *
  48123. * @async
  48124. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  48125. */
  48126. async resolveQueriesAsync() {
  48127. if ( ! this.trackTimestamp || this.pendingResolve ) {
  48128. return this.lastValue;
  48129. }
  48130. this.pendingResolve = true;
  48131. try {
  48132. // Wait for all ended queries to complete
  48133. const resolvePromises = new Map();
  48134. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  48135. const state = this.queryStates.get( baseOffset );
  48136. if ( state === 'ended' ) {
  48137. const query = this.queries[ baseOffset ];
  48138. resolvePromises.set( uid, this.resolveQuery( query ) );
  48139. }
  48140. }
  48141. if ( resolvePromises.size === 0 ) {
  48142. return this.lastValue;
  48143. }
  48144. //
  48145. const framesDuration = {};
  48146. const frames = [];
  48147. for ( const [ uid, promise ] of resolvePromises ) {
  48148. const match = uid.match( /^(.*):f(\d+)$/ );
  48149. const frame = parseInt( match[ 2 ] );
  48150. if ( frames.includes( frame ) === false ) {
  48151. frames.push( frame );
  48152. }
  48153. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  48154. const duration = await promise;
  48155. this.timestamps.set( uid, duration );
  48156. framesDuration[ frame ] += duration;
  48157. }
  48158. // Return the total duration of the last frame
  48159. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  48160. // Store the last valid result
  48161. this.lastValue = totalDuration;
  48162. this.frames = frames;
  48163. // Reset states
  48164. this.currentQueryIndex = 0;
  48165. this.queryOffsets.clear();
  48166. this.queryStates.clear();
  48167. this.activeQuery = null;
  48168. return totalDuration;
  48169. } catch ( e ) {
  48170. error( 'Error resolving queries:', e );
  48171. return this.lastValue;
  48172. } finally {
  48173. this.pendingResolve = false;
  48174. }
  48175. }
  48176. /**
  48177. * Resolves a single query, checking for completion and disjoint operation.
  48178. *
  48179. * @async
  48180. * @param {WebGLQuery} query - The query object to resolve.
  48181. * @returns {Promise<number>} The elapsed time in milliseconds.
  48182. */
  48183. async resolveQuery( query ) {
  48184. return new Promise( ( resolve ) => {
  48185. if ( this.isDisposed ) {
  48186. resolve( this.lastValue );
  48187. return;
  48188. }
  48189. let timeoutId;
  48190. let isResolved = false;
  48191. const cleanup = () => {
  48192. if ( timeoutId ) {
  48193. clearTimeout( timeoutId );
  48194. timeoutId = null;
  48195. }
  48196. };
  48197. const finalizeResolution = ( value ) => {
  48198. if ( ! isResolved ) {
  48199. isResolved = true;
  48200. cleanup();
  48201. resolve( value );
  48202. }
  48203. };
  48204. const checkQuery = () => {
  48205. if ( this.isDisposed ) {
  48206. finalizeResolution( this.lastValue );
  48207. return;
  48208. }
  48209. try {
  48210. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  48211. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  48212. if ( disjoint ) {
  48213. finalizeResolution( this.lastValue );
  48214. return;
  48215. }
  48216. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  48217. if ( ! available ) {
  48218. timeoutId = setTimeout( checkQuery, 1 );
  48219. return;
  48220. }
  48221. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  48222. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  48223. } catch ( e ) {
  48224. error( 'Error checking query:', e );
  48225. resolve( this.lastValue );
  48226. }
  48227. };
  48228. checkQuery();
  48229. } );
  48230. }
  48231. /**
  48232. * Releases all resources held by this query pool.
  48233. * This includes deleting all query objects and clearing internal state.
  48234. */
  48235. dispose() {
  48236. if ( this.isDisposed ) {
  48237. return;
  48238. }
  48239. this.isDisposed = true;
  48240. if ( ! this.trackTimestamp ) return;
  48241. for ( const query of this.queries ) {
  48242. this.gl.deleteQuery( query );
  48243. }
  48244. this.queries = [];
  48245. this.queryStates.clear();
  48246. this.queryOffsets.clear();
  48247. this.lastValue = 0;
  48248. this.activeQuery = null;
  48249. }
  48250. }
  48251. /**
  48252. * A backend implementation targeting WebGL 2.
  48253. *
  48254. * @private
  48255. * @augments Backend
  48256. */
  48257. class WebGLBackend extends Backend {
  48258. /**
  48259. * WebGLBackend options.
  48260. *
  48261. * @typedef {Object} WebGLBackend~Options
  48262. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  48263. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  48264. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  48265. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  48266. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  48267. * @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.
  48268. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  48269. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  48270. */
  48271. /**
  48272. * Constructs a new WebGPU backend.
  48273. *
  48274. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  48275. */
  48276. constructor( parameters = {} ) {
  48277. super( parameters );
  48278. /**
  48279. * This flag can be used for type testing.
  48280. *
  48281. * @type {boolean}
  48282. * @readonly
  48283. * @default true
  48284. */
  48285. this.isWebGLBackend = true;
  48286. /**
  48287. * A reference to a backend module holding shader attribute-related
  48288. * utility functions.
  48289. *
  48290. * @type {?WebGLAttributeUtils}
  48291. * @default null
  48292. */
  48293. this.attributeUtils = null;
  48294. /**
  48295. * A reference to a backend module holding extension-related
  48296. * utility functions.
  48297. *
  48298. * @type {?WebGLExtensions}
  48299. * @default null
  48300. */
  48301. this.extensions = null;
  48302. /**
  48303. * A reference to a backend module holding capability-related
  48304. * utility functions.
  48305. *
  48306. * @type {?WebGLCapabilities}
  48307. * @default null
  48308. */
  48309. this.capabilities = null;
  48310. /**
  48311. * A reference to a backend module holding texture-related
  48312. * utility functions.
  48313. *
  48314. * @type {?WebGLTextureUtils}
  48315. * @default null
  48316. */
  48317. this.textureUtils = null;
  48318. /**
  48319. * A reference to a backend module holding renderer-related
  48320. * utility functions.
  48321. *
  48322. * @type {?WebGLBufferRenderer}
  48323. * @default null
  48324. */
  48325. this.bufferRenderer = null;
  48326. /**
  48327. * A reference to the rendering context.
  48328. *
  48329. * @type {?WebGL2RenderingContext}
  48330. * @default null
  48331. */
  48332. this.gl = null;
  48333. /**
  48334. * A reference to a backend module holding state-related
  48335. * utility functions.
  48336. *
  48337. * @type {?WebGLState}
  48338. * @default null
  48339. */
  48340. this.state = null;
  48341. /**
  48342. * A reference to a backend module holding common
  48343. * utility functions.
  48344. *
  48345. * @type {?WebGLUtils}
  48346. * @default null
  48347. */
  48348. this.utils = null;
  48349. /**
  48350. * Dictionary for caching VAOs.
  48351. *
  48352. * @type {Object<string,WebGLVertexArrayObject>}
  48353. */
  48354. this.vaoCache = {};
  48355. /**
  48356. * Dictionary for caching transform feedback objects.
  48357. *
  48358. * @type {Object<string,WebGLTransformFeedback>}
  48359. */
  48360. this.transformFeedbackCache = {};
  48361. /**
  48362. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  48363. * Only relevant when using compute shaders.
  48364. *
  48365. * @type {boolean}
  48366. * @default false
  48367. */
  48368. this.discard = false;
  48369. /**
  48370. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  48371. * device does not support the extension.
  48372. *
  48373. * @type {?EXTDisjointTimerQueryWebGL2}
  48374. * @default null
  48375. */
  48376. this.disjoint = null;
  48377. /**
  48378. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  48379. * device does not support the extension.
  48380. *
  48381. * @type {?KHRParallelShaderCompile}
  48382. * @default null
  48383. */
  48384. this.parallel = null;
  48385. /**
  48386. * A reference to the current render context.
  48387. *
  48388. * @private
  48389. * @type {RenderContext}
  48390. * @default null
  48391. */
  48392. this._currentContext = null;
  48393. /**
  48394. * A unique collection of bindings.
  48395. *
  48396. * @private
  48397. * @type {WeakSet<Array<BindGroup>>}
  48398. */
  48399. this._knownBindings = new WeakSet();
  48400. /**
  48401. * Whether the device supports framebuffers invalidation or not.
  48402. *
  48403. * @private
  48404. * @type {boolean}
  48405. */
  48406. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  48407. /**
  48408. * The target framebuffer when rendering with
  48409. * the WebXR device API.
  48410. *
  48411. * @private
  48412. * @type {?WebGLFramebuffer}
  48413. * @default null
  48414. */
  48415. this._xrFramebuffer = null;
  48416. }
  48417. /**
  48418. * Initializes the backend so it is ready for usage.
  48419. *
  48420. * @param {Renderer} renderer - The renderer.
  48421. */
  48422. init( renderer ) {
  48423. super.init( renderer );
  48424. //
  48425. const parameters = this.parameters;
  48426. const contextAttributes = {
  48427. antialias: renderer.currentSamples > 0,
  48428. alpha: true, // always true for performance reasons
  48429. depth: renderer.depth,
  48430. stencil: renderer.stencil
  48431. };
  48432. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  48433. function onContextLost( event ) {
  48434. event.preventDefault();
  48435. const contextLossInfo = {
  48436. api: 'WebGL',
  48437. message: event.statusMessage || 'Unknown reason',
  48438. reason: null,
  48439. originalEvent: event
  48440. };
  48441. renderer.onDeviceLost( contextLossInfo );
  48442. }
  48443. this._onContextLost = onContextLost;
  48444. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  48445. this.gl = glContext;
  48446. this.extensions = new WebGLExtensions( this );
  48447. this.capabilities = new WebGLCapabilities( this );
  48448. this.attributeUtils = new WebGLAttributeUtils( this );
  48449. this.textureUtils = new WebGLTextureUtils( this );
  48450. this.bufferRenderer = new WebGLBufferRenderer( this );
  48451. this.state = new WebGLState( this );
  48452. this.utils = new WebGLUtils( this );
  48453. this.extensions.get( 'EXT_color_buffer_float' );
  48454. this.extensions.get( 'WEBGL_clip_cull_distance' );
  48455. this.extensions.get( 'OES_texture_float_linear' );
  48456. this.extensions.get( 'EXT_color_buffer_half_float' );
  48457. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  48458. this.extensions.get( 'WEBGL_render_shared_exponent' );
  48459. this.extensions.get( 'WEBGL_multi_draw' );
  48460. this.extensions.get( 'OVR_multiview2' );
  48461. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  48462. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  48463. this.drawBuffersIndexedExt = this.extensions.get( 'OES_draw_buffers_indexed' );
  48464. }
  48465. /**
  48466. * The coordinate system of the backend.
  48467. *
  48468. * @type {number}
  48469. * @readonly
  48470. */
  48471. get coordinateSystem() {
  48472. return WebGLCoordinateSystem;
  48473. }
  48474. /**
  48475. * This method performs a readback operation by moving buffer data from
  48476. * a storage buffer attribute from the GPU to the CPU.
  48477. *
  48478. * @async
  48479. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  48480. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  48481. */
  48482. async getArrayBufferAsync( attribute ) {
  48483. return await this.attributeUtils.getArrayBufferAsync( attribute );
  48484. }
  48485. /**
  48486. * Ensures the backend is XR compatible.
  48487. *
  48488. * @async
  48489. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  48490. */
  48491. async makeXRCompatible() {
  48492. const attributes = this.gl.getContextAttributes();
  48493. if ( attributes.xrCompatible !== true ) {
  48494. await this.gl.makeXRCompatible();
  48495. }
  48496. }
  48497. /**
  48498. * Sets the XR rendering destination.
  48499. *
  48500. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  48501. */
  48502. setXRTarget( xrFramebuffer ) {
  48503. this._xrFramebuffer = xrFramebuffer;
  48504. }
  48505. /**
  48506. * Configures the given XR render target with external textures.
  48507. *
  48508. * This method is only relevant when using the WebXR Layers API.
  48509. *
  48510. * @param {XRRenderTarget} renderTarget - The XR render target.
  48511. * @param {WebGLTexture} colorTexture - A native color texture.
  48512. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  48513. */
  48514. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  48515. const gl = this.gl;
  48516. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  48517. if ( depthTexture !== null ) {
  48518. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  48519. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  48520. // The multisample_render_to_texture extension doesn't work properly if there
  48521. // are midframe flushes and an external depth texture.
  48522. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  48523. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  48524. }
  48525. renderTarget._autoAllocateDepthBuffer = false;
  48526. }
  48527. }
  48528. /**
  48529. * Inits a time stamp query for the given render context.
  48530. *
  48531. * @param {string} type - The type of the timestamp query.
  48532. * @param {string} uid - A unique identifier for the timestamp query.
  48533. */
  48534. initTimestampQuery( type, uid ) {
  48535. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  48536. if ( ! this.timestampQueryPool[ type ] ) {
  48537. // TODO: Variable maxQueries?
  48538. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  48539. }
  48540. const timestampQueryPool = this.timestampQueryPool[ type ];
  48541. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  48542. if ( baseOffset !== null ) {
  48543. timestampQueryPool.beginQuery( uid );
  48544. }
  48545. }
  48546. // timestamp utils
  48547. /**
  48548. * Prepares the timestamp buffer.
  48549. *
  48550. * @param {string} type - The type of the timestamp query.
  48551. * @param {string} uid - A unique identifier for the timestamp query.
  48552. */
  48553. prepareTimestampBuffer( type, uid ) {
  48554. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  48555. const timestampQueryPool = this.timestampQueryPool[ type ];
  48556. timestampQueryPool.endQuery( uid );
  48557. }
  48558. /**
  48559. * Returns the backend's rendering context.
  48560. *
  48561. * @return {WebGL2RenderingContext} The rendering context.
  48562. */
  48563. getContext() {
  48564. return this.gl;
  48565. }
  48566. /**
  48567. * This method is executed at the beginning of a render call and prepares
  48568. * the WebGL state for upcoming render calls
  48569. *
  48570. * @param {RenderContext} renderContext - The render context.
  48571. */
  48572. beginRender( renderContext ) {
  48573. const { state } = this;
  48574. const renderContextData = this.get( renderContext );
  48575. //
  48576. if ( renderContext.viewport ) {
  48577. this.updateViewport( renderContext );
  48578. } else {
  48579. const { width, height } = this.getDrawingBufferSize();
  48580. state.viewport( 0, 0, width, height );
  48581. }
  48582. if ( renderContext.scissor ) {
  48583. const { x, y, width, height } = renderContext.scissorValue;
  48584. state.scissor( x, renderContext.height - height - y, width, height );
  48585. }
  48586. //
  48587. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  48588. renderContextData.previousContext = this._currentContext;
  48589. this._currentContext = renderContext;
  48590. this._setFramebuffer( renderContext );
  48591. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  48592. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48593. if ( occlusionQueryCount > 0 ) {
  48594. // Get a reference to the array of objects with queries. The renderContextData property
  48595. // can be changed by another render pass before the async reading of all previous queries complete
  48596. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  48597. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  48598. renderContextData.lastOcclusionObject = null;
  48599. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  48600. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  48601. renderContextData.occlusionQueryIndex = 0;
  48602. }
  48603. }
  48604. /**
  48605. * This method is executed at the end of a render call and finalizes work
  48606. * after draw calls.
  48607. *
  48608. * @param {RenderContext} renderContext - The render context.
  48609. */
  48610. finishRender( renderContext ) {
  48611. const { gl, state } = this;
  48612. const renderContextData = this.get( renderContext );
  48613. const previousContext = renderContextData.previousContext;
  48614. state.resetVertexState();
  48615. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48616. if ( occlusionQueryCount > 0 ) {
  48617. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  48618. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  48619. }
  48620. this.resolveOccludedAsync( renderContext );
  48621. }
  48622. const textures = renderContext.textures;
  48623. if ( textures !== null ) {
  48624. for ( let i = 0; i < textures.length; i ++ ) {
  48625. const texture = textures[ i ];
  48626. if ( texture.generateMipmaps ) {
  48627. this.generateMipmaps( texture );
  48628. }
  48629. }
  48630. }
  48631. this._currentContext = previousContext;
  48632. this._resolveRenderTarget( renderContext );
  48633. if ( previousContext !== null ) {
  48634. this._setFramebuffer( previousContext );
  48635. if ( previousContext.viewport ) {
  48636. this.updateViewport( previousContext );
  48637. } else {
  48638. const { width, height } = this.getDrawingBufferSize();
  48639. state.viewport( 0, 0, width, height );
  48640. }
  48641. }
  48642. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  48643. }
  48644. /**
  48645. * This method processes the result of occlusion queries and writes it
  48646. * into render context data.
  48647. *
  48648. * @async
  48649. * @param {RenderContext} renderContext - The render context.
  48650. */
  48651. resolveOccludedAsync( renderContext ) {
  48652. const renderContextData = this.get( renderContext );
  48653. // handle occlusion query results
  48654. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  48655. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  48656. const occluded = new WeakSet();
  48657. const { gl } = this;
  48658. renderContextData.currentOcclusionQueryObjects = null;
  48659. renderContextData.currentOcclusionQueries = null;
  48660. const check = () => {
  48661. let completed = 0;
  48662. // check all queries and requeue as appropriate
  48663. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  48664. const query = currentOcclusionQueries[ i ];
  48665. if ( query === null ) continue;
  48666. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  48667. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  48668. currentOcclusionQueries[ i ] = null;
  48669. gl.deleteQuery( query );
  48670. completed ++;
  48671. }
  48672. }
  48673. if ( completed < currentOcclusionQueries.length ) {
  48674. requestAnimationFrame( check );
  48675. } else {
  48676. renderContextData.occluded = occluded;
  48677. }
  48678. };
  48679. check();
  48680. }
  48681. }
  48682. /**
  48683. * Returns `true` if the given 3D object is fully occluded by other
  48684. * 3D objects in the scene.
  48685. *
  48686. * @param {RenderContext} renderContext - The render context.
  48687. * @param {Object3D} object - The 3D object to test.
  48688. * @return {boolean} Whether the 3D object is fully occluded or not.
  48689. */
  48690. isOccluded( renderContext, object ) {
  48691. const renderContextData = this.get( renderContext );
  48692. return renderContextData.occluded && renderContextData.occluded.has( object );
  48693. }
  48694. /**
  48695. * Updates the viewport with the values from the given render context.
  48696. *
  48697. * @param {RenderContext} renderContext - The render context.
  48698. */
  48699. updateViewport( renderContext ) {
  48700. const { state } = this;
  48701. const { x, y, width, height } = renderContext.viewportValue;
  48702. state.viewport( x, renderContext.height - height - y, width, height );
  48703. }
  48704. /**
  48705. * Defines the scissor test.
  48706. *
  48707. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  48708. */
  48709. setScissorTest( boolean ) {
  48710. const state = this.state;
  48711. state.setScissorTest( boolean );
  48712. }
  48713. /**
  48714. * Returns the clear color and alpha into a single
  48715. * color object.
  48716. *
  48717. * @return {Color4} The clear color.
  48718. */
  48719. getClearColor() {
  48720. const clearColor = super.getClearColor();
  48721. // Since the canvas is always created with alpha: true,
  48722. // WebGL must always premultiply the clear color.
  48723. clearColor.r *= clearColor.a;
  48724. clearColor.g *= clearColor.a;
  48725. clearColor.b *= clearColor.a;
  48726. return clearColor;
  48727. }
  48728. /**
  48729. * Performs a clear operation.
  48730. *
  48731. * @param {boolean} color - Whether the color buffer should be cleared or not.
  48732. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  48733. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  48734. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  48735. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  48736. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  48737. * or not. Only relevant for explicit clears.
  48738. */
  48739. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  48740. const { gl, renderer } = this;
  48741. if ( descriptor === null ) {
  48742. const clearColor = this.getClearColor();
  48743. descriptor = {
  48744. textures: null,
  48745. clearColorValue: clearColor
  48746. };
  48747. }
  48748. //
  48749. let clear = 0;
  48750. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  48751. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  48752. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  48753. if ( clear !== 0 ) {
  48754. let clearColor;
  48755. if ( descriptor.clearColorValue ) {
  48756. clearColor = descriptor.clearColorValue;
  48757. } else {
  48758. clearColor = this.getClearColor();
  48759. }
  48760. const clearDepth = renderer.getClearDepth();
  48761. const clearStencil = renderer.getClearStencil();
  48762. if ( depth ) this.state.setDepthMask( true );
  48763. if ( descriptor.textures === null ) {
  48764. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  48765. gl.clear( clear );
  48766. } else {
  48767. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  48768. if ( color ) {
  48769. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  48770. if ( i === 0 ) {
  48771. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  48772. } else {
  48773. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  48774. }
  48775. }
  48776. }
  48777. if ( depth && stencil ) {
  48778. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  48779. } else if ( depth ) {
  48780. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  48781. } else if ( stencil ) {
  48782. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  48783. }
  48784. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  48785. }
  48786. }
  48787. }
  48788. /**
  48789. * This method is executed at the beginning of a compute call and
  48790. * prepares the state for upcoming compute tasks.
  48791. *
  48792. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  48793. */
  48794. beginCompute( computeGroup ) {
  48795. const { state, gl } = this;
  48796. //
  48797. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  48798. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  48799. }
  48800. /**
  48801. * Executes a compute command for the given compute node.
  48802. *
  48803. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  48804. * @param {Node} computeNode - The compute node.
  48805. * @param {Array<BindGroup>} bindings - The bindings.
  48806. * @param {ComputePipeline} pipeline - The compute pipeline.
  48807. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  48808. */
  48809. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  48810. const { state, gl } = this;
  48811. if ( this.discard === false ) {
  48812. // required here to handle async behaviour of render.compute()
  48813. gl.enable( gl.RASTERIZER_DISCARD );
  48814. this.discard = true;
  48815. }
  48816. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  48817. const vaoKey = this._getVaoKey( attributes );
  48818. const vaoGPU = this.vaoCache[ vaoKey ];
  48819. if ( vaoGPU === undefined ) {
  48820. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  48821. } else {
  48822. state.setVertexState( vaoGPU );
  48823. }
  48824. state.useProgram( programGPU );
  48825. this._bindUniforms( bindings );
  48826. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  48827. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  48828. gl.beginTransformFeedback( gl.POINTS );
  48829. count = ( count !== null ) ? count : computeNode.count;
  48830. if ( Array.isArray( count ) ) {
  48831. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  48832. count = count[ 0 ];
  48833. } else if ( count && typeof count === 'object' && count.isIndirectStorageBufferAttribute ) {
  48834. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute' );
  48835. count = computeNode.count;
  48836. }
  48837. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  48838. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  48839. } else {
  48840. gl.drawArrays( gl.POINTS, 0, count );
  48841. }
  48842. gl.endTransformFeedback();
  48843. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  48844. // switch active buffers
  48845. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48846. const dualAttributeData = transformBuffers[ i ];
  48847. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  48848. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  48849. }
  48850. dualAttributeData.switchBuffers();
  48851. }
  48852. }
  48853. /**
  48854. * This method is executed at the end of a compute call and
  48855. * finalizes work after compute tasks.
  48856. *
  48857. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  48858. */
  48859. finishCompute( computeGroup ) {
  48860. const gl = this.gl;
  48861. this.discard = false;
  48862. gl.disable( gl.RASTERIZER_DISCARD );
  48863. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  48864. if ( this._currentContext ) {
  48865. this._setFramebuffer( this._currentContext );
  48866. }
  48867. }
  48868. /**
  48869. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  48870. *
  48871. * @param {RenderContext} renderContext - The render context.
  48872. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  48873. *
  48874. * @private
  48875. */
  48876. _isRenderCameraDepthArray( renderContext ) {
  48877. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  48878. }
  48879. /**
  48880. * Executes a draw command for the given render object.
  48881. *
  48882. * @param {RenderObject} renderObject - The render object to draw.
  48883. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  48884. */
  48885. draw( renderObject/*, info*/ ) {
  48886. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  48887. const { programGPU } = this.get( pipeline );
  48888. const { gl, state } = this;
  48889. const contextData = this.get( context );
  48890. const drawParams = renderObject.getDrawParameters();
  48891. if ( drawParams === null ) return;
  48892. //
  48893. this._bindUniforms( renderObject.getBindings() );
  48894. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  48895. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  48896. if ( context.textures !== null && context.textures.length > 1 ) {
  48897. state.setMRTBlending( context.textures );
  48898. }
  48899. state.useProgram( programGPU );
  48900. // vertex state
  48901. const attributes = renderObject.getAttributes();
  48902. const attributesData = this.get( attributes );
  48903. let vaoGPU = attributesData.vaoGPU;
  48904. if ( vaoGPU === undefined ) {
  48905. const vaoKey = this._getVaoKey( attributes );
  48906. vaoGPU = this.vaoCache[ vaoKey ];
  48907. if ( vaoGPU === undefined ) {
  48908. vaoGPU = this._createVao( attributes );
  48909. this.vaoCache[ vaoKey ] = vaoGPU;
  48910. attributesData.vaoGPU = vaoGPU;
  48911. }
  48912. }
  48913. const index = renderObject.getIndex();
  48914. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  48915. state.setVertexState( vaoGPU, indexGPU );
  48916. //
  48917. const lastObject = contextData.lastOcclusionObject;
  48918. if ( lastObject !== object && lastObject !== undefined ) {
  48919. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  48920. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  48921. contextData.occlusionQueryIndex ++;
  48922. }
  48923. if ( object.occlusionTest === true ) {
  48924. const query = gl.createQuery();
  48925. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  48926. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  48927. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  48928. }
  48929. contextData.lastOcclusionObject = object;
  48930. }
  48931. //
  48932. const renderer = this.bufferRenderer;
  48933. if ( object.isPoints ) renderer.mode = gl.POINTS;
  48934. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  48935. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  48936. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  48937. else {
  48938. if ( material.wireframe === true ) {
  48939. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  48940. renderer.mode = gl.LINES;
  48941. } else {
  48942. renderer.mode = gl.TRIANGLES;
  48943. }
  48944. }
  48945. //
  48946. const { vertexCount, instanceCount } = drawParams;
  48947. let { firstVertex } = drawParams;
  48948. renderer.object = object;
  48949. if ( index !== null ) {
  48950. firstVertex *= index.array.BYTES_PER_ELEMENT;
  48951. const indexData = this.get( index );
  48952. renderer.index = index.count;
  48953. renderer.type = indexData.type;
  48954. } else {
  48955. renderer.index = 0;
  48956. }
  48957. const draw = () => {
  48958. if ( object.isBatchedMesh ) {
  48959. if ( object._multiDrawInstances !== null ) {
  48960. // @deprecated, r174
  48961. warnOnce( 'WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  48962. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  48963. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  48964. warnOnce( 'WebGLBackend: WEBGL_multi_draw not supported.' );
  48965. } else {
  48966. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  48967. }
  48968. } else if ( instanceCount > 1 ) {
  48969. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  48970. } else {
  48971. renderer.render( firstVertex, vertexCount );
  48972. }
  48973. };
  48974. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  48975. const cameraData = this.get( renderObject.camera );
  48976. const cameras = renderObject.camera.cameras;
  48977. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  48978. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  48979. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  48980. const indexesGPU = [];
  48981. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  48982. const bufferGPU = gl.createBuffer();
  48983. data[ 0 ] = i;
  48984. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  48985. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  48986. indexesGPU.push( bufferGPU );
  48987. }
  48988. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  48989. }
  48990. const cameraIndexData = this.get( cameraIndex );
  48991. const pixelRatio = this.renderer.getPixelRatio();
  48992. const renderTarget = this._currentContext.renderTarget;
  48993. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  48994. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  48995. if ( isRenderCameraDepthArray ) {
  48996. // Clear the depth texture
  48997. const textureData = this.get( renderTarget.depthTexture );
  48998. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  48999. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  49000. const { stencilBuffer } = renderTarget;
  49001. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49002. this.renderer._activeCubeFace = i;
  49003. this._currentContext.activeCubeFace = i;
  49004. this._setFramebuffer( this._currentContext );
  49005. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  49006. }
  49007. this.renderer._activeCubeFace = prevActiveCubeFace;
  49008. this._currentContext.activeCubeFace = prevActiveCubeFace;
  49009. }
  49010. }
  49011. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49012. const subCamera = cameras[ i ];
  49013. if ( object.layers.test( subCamera.layers ) ) {
  49014. if ( isRenderCameraDepthArray ) {
  49015. // Update the active layer
  49016. this.renderer._activeCubeFace = i;
  49017. this._currentContext.activeCubeFace = i;
  49018. this._setFramebuffer( this._currentContext );
  49019. }
  49020. const vp = subCamera.viewport;
  49021. if ( vp !== undefined ) {
  49022. const x = vp.x * pixelRatio;
  49023. const y = vp.y * pixelRatio;
  49024. const width = vp.width * pixelRatio;
  49025. const height = vp.height * pixelRatio;
  49026. state.viewport(
  49027. Math.floor( x ),
  49028. Math.floor( renderObject.context.height - height - y ),
  49029. Math.floor( width ),
  49030. Math.floor( height )
  49031. );
  49032. }
  49033. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  49034. draw();
  49035. }
  49036. this._currentContext.activeCubeFace = prevActiveCubeFace;
  49037. this.renderer._activeCubeFace = prevActiveCubeFace;
  49038. }
  49039. } else {
  49040. draw();
  49041. }
  49042. }
  49043. /**
  49044. * Explain why always null is returned.
  49045. *
  49046. * @param {RenderObject} renderObject - The render object.
  49047. * @return {boolean} Whether the render pipeline requires an update or not.
  49048. */
  49049. needsRenderUpdate( /*renderObject*/ ) {
  49050. return false;
  49051. }
  49052. /**
  49053. * Explain why no cache key is computed.
  49054. *
  49055. * @param {RenderObject} renderObject - The render object.
  49056. * @return {string} The cache key.
  49057. */
  49058. getRenderCacheKey( /*renderObject*/ ) {
  49059. return '';
  49060. }
  49061. // textures
  49062. /**
  49063. * Creates a default texture for the given texture that can be used
  49064. * as a placeholder until the actual texture is ready for usage.
  49065. *
  49066. * @param {Texture} texture - The texture to create a default texture for.
  49067. */
  49068. createDefaultTexture( texture ) {
  49069. this.textureUtils.createDefaultTexture( texture );
  49070. }
  49071. /**
  49072. * Defines a texture on the GPU for the given texture object.
  49073. *
  49074. * @param {Texture} texture - The texture.
  49075. * @param {Object} [options={}] - Optional configuration parameter.
  49076. */
  49077. createTexture( texture, options ) {
  49078. this.textureUtils.createTexture( texture, options );
  49079. }
  49080. /**
  49081. * Uploads the updated texture data to the GPU.
  49082. *
  49083. * @param {Texture} texture - The texture.
  49084. * @param {Object} [options={}] - Optional configuration parameter.
  49085. */
  49086. updateTexture( texture, options ) {
  49087. this.textureUtils.updateTexture( texture, options );
  49088. }
  49089. /**
  49090. * Generates mipmaps for the given texture.
  49091. *
  49092. * @param {Texture} texture - The texture.
  49093. */
  49094. generateMipmaps( texture ) {
  49095. this.textureUtils.generateMipmaps( texture );
  49096. }
  49097. /**
  49098. * Destroys the GPU data for the given texture object.
  49099. *
  49100. * @param {Texture} texture - The texture.
  49101. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  49102. */
  49103. destroyTexture( texture, isDefaultTexture = false ) {
  49104. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  49105. }
  49106. /**
  49107. * Returns texture data as a typed array.
  49108. *
  49109. * @async
  49110. * @param {Texture} texture - The texture to copy.
  49111. * @param {number} x - The x coordinate of the copy origin.
  49112. * @param {number} y - The y coordinate of the copy origin.
  49113. * @param {number} width - The width of the copy.
  49114. * @param {number} height - The height of the copy.
  49115. * @param {number} faceIndex - The face index.
  49116. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49117. */
  49118. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49119. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  49120. }
  49121. /**
  49122. * This method does nothing since WebGL 2 has no concept of samplers.
  49123. *
  49124. * @param {Texture} texture - The texture to update the sampler for.
  49125. * @return {string} The current sampler key.
  49126. */
  49127. updateSampler( /*texture*/ ) {
  49128. return '';
  49129. }
  49130. // node builder
  49131. /**
  49132. * Returns a node builder for the given render object.
  49133. *
  49134. * @param {RenderObject} object - The render object.
  49135. * @param {Renderer} renderer - The renderer.
  49136. * @return {GLSLNodeBuilder} The node builder.
  49137. */
  49138. createNodeBuilder( object, renderer ) {
  49139. return new GLSLNodeBuilder( object, renderer );
  49140. }
  49141. // program
  49142. /**
  49143. * Creates a shader program from the given programmable stage.
  49144. *
  49145. * @param {ProgrammableStage} program - The programmable stage.
  49146. */
  49147. createProgram( program ) {
  49148. const gl = this.gl;
  49149. const { stage, code } = program;
  49150. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  49151. gl.shaderSource( shader, code );
  49152. gl.compileShader( shader );
  49153. this.set( program, {
  49154. shaderGPU: shader
  49155. } );
  49156. }
  49157. /**
  49158. * Destroys the shader program of the given programmable stage.
  49159. *
  49160. * @param {ProgrammableStage} program - The programmable stage.
  49161. */
  49162. destroyProgram( program ) {
  49163. this.delete( program );
  49164. }
  49165. /**
  49166. * Creates a render pipeline for the given render object.
  49167. *
  49168. * @param {RenderObject} renderObject - The render object.
  49169. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  49170. */
  49171. createRenderPipeline( renderObject, promises ) {
  49172. const gl = this.gl;
  49173. const pipeline = renderObject.pipeline;
  49174. // Program
  49175. const { fragmentProgram, vertexProgram } = pipeline;
  49176. const programGPU = gl.createProgram();
  49177. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  49178. const vertexShader = this.get( vertexProgram ).shaderGPU;
  49179. gl.attachShader( programGPU, fragmentShader );
  49180. gl.attachShader( programGPU, vertexShader );
  49181. gl.linkProgram( programGPU );
  49182. this.set( pipeline, {
  49183. programGPU,
  49184. fragmentShader,
  49185. vertexShader
  49186. } );
  49187. if ( promises !== null && this.parallel ) {
  49188. const p = new Promise( ( resolve /*, reject*/ ) => {
  49189. const parallel = this.parallel;
  49190. const checkStatus = () => {
  49191. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  49192. this._completeCompile( renderObject, pipeline );
  49193. resolve();
  49194. } else {
  49195. requestAnimationFrame( checkStatus );
  49196. }
  49197. };
  49198. checkStatus();
  49199. } );
  49200. promises.push( p );
  49201. return;
  49202. }
  49203. this._completeCompile( renderObject, pipeline );
  49204. }
  49205. /**
  49206. * Formats the source code of error messages.
  49207. *
  49208. * @private
  49209. * @param {string} string - The code.
  49210. * @param {number} errorLine - The error line.
  49211. * @return {string} The formatted code.
  49212. */
  49213. _handleSource( string, errorLine ) {
  49214. const lines = string.split( '\n' );
  49215. const lines2 = [];
  49216. const from = Math.max( errorLine - 6, 0 );
  49217. const to = Math.min( errorLine + 6, lines.length );
  49218. for ( let i = from; i < to; i ++ ) {
  49219. const line = i + 1;
  49220. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  49221. }
  49222. return lines2.join( '\n' );
  49223. }
  49224. /**
  49225. * Gets the shader compilation errors from the info log.
  49226. *
  49227. * @private
  49228. * @param {WebGL2RenderingContext} gl - The rendering context.
  49229. * @param {WebGLShader} shader - The WebGL shader object.
  49230. * @param {string} type - The shader type.
  49231. * @return {string} The shader errors.
  49232. */
  49233. _getShaderErrors( gl, shader, type ) {
  49234. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  49235. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  49236. const errors = shaderInfoLog.trim();
  49237. if ( status && errors === '' ) return '';
  49238. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  49239. if ( errorMatches ) {
  49240. const errorLine = parseInt( errorMatches[ 1 ] );
  49241. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  49242. } else {
  49243. return errors;
  49244. }
  49245. }
  49246. /**
  49247. * Logs shader compilation errors.
  49248. *
  49249. * @private
  49250. * @param {WebGLProgram} programGPU - The WebGL program.
  49251. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  49252. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  49253. */
  49254. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  49255. if ( this.renderer.debug.checkShaderErrors ) {
  49256. const gl = this.gl;
  49257. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  49258. const programLog = programInfoLog.trim();
  49259. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49260. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  49261. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  49262. } else {
  49263. // default error reporting
  49264. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  49265. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  49266. error(
  49267. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  49268. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  49269. 'Program Info Log: ' + programLog + '\n' +
  49270. vertexErrors + '\n' +
  49271. fragmentErrors
  49272. );
  49273. }
  49274. } else if ( programLog !== '' ) {
  49275. warn( 'WebGLProgram: Program Info Log:', programLog );
  49276. }
  49277. }
  49278. }
  49279. /**
  49280. * Completes the shader program setup for the given render object.
  49281. *
  49282. * @private
  49283. * @param {RenderObject} renderObject - The render object.
  49284. * @param {RenderPipeline} pipeline - The render pipeline.
  49285. */
  49286. _completeCompile( renderObject, pipeline ) {
  49287. const { state, gl } = this;
  49288. const pipelineData = this.get( pipeline );
  49289. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  49290. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49291. this._logProgramError( programGPU, fragmentShader, vertexShader );
  49292. }
  49293. state.useProgram( programGPU );
  49294. // Bindings
  49295. const bindings = renderObject.getBindings();
  49296. this._setupBindings( bindings, programGPU );
  49297. //
  49298. this.set( pipeline, {
  49299. programGPU
  49300. } );
  49301. }
  49302. /**
  49303. * Creates a compute pipeline for the given compute node.
  49304. *
  49305. * @param {ComputePipeline} computePipeline - The compute pipeline.
  49306. * @param {Array<BindGroup>} bindings - The bindings.
  49307. */
  49308. createComputePipeline( computePipeline, bindings ) {
  49309. const { state, gl } = this;
  49310. // Program
  49311. const fragmentProgram = {
  49312. stage: 'fragment',
  49313. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  49314. };
  49315. this.createProgram( fragmentProgram );
  49316. const { computeProgram } = computePipeline;
  49317. const programGPU = gl.createProgram();
  49318. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  49319. const vertexShader = this.get( computeProgram ).shaderGPU;
  49320. const transforms = computeProgram.transforms;
  49321. const transformVaryingNames = [];
  49322. const transformAttributeNodes = [];
  49323. for ( let i = 0; i < transforms.length; i ++ ) {
  49324. const transform = transforms[ i ];
  49325. transformVaryingNames.push( transform.varyingName );
  49326. transformAttributeNodes.push( transform.attributeNode );
  49327. }
  49328. gl.attachShader( programGPU, fragmentShader );
  49329. gl.attachShader( programGPU, vertexShader );
  49330. gl.transformFeedbackVaryings(
  49331. programGPU,
  49332. transformVaryingNames,
  49333. gl.SEPARATE_ATTRIBS
  49334. );
  49335. gl.linkProgram( programGPU );
  49336. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49337. this._logProgramError( programGPU, fragmentShader, vertexShader );
  49338. }
  49339. state.useProgram( programGPU );
  49340. // Bindings
  49341. this._setupBindings( bindings, programGPU );
  49342. const attributeNodes = computeProgram.attributes;
  49343. const attributes = [];
  49344. const transformBuffers = [];
  49345. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  49346. const attribute = attributeNodes[ i ].node.attribute;
  49347. attributes.push( attribute );
  49348. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49349. }
  49350. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  49351. const attribute = transformAttributeNodes[ i ].attribute;
  49352. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49353. const attributeData = this.get( attribute );
  49354. transformBuffers.push( attributeData );
  49355. }
  49356. //
  49357. this.set( computePipeline, {
  49358. programGPU,
  49359. transformBuffers,
  49360. attributes
  49361. } );
  49362. }
  49363. /**
  49364. * Creates bindings from the given bind group definition.
  49365. *
  49366. * @param {BindGroup} bindGroup - The bind group.
  49367. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49368. * @param {number} cacheIndex - The cache index.
  49369. * @param {number} version - The version.
  49370. */
  49371. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  49372. if ( this._knownBindings.has( bindings ) === false ) {
  49373. this._knownBindings.add( bindings );
  49374. let uniformBuffers = 0;
  49375. let textures = 0;
  49376. for ( const bindGroup of bindings ) {
  49377. this.set( bindGroup, {
  49378. textures: textures,
  49379. uniformBuffers: uniformBuffers
  49380. } );
  49381. for ( const binding of bindGroup.bindings ) {
  49382. if ( binding.isUniformBuffer ) uniformBuffers ++;
  49383. if ( binding.isSampledTexture ) textures ++;
  49384. }
  49385. }
  49386. }
  49387. this.updateBindings( bindGroup, bindings );
  49388. }
  49389. /**
  49390. * Updates the given bind group definition.
  49391. *
  49392. * @param {BindGroup} bindGroup - The bind group.
  49393. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49394. * @param {number} cacheIndex - The cache index.
  49395. * @param {number} version - The version.
  49396. */
  49397. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  49398. const { gl } = this;
  49399. const bindGroupData = this.get( bindGroup );
  49400. let i = bindGroupData.uniformBuffers;
  49401. let t = bindGroupData.textures;
  49402. for ( const binding of bindGroup.bindings ) {
  49403. const map = this.get( binding );
  49404. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49405. const array = binding.buffer;
  49406. let { bufferGPU } = this.get( array );
  49407. if ( bufferGPU === undefined ) {
  49408. // create
  49409. bufferGPU = gl.createBuffer();
  49410. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49411. gl.bufferData( gl.UNIFORM_BUFFER, array.byteLength, gl.DYNAMIC_DRAW );
  49412. this.set( array, { bufferGPU } );
  49413. } else {
  49414. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49415. }
  49416. // update
  49417. const updateRanges = binding.updateRanges;
  49418. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49419. if ( updateRanges.length === 0 ) {
  49420. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  49421. } else {
  49422. const isTyped = isTypedArray( array );
  49423. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  49424. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49425. const range = updateRanges[ i ];
  49426. const dataOffset = range.start * byteOffsetFactor;
  49427. const size = range.count * byteOffsetFactor;
  49428. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49429. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  49430. }
  49431. }
  49432. map.index = i ++;
  49433. map.bufferGPU = bufferGPU;
  49434. this.set( binding, map );
  49435. } else if ( binding.isSampledTexture ) {
  49436. const { textureGPU, glTextureType } = this.get( binding.texture );
  49437. map.index = t ++;
  49438. map.textureGPU = textureGPU;
  49439. map.glTextureType = glTextureType;
  49440. this.set( binding, map );
  49441. }
  49442. }
  49443. }
  49444. /**
  49445. * Updates a buffer binding.
  49446. *
  49447. * @param {Buffer} binding - The buffer binding to update.
  49448. */
  49449. updateBinding( binding ) {
  49450. const gl = this.gl;
  49451. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49452. const bindingData = this.get( binding );
  49453. const bufferGPU = bindingData.bufferGPU;
  49454. const array = binding.buffer;
  49455. const updateRanges = binding.updateRanges;
  49456. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49457. if ( updateRanges.length === 0 ) {
  49458. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  49459. } else {
  49460. const isTyped = isTypedArray( array );
  49461. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  49462. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49463. const range = updateRanges[ i ];
  49464. const dataOffset = range.start * byteOffsetFactor;
  49465. const size = range.count * byteOffsetFactor;
  49466. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49467. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  49468. }
  49469. }
  49470. }
  49471. }
  49472. // attributes
  49473. /**
  49474. * Creates the GPU buffer of an indexed shader attribute.
  49475. *
  49476. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  49477. */
  49478. createIndexAttribute( attribute ) {
  49479. const gl = this.gl;
  49480. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  49481. }
  49482. /**
  49483. * Creates the GPU buffer of a shader attribute.
  49484. *
  49485. * @param {BufferAttribute} attribute - The buffer attribute.
  49486. */
  49487. createAttribute( attribute ) {
  49488. if ( this.has( attribute ) ) return;
  49489. const gl = this.gl;
  49490. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49491. }
  49492. /**
  49493. * Creates the GPU buffer of a storage attribute.
  49494. *
  49495. * @param {BufferAttribute} attribute - The buffer attribute.
  49496. */
  49497. createStorageAttribute( attribute ) {
  49498. if ( this.has( attribute ) ) return;
  49499. const gl = this.gl;
  49500. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49501. }
  49502. /**
  49503. * Updates the GPU buffer of a shader attribute.
  49504. *
  49505. * @param {BufferAttribute} attribute - The buffer attribute to update.
  49506. */
  49507. updateAttribute( attribute ) {
  49508. this.attributeUtils.updateAttribute( attribute );
  49509. }
  49510. /**
  49511. * Destroys the GPU buffer of a shader attribute.
  49512. *
  49513. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  49514. */
  49515. destroyAttribute( attribute ) {
  49516. this.attributeUtils.destroyAttribute( attribute );
  49517. }
  49518. /**
  49519. * Checks if the given feature is supported by the backend.
  49520. *
  49521. * @param {string} name - The feature's name.
  49522. * @return {boolean} Whether the feature is supported or not.
  49523. */
  49524. hasFeature( name ) {
  49525. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  49526. const extensions = this.extensions;
  49527. for ( let i = 0; i < keysMatching.length; i ++ ) {
  49528. if ( extensions.has( keysMatching[ i ] ) ) return true;
  49529. }
  49530. return false;
  49531. }
  49532. /**
  49533. * Returns the maximum anisotropy texture filtering value.
  49534. *
  49535. * @return {number} The maximum anisotropy texture filtering value.
  49536. */
  49537. getMaxAnisotropy() {
  49538. return this.capabilities.getMaxAnisotropy();
  49539. }
  49540. /**
  49541. * Copies data of the given source texture to the given destination texture.
  49542. *
  49543. * @param {Texture} srcTexture - The source texture.
  49544. * @param {Texture} dstTexture - The destination texture.
  49545. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  49546. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  49547. * @param {number} [srcLevel=0] - The source mip level to copy from.
  49548. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  49549. */
  49550. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  49551. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  49552. }
  49553. /**
  49554. * Copies the current bound framebuffer to the given texture.
  49555. *
  49556. * @param {Texture} texture - The destination texture.
  49557. * @param {RenderContext} renderContext - The render context.
  49558. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  49559. */
  49560. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  49561. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  49562. }
  49563. /**
  49564. * Configures the active framebuffer from the given render context.
  49565. *
  49566. * @private
  49567. * @param {RenderContext} descriptor - The render context.
  49568. */
  49569. _setFramebuffer( descriptor ) {
  49570. const { gl, state } = this;
  49571. let currentFrameBuffer = null;
  49572. if ( descriptor.textures !== null ) {
  49573. const renderTarget = descriptor.renderTarget;
  49574. const renderTargetContextData = this.get( renderTarget );
  49575. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  49576. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  49577. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  49578. const isRenderTargetArray = renderTarget.depth > 1;
  49579. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  49580. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  49581. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  49582. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  49583. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  49584. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  49585. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  49586. const cacheKey = getCacheKey( descriptor );
  49587. let fb;
  49588. if ( isCube ) {
  49589. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  49590. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  49591. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  49592. fb = this._xrFramebuffer;
  49593. } else {
  49594. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  49595. fb = renderTargetContextData.framebuffers[ cacheKey ];
  49596. }
  49597. if ( fb === undefined ) {
  49598. fb = gl.createFramebuffer();
  49599. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49600. const textures = descriptor.textures;
  49601. const depthInvalidationArray = [];
  49602. if ( isCube ) {
  49603. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  49604. const { textureGPU } = this.get( textures[ 0 ] );
  49605. const cubeFace = this.renderer._activeCubeFace;
  49606. const mipLevel = this.renderer._activeMipmapLevel;
  49607. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  49608. } else {
  49609. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  49610. for ( let i = 0; i < textures.length; i ++ ) {
  49611. const texture = textures[ i ];
  49612. const textureData = this.get( texture );
  49613. textureData.renderTarget = descriptor.renderTarget;
  49614. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  49615. const attachment = gl.COLOR_ATTACHMENT0 + i;
  49616. if ( renderTarget.multiview ) {
  49617. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  49618. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  49619. const layer = this.renderer._activeCubeFace;
  49620. const mipLevel = this.renderer._activeMipmapLevel;
  49621. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  49622. } else {
  49623. if ( useMultisampledRTT ) {
  49624. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49625. } else {
  49626. const mipLevel = this.renderer._activeMipmapLevel;
  49627. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  49628. }
  49629. }
  49630. }
  49631. }
  49632. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49633. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  49634. const renderbuffer = gl.createRenderbuffer();
  49635. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  49636. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  49637. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  49638. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  49639. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  49640. } else {
  49641. if ( descriptor.depthTexture !== null ) {
  49642. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  49643. const textureData = this.get( descriptor.depthTexture );
  49644. textureData.renderTarget = descriptor.renderTarget;
  49645. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  49646. if ( renderTarget.multiview ) {
  49647. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  49648. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  49649. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49650. } else {
  49651. if ( descriptor.depthTexture.isArrayTexture ) {
  49652. const layer = this.renderer._activeCubeFace;
  49653. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  49654. } else {
  49655. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49656. }
  49657. }
  49658. }
  49659. }
  49660. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  49661. } else {
  49662. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  49663. if ( isRenderCameraDepthArray ) {
  49664. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49665. const layer = this.renderer._activeCubeFace;
  49666. const depthData = this.get( descriptor.depthTexture );
  49667. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49668. gl.framebufferTextureLayer(
  49669. gl.FRAMEBUFFER,
  49670. depthStyle,
  49671. depthData.textureGPU,
  49672. 0,
  49673. layer
  49674. );
  49675. }
  49676. // rebind external XR textures
  49677. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  49678. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49679. // rebind color
  49680. const textureData = this.get( descriptor.textures[ 0 ] );
  49681. if ( renderTarget.multiview ) {
  49682. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  49683. } else if ( useMultisampledRTT ) {
  49684. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49685. } else {
  49686. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49687. }
  49688. // rebind depth
  49689. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49690. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  49691. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  49692. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  49693. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  49694. } else {
  49695. const textureData = this.get( descriptor.depthTexture );
  49696. if ( renderTarget.multiview ) {
  49697. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  49698. } else if ( useMultisampledRTT ) {
  49699. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49700. } else {
  49701. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49702. }
  49703. }
  49704. }
  49705. }
  49706. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  49707. if ( msaaFb === undefined ) {
  49708. const invalidationArray = [];
  49709. msaaFb = gl.createFramebuffer();
  49710. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  49711. const msaaRenderbuffers = [];
  49712. const textures = descriptor.textures;
  49713. for ( let i = 0; i < textures.length; i ++ ) {
  49714. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  49715. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49716. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  49717. const texture = descriptor.textures[ i ];
  49718. const textureData = this.get( texture );
  49719. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  49720. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49721. }
  49722. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  49723. renderTargetContextData.msaaFrameBuffer = msaaFb;
  49724. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  49725. if ( depthBuffer && depthRenderbuffer === undefined ) {
  49726. depthRenderbuffer = gl.createRenderbuffer();
  49727. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  49728. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  49729. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49730. invalidationArray.push( depthStyle );
  49731. }
  49732. renderTargetContextData.invalidationArray = invalidationArray;
  49733. }
  49734. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  49735. } else {
  49736. currentFrameBuffer = fb;
  49737. }
  49738. state.drawBuffers( descriptor, fb );
  49739. }
  49740. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  49741. }
  49742. /**
  49743. * Computes the VAO key for the given index and attributes.
  49744. *
  49745. * @private
  49746. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  49747. * @return {string} The VAO key.
  49748. */
  49749. _getVaoKey( attributes ) {
  49750. let key = '';
  49751. for ( let i = 0; i < attributes.length; i ++ ) {
  49752. const attributeData = this.get( attributes[ i ] );
  49753. key += ':' + attributeData.id;
  49754. }
  49755. return key;
  49756. }
  49757. /**
  49758. * Creates a VAO from the index and attributes.
  49759. *
  49760. * @private
  49761. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  49762. * @return {Object} The VAO data.
  49763. */
  49764. _createVao( attributes ) {
  49765. const { gl } = this;
  49766. const vaoGPU = gl.createVertexArray();
  49767. gl.bindVertexArray( vaoGPU );
  49768. for ( let i = 0; i < attributes.length; i ++ ) {
  49769. const attribute = attributes[ i ];
  49770. const attributeData = this.get( attribute );
  49771. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  49772. gl.enableVertexAttribArray( i );
  49773. let stride, offset;
  49774. if ( attribute.isInterleavedBufferAttribute === true ) {
  49775. stride = attribute.data.stride * attributeData.bytesPerElement;
  49776. offset = attribute.offset * attributeData.bytesPerElement;
  49777. } else {
  49778. stride = 0;
  49779. offset = 0;
  49780. }
  49781. if ( attributeData.isInteger ) {
  49782. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  49783. } else {
  49784. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  49785. }
  49786. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  49787. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  49788. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  49789. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  49790. }
  49791. }
  49792. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  49793. return vaoGPU;
  49794. }
  49795. /**
  49796. * Creates a transform feedback from the given transform buffers.
  49797. *
  49798. * @private
  49799. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  49800. * @return {WebGLTransformFeedback} The transform feedback.
  49801. */
  49802. _getTransformFeedback( transformBuffers ) {
  49803. let key = '';
  49804. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  49805. key += ':' + transformBuffers[ i ].id;
  49806. }
  49807. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  49808. if ( transformFeedbackGPU !== undefined ) {
  49809. return transformFeedbackGPU;
  49810. }
  49811. const { gl } = this;
  49812. transformFeedbackGPU = gl.createTransformFeedback();
  49813. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  49814. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  49815. const attributeData = transformBuffers[ i ];
  49816. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  49817. }
  49818. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  49819. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  49820. return transformFeedbackGPU;
  49821. }
  49822. /**
  49823. * Setups the given bindings.
  49824. *
  49825. * @private
  49826. * @param {Array<BindGroup>} bindings - The bindings.
  49827. * @param {WebGLProgram} programGPU - The WebGL program.
  49828. */
  49829. _setupBindings( bindings, programGPU ) {
  49830. const gl = this.gl;
  49831. for ( const bindGroup of bindings ) {
  49832. for ( const binding of bindGroup.bindings ) {
  49833. const bindingData = this.get( binding );
  49834. const index = bindingData.index;
  49835. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49836. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  49837. gl.uniformBlockBinding( programGPU, location, index );
  49838. } else if ( binding.isSampledTexture ) {
  49839. const location = gl.getUniformLocation( programGPU, binding.name );
  49840. gl.uniform1i( location, index );
  49841. }
  49842. }
  49843. }
  49844. }
  49845. /**
  49846. * Binds the given uniforms.
  49847. *
  49848. * @private
  49849. * @param {Array<BindGroup>} bindings - The bindings.
  49850. */
  49851. _bindUniforms( bindings ) {
  49852. const { gl, state } = this;
  49853. for ( const bindGroup of bindings ) {
  49854. for ( const binding of bindGroup.bindings ) {
  49855. const bindingData = this.get( binding );
  49856. const index = bindingData.index;
  49857. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49858. // TODO USE bindBufferRange to group multiple uniform buffers
  49859. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  49860. } else if ( binding.isSampledTexture ) {
  49861. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  49862. }
  49863. }
  49864. }
  49865. }
  49866. /**
  49867. * The method ensures multisampled render targets are resolved.
  49868. *
  49869. * @private
  49870. * @param {RenderContext} renderContext - The render context.
  49871. */
  49872. _resolveRenderTarget( renderContext ) {
  49873. const { gl, state } = this;
  49874. const renderTarget = renderContext.renderTarget;
  49875. if ( renderContext.textures !== null && renderTarget ) {
  49876. const renderTargetContextData = this.get( renderTarget );
  49877. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  49878. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  49879. let mask = gl.COLOR_BUFFER_BIT;
  49880. if ( renderTarget.resolveDepthBuffer ) {
  49881. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  49882. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  49883. }
  49884. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  49885. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  49886. const textures = renderContext.textures;
  49887. const isMRT = textures.length > 1;
  49888. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  49889. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  49890. if ( isMRT ) {
  49891. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  49892. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  49893. for ( let i = 0; i < textures.length; i ++ ) {
  49894. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  49895. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  49896. }
  49897. }
  49898. for ( let i = 0; i < textures.length; i ++ ) {
  49899. if ( isMRT ) {
  49900. // configure attachment for resolve
  49901. const { textureGPU } = this.get( textures[ i ] );
  49902. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49903. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  49904. }
  49905. if ( renderContext.scissor ) {
  49906. const { x, y, width, height } = renderContext.scissorValue;
  49907. const viewY = renderContext.height - height - y;
  49908. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  49909. } else {
  49910. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  49911. }
  49912. }
  49913. if ( isMRT ) {
  49914. // restore attachments
  49915. for ( let i = 0; i < textures.length; i ++ ) {
  49916. const { textureGPU } = this.get( textures[ i ] );
  49917. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49918. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  49919. }
  49920. }
  49921. if ( this._supportsInvalidateFramebuffer === true ) {
  49922. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  49923. }
  49924. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  49925. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  49926. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  49927. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  49928. }
  49929. }
  49930. }
  49931. /**
  49932. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  49933. * should be used when MSAA is enabled.
  49934. *
  49935. * @private
  49936. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  49937. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  49938. */
  49939. _useMultisampledExtension( renderTarget ) {
  49940. if ( renderTarget.multiview === true ) {
  49941. return true;
  49942. }
  49943. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  49944. }
  49945. /**
  49946. * Frees internal resources.
  49947. */
  49948. dispose() {
  49949. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  49950. const extension = this.extensions.get( 'WEBGL_lose_context' );
  49951. if ( extension ) extension.loseContext();
  49952. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  49953. }
  49954. }
  49955. const GPUPrimitiveTopology = {
  49956. PointList: 'point-list',
  49957. LineList: 'line-list',
  49958. LineStrip: 'line-strip',
  49959. TriangleList: 'triangle-list',
  49960. TriangleStrip: 'triangle-strip',
  49961. };
  49962. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  49963. const GPUCompareFunction = {
  49964. Never: 'never',
  49965. Less: 'less',
  49966. Equal: 'equal',
  49967. LessEqual: 'less-equal',
  49968. Greater: 'greater',
  49969. NotEqual: 'not-equal',
  49970. GreaterEqual: 'greater-equal',
  49971. Always: 'always'
  49972. };
  49973. const GPUStoreOp = {
  49974. Store: 'store'};
  49975. const GPULoadOp = {
  49976. Load: 'load',
  49977. Clear: 'clear'
  49978. };
  49979. const GPUFrontFace = {
  49980. CCW: 'ccw',
  49981. CW: 'cw'
  49982. };
  49983. const GPUCullMode = {
  49984. None: 'none',
  49985. Back: 'back'
  49986. };
  49987. const GPUIndexFormat = {
  49988. Uint16: 'uint16',
  49989. Uint32: 'uint32'
  49990. };
  49991. const GPUTextureFormat = {
  49992. // 8-bit formats
  49993. R8Unorm: 'r8unorm',
  49994. R8Snorm: 'r8snorm',
  49995. R8Uint: 'r8uint',
  49996. R8Sint: 'r8sint',
  49997. // 16-bit formats
  49998. R16Uint: 'r16uint',
  49999. R16Sint: 'r16sint',
  50000. R16Float: 'r16float',
  50001. RG8Unorm: 'rg8unorm',
  50002. RG8Snorm: 'rg8snorm',
  50003. RG8Uint: 'rg8uint',
  50004. RG8Sint: 'rg8sint',
  50005. // 32-bit formats
  50006. R32Uint: 'r32uint',
  50007. R32Sint: 'r32sint',
  50008. R32Float: 'r32float',
  50009. RG16Uint: 'rg16uint',
  50010. RG16Sint: 'rg16sint',
  50011. RG16Float: 'rg16float',
  50012. RGBA8Unorm: 'rgba8unorm',
  50013. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  50014. RGBA8Snorm: 'rgba8snorm',
  50015. RGBA8Uint: 'rgba8uint',
  50016. RGBA8Sint: 'rgba8sint',
  50017. BGRA8Unorm: 'bgra8unorm',
  50018. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  50019. // Packed 32-bit formats
  50020. RGB9E5UFloat: 'rgb9e5ufloat',
  50021. RGB10A2Unorm: 'rgb10a2unorm',
  50022. RG11B10UFloat: 'rg11b10ufloat',
  50023. // 64-bit formats
  50024. RG32Uint: 'rg32uint',
  50025. RG32Sint: 'rg32sint',
  50026. RG32Float: 'rg32float',
  50027. RGBA16Uint: 'rgba16uint',
  50028. RGBA16Sint: 'rgba16sint',
  50029. RGBA16Float: 'rgba16float',
  50030. // 128-bit formats
  50031. RGBA32Uint: 'rgba32uint',
  50032. RGBA32Sint: 'rgba32sint',
  50033. RGBA32Float: 'rgba32float',
  50034. Depth16Unorm: 'depth16unorm',
  50035. Depth24Plus: 'depth24plus',
  50036. Depth24PlusStencil8: 'depth24plus-stencil8',
  50037. Depth32Float: 'depth32float',
  50038. // 'depth32float-stencil8' extension
  50039. Depth32FloatStencil8: 'depth32float-stencil8',
  50040. // BC compressed formats usable if 'texture-compression-bc' is both
  50041. // supported by the device/user agent and enabled in requestDevice.
  50042. BC1RGBAUnorm: 'bc1-rgba-unorm',
  50043. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  50044. BC2RGBAUnorm: 'bc2-rgba-unorm',
  50045. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  50046. BC3RGBAUnorm: 'bc3-rgba-unorm',
  50047. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  50048. BC4RUnorm: 'bc4-r-unorm',
  50049. BC4RSnorm: 'bc4-r-snorm',
  50050. BC5RGUnorm: 'bc5-rg-unorm',
  50051. BC5RGSnorm: 'bc5-rg-snorm',
  50052. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  50053. BC6HRGBFloat: 'bc6h-rgb-float',
  50054. BC7RGBAUnorm: 'bc7-rgba-unorm',
  50055. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  50056. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  50057. // supported by the device/user agent and enabled in requestDevice.
  50058. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  50059. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  50060. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  50061. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  50062. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  50063. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  50064. EACR11Unorm: 'eac-r11unorm',
  50065. EACR11Snorm: 'eac-r11snorm',
  50066. EACRG11Unorm: 'eac-rg11unorm',
  50067. EACRG11Snorm: 'eac-rg11snorm',
  50068. // ASTC compressed formats usable if 'texture-compression-astc' is both
  50069. // supported by the device/user agent and enabled in requestDevice.
  50070. ASTC4x4Unorm: 'astc-4x4-unorm',
  50071. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  50072. ASTC5x4Unorm: 'astc-5x4-unorm',
  50073. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  50074. ASTC5x5Unorm: 'astc-5x5-unorm',
  50075. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  50076. ASTC6x5Unorm: 'astc-6x5-unorm',
  50077. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  50078. ASTC6x6Unorm: 'astc-6x6-unorm',
  50079. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  50080. ASTC8x5Unorm: 'astc-8x5-unorm',
  50081. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  50082. ASTC8x6Unorm: 'astc-8x6-unorm',
  50083. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  50084. ASTC8x8Unorm: 'astc-8x8-unorm',
  50085. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  50086. ASTC10x5Unorm: 'astc-10x5-unorm',
  50087. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  50088. ASTC10x6Unorm: 'astc-10x6-unorm',
  50089. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  50090. ASTC10x8Unorm: 'astc-10x8-unorm',
  50091. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  50092. ASTC10x10Unorm: 'astc-10x10-unorm',
  50093. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  50094. ASTC12x10Unorm: 'astc-12x10-unorm',
  50095. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  50096. ASTC12x12Unorm: 'astc-12x12-unorm',
  50097. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  50098. };
  50099. const GPUAddressMode = {
  50100. ClampToEdge: 'clamp-to-edge',
  50101. Repeat: 'repeat',
  50102. MirrorRepeat: 'mirror-repeat'
  50103. };
  50104. const GPUFilterMode = {
  50105. Linear: 'linear',
  50106. Nearest: 'nearest'
  50107. };
  50108. const GPUBlendFactor = {
  50109. Zero: 'zero',
  50110. One: 'one',
  50111. Src: 'src',
  50112. OneMinusSrc: 'one-minus-src',
  50113. SrcAlpha: 'src-alpha',
  50114. OneMinusSrcAlpha: 'one-minus-src-alpha',
  50115. Dst: 'dst',
  50116. OneMinusDst: 'one-minus-dst',
  50117. DstAlpha: 'dst-alpha',
  50118. OneMinusDstAlpha: 'one-minus-dst-alpha',
  50119. SrcAlphaSaturated: 'src-alpha-saturated',
  50120. Constant: 'constant',
  50121. OneMinusConstant: 'one-minus-constant'
  50122. };
  50123. const GPUBlendOperation = {
  50124. Add: 'add',
  50125. Subtract: 'subtract',
  50126. ReverseSubtract: 'reverse-subtract',
  50127. Min: 'min',
  50128. Max: 'max'
  50129. };
  50130. const GPUColorWriteFlags = {
  50131. None: 0,
  50132. All: 0xF
  50133. };
  50134. const GPUStencilOperation = {
  50135. Keep: 'keep',
  50136. Zero: 'zero',
  50137. Replace: 'replace',
  50138. Invert: 'invert',
  50139. IncrementClamp: 'increment-clamp',
  50140. DecrementClamp: 'decrement-clamp',
  50141. IncrementWrap: 'increment-wrap',
  50142. DecrementWrap: 'decrement-wrap'
  50143. };
  50144. const GPUBufferBindingType = {
  50145. Storage: 'storage',
  50146. ReadOnlyStorage: 'read-only-storage'
  50147. };
  50148. const GPUStorageTextureAccess = {
  50149. WriteOnly: 'write-only',
  50150. ReadOnly: 'read-only',
  50151. ReadWrite: 'read-write',
  50152. };
  50153. const GPUSamplerBindingType = {
  50154. NonFiltering: 'non-filtering',
  50155. Comparison: 'comparison'
  50156. };
  50157. const GPUTextureSampleType = {
  50158. Float: 'float',
  50159. UnfilterableFloat: 'unfilterable-float',
  50160. Depth: 'depth',
  50161. SInt: 'sint',
  50162. UInt: 'uint'
  50163. };
  50164. const GPUTextureDimension = {
  50165. TwoD: '2d',
  50166. ThreeD: '3d'
  50167. };
  50168. const GPUTextureViewDimension = {
  50169. TwoD: '2d',
  50170. TwoDArray: '2d-array',
  50171. Cube: 'cube',
  50172. ThreeD: '3d'
  50173. };
  50174. const GPUTextureAspect = {
  50175. All: 'all'};
  50176. const GPUInputStepMode = {
  50177. Vertex: 'vertex',
  50178. Instance: 'instance'
  50179. };
  50180. const GPUFeatureName = {
  50181. CoreFeaturesAndLimits: 'core-features-and-limits',
  50182. DepthClipControl: 'depth-clip-control',
  50183. Depth32FloatStencil8: 'depth32float-stencil8',
  50184. TextureCompressionBC: 'texture-compression-bc',
  50185. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  50186. TextureCompressionETC2: 'texture-compression-etc2',
  50187. TextureCompressionASTC: 'texture-compression-astc',
  50188. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  50189. TimestampQuery: 'timestamp-query',
  50190. IndirectFirstInstance: 'indirect-first-instance',
  50191. ShaderF16: 'shader-f16',
  50192. RG11B10UFloat: 'rg11b10ufloat-renderable',
  50193. BGRA8UNormStorage: 'bgra8unorm-storage',
  50194. Float32Filterable: 'float32-filterable',
  50195. Float32Blendable: 'float32-blendable',
  50196. ClipDistances: 'clip-distances',
  50197. DualSourceBlending: 'dual-source-blending',
  50198. Subgroups: 'subgroups',
  50199. TextureFormatsTier1: 'texture-formats-tier1',
  50200. TextureFormatsTier2: 'texture-formats-tier2'
  50201. };
  50202. const GPUFeatureMap = {
  50203. 'texture-compression-s3tc': 'texture-compression-bc',
  50204. 'texture-compression-etc1': 'texture-compression-etc2'
  50205. };
  50206. /**
  50207. * A special form of sampler binding type.
  50208. * It's texture value is managed by a node object.
  50209. *
  50210. * @private
  50211. * @augments Sampler
  50212. */
  50213. class NodeSampler extends Sampler {
  50214. /**
  50215. * Constructs a new node-based sampler.
  50216. *
  50217. * @param {string} name - The samplers's name.
  50218. * @param {TextureNode} textureNode - The texture node.
  50219. * @param {UniformGroupNode} groupNode - The uniform group node.
  50220. */
  50221. constructor( name, textureNode, groupNode ) {
  50222. super( name, textureNode ? textureNode.value : null );
  50223. /**
  50224. * The texture node.
  50225. *
  50226. * @type {TextureNode}
  50227. */
  50228. this.textureNode = textureNode;
  50229. /**
  50230. * The uniform group node.
  50231. *
  50232. * @type {UniformGroupNode}
  50233. */
  50234. this.groupNode = groupNode;
  50235. }
  50236. /**
  50237. * Updates the texture value of this sampler.
  50238. *
  50239. * @return {boolean} Whether the sampler needs an update or not.
  50240. */
  50241. update() {
  50242. const { textureNode } = this;
  50243. if ( this.texture !== textureNode.value ) {
  50244. this.texture = textureNode.value;
  50245. return true;
  50246. }
  50247. return super.update();
  50248. }
  50249. }
  50250. /**
  50251. * Represents a storage buffer binding type.
  50252. *
  50253. * @private
  50254. * @augments Buffer
  50255. */
  50256. class StorageBuffer extends Buffer {
  50257. /**
  50258. * Constructs a new uniform buffer.
  50259. *
  50260. * @param {string} name - The buffer's name.
  50261. * @param {BufferAttribute} attribute - The buffer attribute.
  50262. */
  50263. constructor( name, attribute ) {
  50264. super( name, attribute ? attribute.array : null );
  50265. /**
  50266. * This flag can be used for type testing.
  50267. *
  50268. * @type {BufferAttribute}
  50269. */
  50270. this.attribute = attribute;
  50271. /**
  50272. * This flag can be used for type testing.
  50273. *
  50274. * @type {boolean}
  50275. * @readonly
  50276. * @default true
  50277. */
  50278. this.isStorageBuffer = true;
  50279. }
  50280. }
  50281. let _id = 0;
  50282. /**
  50283. * A special form of storage buffer binding type.
  50284. * It's buffer value is managed by a node object.
  50285. *
  50286. * @private
  50287. * @augments StorageBuffer
  50288. */
  50289. class NodeStorageBuffer extends StorageBuffer {
  50290. /**
  50291. * Constructs a new node-based storage buffer.
  50292. *
  50293. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  50294. * @param {UniformGroupNode} groupNode - The uniform group node.
  50295. */
  50296. constructor( nodeUniform, groupNode ) {
  50297. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  50298. /**
  50299. * The node uniform.
  50300. *
  50301. * @type {StorageBufferNode}
  50302. */
  50303. this.nodeUniform = nodeUniform;
  50304. /**
  50305. * The access type.
  50306. *
  50307. * @type {string}
  50308. */
  50309. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  50310. /**
  50311. * The uniform group node.
  50312. *
  50313. * @type {UniformGroupNode}
  50314. */
  50315. this.groupNode = groupNode;
  50316. }
  50317. /**
  50318. * The storage buffer.
  50319. *
  50320. * @type {BufferAttribute}
  50321. */
  50322. get buffer() {
  50323. return this.nodeUniform.value;
  50324. }
  50325. }
  50326. /**
  50327. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  50328. *
  50329. * @private
  50330. */
  50331. class WebGPUTexturePassUtils extends DataMap {
  50332. /**
  50333. * Constructs a new utility object.
  50334. *
  50335. * @param {GPUDevice} device - The WebGPU device.
  50336. */
  50337. constructor( device ) {
  50338. super();
  50339. /**
  50340. * The WebGPU device.
  50341. *
  50342. * @type {GPUDevice}
  50343. */
  50344. this.device = device;
  50345. const mipmapVertexSource = `
  50346. struct VarysStruct {
  50347. @builtin( position ) Position: vec4<f32>,
  50348. @location( 0 ) vTex : vec2<f32>
  50349. };
  50350. @vertex
  50351. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  50352. var Varys : VarysStruct;
  50353. var pos = array< vec2<f32>, 4 >(
  50354. vec2<f32>( -1.0, 1.0 ),
  50355. vec2<f32>( 1.0, 1.0 ),
  50356. vec2<f32>( -1.0, -1.0 ),
  50357. vec2<f32>( 1.0, -1.0 )
  50358. );
  50359. var tex = array< vec2<f32>, 4 >(
  50360. vec2<f32>( 0.0, 0.0 ),
  50361. vec2<f32>( 1.0, 0.0 ),
  50362. vec2<f32>( 0.0, 1.0 ),
  50363. vec2<f32>( 1.0, 1.0 )
  50364. );
  50365. Varys.vTex = tex[ vertexIndex ];
  50366. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  50367. return Varys;
  50368. }
  50369. `;
  50370. const mipmapFragmentSource = `
  50371. @group( 0 ) @binding( 0 )
  50372. var imgSampler : sampler;
  50373. @group( 0 ) @binding( 1 )
  50374. var img : texture_2d<f32>;
  50375. @fragment
  50376. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  50377. return textureSample( img, imgSampler, vTex );
  50378. }
  50379. `;
  50380. const flipYFragmentSource = `
  50381. @group( 0 ) @binding( 0 )
  50382. var imgSampler : sampler;
  50383. @group( 0 ) @binding( 1 )
  50384. var img : texture_2d<f32>;
  50385. @fragment
  50386. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  50387. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  50388. }
  50389. `;
  50390. /**
  50391. * The mipmap GPU sampler.
  50392. *
  50393. * @type {GPUSampler}
  50394. */
  50395. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  50396. /**
  50397. * The flipY GPU sampler.
  50398. *
  50399. * @type {GPUSampler}
  50400. */
  50401. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  50402. /**
  50403. * A cache for GPU render pipelines used for copy/transfer passes.
  50404. * Every texture format requires a unique pipeline.
  50405. *
  50406. * @type {Object<string,GPURenderPipeline>}
  50407. */
  50408. this.transferPipelines = {};
  50409. /**
  50410. * A cache for GPU render pipelines used for flipY passes.
  50411. * Every texture format requires a unique pipeline.
  50412. *
  50413. * @type {Object<string,GPURenderPipeline>}
  50414. */
  50415. this.flipYPipelines = {};
  50416. /**
  50417. * The mipmap vertex shader module.
  50418. *
  50419. * @type {GPUShaderModule}
  50420. */
  50421. this.mipmapVertexShaderModule = device.createShaderModule( {
  50422. label: 'mipmapVertex',
  50423. code: mipmapVertexSource
  50424. } );
  50425. /**
  50426. * The mipmap fragment shader module.
  50427. *
  50428. * @type {GPUShaderModule}
  50429. */
  50430. this.mipmapFragmentShaderModule = device.createShaderModule( {
  50431. label: 'mipmapFragment',
  50432. code: mipmapFragmentSource
  50433. } );
  50434. /**
  50435. * The flipY fragment shader module.
  50436. *
  50437. * @type {GPUShaderModule}
  50438. */
  50439. this.flipYFragmentShaderModule = device.createShaderModule( {
  50440. label: 'flipYFragment',
  50441. code: flipYFragmentSource
  50442. } );
  50443. }
  50444. /**
  50445. * Returns a render pipeline for the internal copy render pass. The pass
  50446. * requires a unique render pipeline for each texture format.
  50447. *
  50448. * @param {string} format - The GPU texture format
  50449. * @return {GPURenderPipeline} The GPU render pipeline.
  50450. */
  50451. getTransferPipeline( format ) {
  50452. let pipeline = this.transferPipelines[ format ];
  50453. if ( pipeline === undefined ) {
  50454. pipeline = this.device.createRenderPipeline( {
  50455. label: `mipmap-${ format }`,
  50456. vertex: {
  50457. module: this.mipmapVertexShaderModule,
  50458. entryPoint: 'main'
  50459. },
  50460. fragment: {
  50461. module: this.mipmapFragmentShaderModule,
  50462. entryPoint: 'main',
  50463. targets: [ { format } ]
  50464. },
  50465. primitive: {
  50466. topology: GPUPrimitiveTopology.TriangleStrip,
  50467. stripIndexFormat: GPUIndexFormat.Uint32
  50468. },
  50469. layout: 'auto'
  50470. } );
  50471. this.transferPipelines[ format ] = pipeline;
  50472. }
  50473. return pipeline;
  50474. }
  50475. /**
  50476. * Returns a render pipeline for the flipY render pass. The pass
  50477. * requires a unique render pipeline for each texture format.
  50478. *
  50479. * @param {string} format - The GPU texture format
  50480. * @return {GPURenderPipeline} The GPU render pipeline.
  50481. */
  50482. getFlipYPipeline( format ) {
  50483. let pipeline = this.flipYPipelines[ format ];
  50484. if ( pipeline === undefined ) {
  50485. pipeline = this.device.createRenderPipeline( {
  50486. label: `flipY-${ format }`,
  50487. vertex: {
  50488. module: this.mipmapVertexShaderModule,
  50489. entryPoint: 'main'
  50490. },
  50491. fragment: {
  50492. module: this.flipYFragmentShaderModule,
  50493. entryPoint: 'main',
  50494. targets: [ { format } ]
  50495. },
  50496. primitive: {
  50497. topology: GPUPrimitiveTopology.TriangleStrip,
  50498. stripIndexFormat: GPUIndexFormat.Uint32
  50499. },
  50500. layout: 'auto'
  50501. } );
  50502. this.flipYPipelines[ format ] = pipeline;
  50503. }
  50504. return pipeline;
  50505. }
  50506. /**
  50507. * Flip the contents of the given GPU texture along its vertical axis.
  50508. *
  50509. * @param {GPUTexture} textureGPU - The GPU texture object.
  50510. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50511. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  50512. */
  50513. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  50514. const format = textureGPUDescriptor.format;
  50515. const { width, height } = textureGPUDescriptor.size;
  50516. const transferPipeline = this.getTransferPipeline( format );
  50517. const flipYPipeline = this.getFlipYPipeline( format );
  50518. const tempTexture = this.device.createTexture( {
  50519. size: { width, height, depthOrArrayLayers: 1 },
  50520. format,
  50521. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  50522. } );
  50523. const srcView = textureGPU.createView( {
  50524. baseMipLevel: 0,
  50525. mipLevelCount: 1,
  50526. dimension: GPUTextureViewDimension.TwoD,
  50527. baseArrayLayer
  50528. } );
  50529. const dstView = tempTexture.createView( {
  50530. baseMipLevel: 0,
  50531. mipLevelCount: 1,
  50532. dimension: GPUTextureViewDimension.TwoD,
  50533. baseArrayLayer: 0
  50534. } );
  50535. const commandEncoder = this.device.createCommandEncoder( {} );
  50536. const pass = ( pipeline, sourceView, destinationView ) => {
  50537. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  50538. const bindGroup = this.device.createBindGroup( {
  50539. layout: bindGroupLayout,
  50540. entries: [ {
  50541. binding: 0,
  50542. resource: this.flipYSampler
  50543. }, {
  50544. binding: 1,
  50545. resource: sourceView
  50546. } ]
  50547. } );
  50548. const passEncoder = commandEncoder.beginRenderPass( {
  50549. colorAttachments: [ {
  50550. view: destinationView,
  50551. loadOp: GPULoadOp.Clear,
  50552. storeOp: GPUStoreOp.Store,
  50553. clearValue: [ 0, 0, 0, 0 ]
  50554. } ]
  50555. } );
  50556. passEncoder.setPipeline( pipeline );
  50557. passEncoder.setBindGroup( 0, bindGroup );
  50558. passEncoder.draw( 4, 1, 0, 0 );
  50559. passEncoder.end();
  50560. };
  50561. pass( transferPipeline, srcView, dstView );
  50562. pass( flipYPipeline, dstView, srcView );
  50563. this.device.queue.submit( [ commandEncoder.finish() ] );
  50564. tempTexture.destroy();
  50565. }
  50566. /**
  50567. * Generates mipmaps for the given GPU texture.
  50568. *
  50569. * @param {GPUTexture} textureGPU - The GPU texture object.
  50570. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50571. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  50572. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  50573. */
  50574. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0, encoder = null ) {
  50575. const textureData = this.get( textureGPU );
  50576. if ( textureData.layers === undefined ) {
  50577. textureData.layers = [];
  50578. }
  50579. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  50580. const commandEncoder = encoder || this.device.createCommandEncoder( { label: 'mipmapEncoder' } );
  50581. this._mipmapRunBundles( commandEncoder, passes );
  50582. if ( encoder === null ) this.device.queue.submit( [ commandEncoder.finish() ] );
  50583. textureData.layers[ baseArrayLayer ] = passes;
  50584. }
  50585. /**
  50586. * Since multiple copy render passes are required to generate mipmaps, the passes
  50587. * are managed as render bundles to improve performance.
  50588. *
  50589. * @param {GPUTexture} textureGPU - The GPU texture object.
  50590. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50591. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  50592. * @return {Array<Object>} An array of render bundles.
  50593. */
  50594. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  50595. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  50596. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  50597. let srcView = textureGPU.createView( {
  50598. baseMipLevel: 0,
  50599. mipLevelCount: 1,
  50600. dimension: GPUTextureViewDimension.TwoD,
  50601. baseArrayLayer
  50602. } );
  50603. const passes = [];
  50604. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  50605. const bindGroup = this.device.createBindGroup( {
  50606. layout: bindGroupLayout,
  50607. entries: [ {
  50608. binding: 0,
  50609. resource: this.mipmapSampler
  50610. }, {
  50611. binding: 1,
  50612. resource: srcView
  50613. } ]
  50614. } );
  50615. const dstView = textureGPU.createView( {
  50616. baseMipLevel: i,
  50617. mipLevelCount: 1,
  50618. dimension: GPUTextureViewDimension.TwoD,
  50619. baseArrayLayer
  50620. } );
  50621. const passDescriptor = {
  50622. colorAttachments: [ {
  50623. view: dstView,
  50624. loadOp: GPULoadOp.Clear,
  50625. storeOp: GPUStoreOp.Store,
  50626. clearValue: [ 0, 0, 0, 0 ]
  50627. } ]
  50628. };
  50629. const passEncoder = this.device.createRenderBundleEncoder( {
  50630. colorFormats: [ textureGPUDescriptor.format ]
  50631. } );
  50632. passEncoder.setPipeline( pipeline );
  50633. passEncoder.setBindGroup( 0, bindGroup );
  50634. passEncoder.draw( 4, 1, 0, 0 );
  50635. passes.push( {
  50636. renderBundles: [ passEncoder.finish() ],
  50637. passDescriptor
  50638. } );
  50639. srcView = dstView;
  50640. }
  50641. return passes;
  50642. }
  50643. /**
  50644. * Executes the render bundles.
  50645. *
  50646. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  50647. * @param {Array<Object>} passes - An array of render bundles.
  50648. */
  50649. _mipmapRunBundles( commandEncoder, passes ) {
  50650. const levels = passes.length;
  50651. for ( let i = 0; i < levels; i ++ ) {
  50652. const pass = passes[ i ];
  50653. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  50654. passEncoder.executeBundles( pass.renderBundles );
  50655. passEncoder.end();
  50656. }
  50657. }
  50658. }
  50659. const _compareToWebGPU = {
  50660. [ NeverCompare ]: 'never',
  50661. [ LessCompare ]: 'less',
  50662. [ EqualCompare ]: 'equal',
  50663. [ LessEqualCompare ]: 'less-equal',
  50664. [ GreaterCompare ]: 'greater',
  50665. [ GreaterEqualCompare ]: 'greater-equal',
  50666. [ AlwaysCompare ]: 'always',
  50667. [ NotEqualCompare ]: 'not-equal'
  50668. };
  50669. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  50670. /**
  50671. * A WebGPU backend utility module for managing textures.
  50672. *
  50673. * @private
  50674. */
  50675. class WebGPUTextureUtils {
  50676. /**
  50677. * Constructs a new utility object.
  50678. *
  50679. * @param {WebGPUBackend} backend - The WebGPU backend.
  50680. */
  50681. constructor( backend ) {
  50682. /**
  50683. * A reference to the WebGPU backend.
  50684. *
  50685. * @type {WebGPUBackend}
  50686. */
  50687. this.backend = backend;
  50688. /**
  50689. * A reference to the pass utils.
  50690. *
  50691. * @type {?WebGPUTexturePassUtils}
  50692. * @default null
  50693. */
  50694. this._passUtils = null;
  50695. /**
  50696. * A dictionary for managing default textures. The key
  50697. * is the texture format, the value the texture object.
  50698. *
  50699. * @type {Object<string,Texture>}
  50700. */
  50701. this.defaultTexture = {};
  50702. /**
  50703. * A dictionary for managing default cube textures. The key
  50704. * is the texture format, the value the texture object.
  50705. *
  50706. * @type {Object<string,CubeTexture>}
  50707. */
  50708. this.defaultCubeTexture = {};
  50709. /**
  50710. * A default video frame.
  50711. *
  50712. * @type {?VideoFrame}
  50713. * @default null
  50714. */
  50715. this.defaultVideoFrame = null;
  50716. /**
  50717. * A cache of shared texture samplers.
  50718. *
  50719. * @type {Map<string, Object>}
  50720. */
  50721. this._samplerCache = new Map();
  50722. }
  50723. /**
  50724. * Creates a GPU sampler for the given texture.
  50725. *
  50726. * @param {Texture} texture - The texture to create the sampler for.
  50727. * @return {string} The current sampler key.
  50728. */
  50729. updateSampler( texture ) {
  50730. const backend = this.backend;
  50731. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  50732. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  50733. texture.anisotropy + '-' + ( texture.compareFunction || 0 );
  50734. let samplerData = this._samplerCache.get( samplerKey );
  50735. if ( samplerData === undefined ) {
  50736. const samplerDescriptorGPU = {
  50737. addressModeU: this._convertAddressMode( texture.wrapS ),
  50738. addressModeV: this._convertAddressMode( texture.wrapT ),
  50739. addressModeW: this._convertAddressMode( texture.wrapR ),
  50740. magFilter: this._convertFilterMode( texture.magFilter ),
  50741. minFilter: this._convertFilterMode( texture.minFilter ),
  50742. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  50743. maxAnisotropy: 1
  50744. };
  50745. // anisotropy can only be used when all filter modes are set to linear.
  50746. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  50747. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  50748. }
  50749. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  50750. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  50751. }
  50752. const sampler = backend.device.createSampler( samplerDescriptorGPU );
  50753. samplerData = { sampler, usedTimes: 0 };
  50754. this._samplerCache.set( samplerKey, samplerData );
  50755. }
  50756. const textureData = backend.get( texture );
  50757. if ( textureData.sampler !== samplerData.sampler ) {
  50758. // check if previous sampler is unused so it can be deleted
  50759. if ( textureData.sampler !== undefined ) {
  50760. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  50761. oldSamplerData.usedTimes --;
  50762. if ( oldSamplerData.usedTimes === 0 ) {
  50763. this._samplerCache.delete( textureData.samplerKey );
  50764. }
  50765. }
  50766. // update to new sampler data
  50767. textureData.samplerKey = samplerKey;
  50768. textureData.sampler = samplerData.sampler;
  50769. samplerData.usedTimes ++;
  50770. }
  50771. return samplerKey;
  50772. }
  50773. /**
  50774. * Creates a default texture for the given texture that can be used
  50775. * as a placeholder until the actual texture is ready for usage.
  50776. *
  50777. * @param {Texture} texture - The texture to create a default texture for.
  50778. */
  50779. createDefaultTexture( texture ) {
  50780. let textureGPU;
  50781. const format = getFormat( texture );
  50782. if ( texture.isCubeTexture ) {
  50783. textureGPU = this._getDefaultCubeTextureGPU( format );
  50784. } else {
  50785. textureGPU = this._getDefaultTextureGPU( format );
  50786. }
  50787. this.backend.get( texture ).texture = textureGPU;
  50788. }
  50789. /**
  50790. * Defines a texture on the GPU for the given texture object.
  50791. *
  50792. * @param {Texture} texture - The texture.
  50793. * @param {Object} [options={}] - Optional configuration parameter.
  50794. */
  50795. createTexture( texture, options = {} ) {
  50796. const backend = this.backend;
  50797. const textureData = backend.get( texture );
  50798. if ( textureData.initialized ) {
  50799. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  50800. }
  50801. if ( texture.isExternalTexture ) {
  50802. textureData.texture = texture.sourceTexture;
  50803. textureData.initialized = true;
  50804. return;
  50805. }
  50806. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  50807. if ( options.levels === undefined ) options.levels = 1;
  50808. if ( options.depth === undefined ) options.depth = 1;
  50809. const { width, height, depth, levels } = options;
  50810. if ( texture.isFramebufferTexture ) {
  50811. if ( options.renderTarget ) {
  50812. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  50813. } else {
  50814. options.format = this.backend.utils.getPreferredCanvasFormat();
  50815. }
  50816. }
  50817. const dimension = this._getDimension( texture );
  50818. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  50819. textureData.format = format;
  50820. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  50821. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  50822. if ( texture.isStorageTexture === true ) {
  50823. usage |= GPUTextureUsage.STORAGE_BINDING;
  50824. }
  50825. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  50826. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  50827. }
  50828. const textureDescriptorGPU = {
  50829. label: texture.name,
  50830. size: {
  50831. width: width,
  50832. height: height,
  50833. depthOrArrayLayers: depth,
  50834. },
  50835. mipLevelCount: levels,
  50836. sampleCount: primarySamples,
  50837. dimension: dimension,
  50838. format: format,
  50839. usage: usage
  50840. };
  50841. // texture creation
  50842. if ( format === undefined ) {
  50843. warn( 'WebGPURenderer: Texture format not supported.' );
  50844. this.createDefaultTexture( texture );
  50845. return;
  50846. }
  50847. if ( texture.isCubeTexture ) {
  50848. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  50849. }
  50850. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  50851. if ( isMSAA ) {
  50852. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  50853. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  50854. msaaTextureDescriptorGPU.sampleCount = samples;
  50855. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  50856. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  50857. }
  50858. textureData.initialized = true;
  50859. textureData.textureDescriptorGPU = textureDescriptorGPU;
  50860. }
  50861. /**
  50862. * Destroys the GPU data for the given texture object.
  50863. *
  50864. * @param {Texture} texture - The texture.
  50865. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  50866. */
  50867. destroyTexture( texture, isDefaultTexture = false ) {
  50868. const backend = this.backend;
  50869. const textureData = backend.get( texture );
  50870. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  50871. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  50872. backend.delete( texture );
  50873. }
  50874. /**
  50875. * Generates mipmaps for the given texture.
  50876. *
  50877. * @param {Texture} texture - The texture.
  50878. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  50879. */
  50880. generateMipmaps( texture, encoder = null ) {
  50881. const textureData = this.backend.get( texture );
  50882. if ( texture.isCubeTexture ) {
  50883. for ( let i = 0; i < 6; i ++ ) {
  50884. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  50885. }
  50886. } else {
  50887. const depth = texture.image.depth || 1;
  50888. for ( let i = 0; i < depth; i ++ ) {
  50889. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  50890. }
  50891. }
  50892. }
  50893. /**
  50894. * Returns the color buffer representing the color
  50895. * attachment of the default framebuffer.
  50896. *
  50897. * @return {GPUTexture} The color buffer.
  50898. */
  50899. getColorBuffer() {
  50900. const backend = this.backend;
  50901. const canvasTarget = backend.renderer.getCanvasTarget();
  50902. const { width, height } = backend.getDrawingBufferSize();
  50903. const samples = backend.renderer.currentSamples;
  50904. const colorTexture = canvasTarget.colorTexture;
  50905. const colorTextureData = backend.get( colorTexture );
  50906. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  50907. return colorTextureData.texture;
  50908. }
  50909. // recreate
  50910. let colorBuffer = colorTextureData.texture;
  50911. if ( colorBuffer ) colorBuffer.destroy();
  50912. colorBuffer = backend.device.createTexture( {
  50913. label: 'colorBuffer',
  50914. size: {
  50915. width: width,
  50916. height: height,
  50917. depthOrArrayLayers: 1
  50918. },
  50919. sampleCount: backend.utils.getSampleCount( backend.renderer.currentSamples ),
  50920. format: backend.utils.getPreferredCanvasFormat(),
  50921. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  50922. } );
  50923. //
  50924. colorTexture.source.width = width;
  50925. colorTexture.source.height = height;
  50926. colorTexture.samples = samples;
  50927. colorTextureData.texture = colorBuffer;
  50928. return colorBuffer;
  50929. }
  50930. /**
  50931. * Returns the depth buffer representing the depth
  50932. * attachment of the default framebuffer.
  50933. *
  50934. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  50935. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  50936. * @return {GPUTexture} The depth buffer.
  50937. */
  50938. getDepthBuffer( depth = true, stencil = false ) {
  50939. const backend = this.backend;
  50940. const canvasTarget = backend.renderer.getCanvasTarget();
  50941. const { width, height } = backend.getDrawingBufferSize();
  50942. const samples = backend.renderer.currentSamples;
  50943. const depthTexture = canvasTarget.depthTexture;
  50944. if ( depthTexture.width === width &&
  50945. depthTexture.height === height &&
  50946. depthTexture.samples === samples &&
  50947. depthTexture.depth === depth &&
  50948. depthTexture.stencil === stencil ) {
  50949. return backend.get( depthTexture ).texture;
  50950. }
  50951. //
  50952. const depthTextureGPU = backend.get( depthTexture ).texture;
  50953. let format, type;
  50954. if ( stencil ) {
  50955. format = DepthStencilFormat;
  50956. type = UnsignedInt248Type;
  50957. } else if ( depth ) {
  50958. format = DepthFormat;
  50959. type = UnsignedIntType;
  50960. }
  50961. if ( depthTextureGPU !== undefined ) {
  50962. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  50963. return depthTextureGPU;
  50964. }
  50965. this.destroyTexture( depthTexture );
  50966. }
  50967. // recreate
  50968. depthTexture.name = 'depthBuffer';
  50969. depthTexture.format = format;
  50970. depthTexture.type = type;
  50971. depthTexture.image.width = width;
  50972. depthTexture.image.height = height;
  50973. depthTexture.samples = samples;
  50974. this.createTexture( depthTexture, { width, height } );
  50975. return backend.get( depthTexture ).texture;
  50976. }
  50977. /**
  50978. * Uploads the updated texture data to the GPU.
  50979. *
  50980. * @param {Texture} texture - The texture.
  50981. * @param {Object} [options={}] - Optional configuration parameter.
  50982. */
  50983. updateTexture( texture, options ) {
  50984. const textureData = this.backend.get( texture );
  50985. const mipmaps = texture.mipmaps;
  50986. const { textureDescriptorGPU } = textureData;
  50987. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  50988. return;
  50989. // transfer texture data
  50990. if ( texture.isDataTexture ) {
  50991. if ( mipmaps.length > 0 ) {
  50992. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50993. const mipmap = mipmaps[ i ];
  50994. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  50995. }
  50996. } else {
  50997. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  50998. }
  50999. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  51000. for ( let i = 0; i < options.image.depth; i ++ ) {
  51001. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  51002. }
  51003. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  51004. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  51005. } else if ( texture.isCubeTexture ) {
  51006. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  51007. } else {
  51008. if ( mipmaps.length > 0 ) {
  51009. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  51010. const mipmap = mipmaps[ i ];
  51011. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  51012. }
  51013. } else {
  51014. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  51015. }
  51016. }
  51017. //
  51018. textureData.version = texture.version;
  51019. }
  51020. /**
  51021. * Returns texture data as a typed array.
  51022. *
  51023. * @async
  51024. * @param {Texture} texture - The texture to copy.
  51025. * @param {number} x - The x coordinate of the copy origin.
  51026. * @param {number} y - The y coordinate of the copy origin.
  51027. * @param {number} width - The width of the copy.
  51028. * @param {number} height - The height of the copy.
  51029. * @param {number} faceIndex - The face index.
  51030. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  51031. */
  51032. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  51033. const device = this.backend.device;
  51034. const textureData = this.backend.get( texture );
  51035. const textureGPU = textureData.texture;
  51036. const format = textureData.textureDescriptorGPU.format;
  51037. const bytesPerTexel = this._getBytesPerTexel( format );
  51038. let bytesPerRow = width * bytesPerTexel;
  51039. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  51040. const readBuffer = device.createBuffer(
  51041. {
  51042. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  51043. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  51044. }
  51045. );
  51046. const encoder = device.createCommandEncoder();
  51047. encoder.copyTextureToBuffer(
  51048. {
  51049. texture: textureGPU,
  51050. origin: { x, y, z: faceIndex },
  51051. },
  51052. {
  51053. buffer: readBuffer,
  51054. bytesPerRow: bytesPerRow
  51055. },
  51056. {
  51057. width: width,
  51058. height: height
  51059. }
  51060. );
  51061. const typedArrayType = this._getTypedArrayType( format );
  51062. device.queue.submit( [ encoder.finish() ] );
  51063. await readBuffer.mapAsync( GPUMapMode.READ );
  51064. const buffer = readBuffer.getMappedRange();
  51065. return new typedArrayType( buffer );
  51066. }
  51067. /**
  51068. * Frees all internal resources.
  51069. */
  51070. dispose() {
  51071. this._samplerCache.clear();
  51072. }
  51073. /**
  51074. * Returns the default GPU texture for the given format.
  51075. *
  51076. * @private
  51077. * @param {string} format - The GPU format.
  51078. * @return {GPUTexture} The GPU texture.
  51079. */
  51080. _getDefaultTextureGPU( format ) {
  51081. let defaultTexture = this.defaultTexture[ format ];
  51082. if ( defaultTexture === undefined ) {
  51083. const texture = new Texture();
  51084. texture.minFilter = NearestFilter;
  51085. texture.magFilter = NearestFilter;
  51086. this.createTexture( texture, { width: 1, height: 1, format } );
  51087. this.defaultTexture[ format ] = defaultTexture = texture;
  51088. }
  51089. return this.backend.get( defaultTexture ).texture;
  51090. }
  51091. /**
  51092. * Returns the default GPU cube texture for the given format.
  51093. *
  51094. * @private
  51095. * @param {string} format - The GPU format.
  51096. * @return {GPUTexture} The GPU texture.
  51097. */
  51098. _getDefaultCubeTextureGPU( format ) {
  51099. let defaultCubeTexture = this.defaultTexture[ format ];
  51100. if ( defaultCubeTexture === undefined ) {
  51101. const texture = new CubeTexture();
  51102. texture.minFilter = NearestFilter;
  51103. texture.magFilter = NearestFilter;
  51104. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  51105. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  51106. }
  51107. return this.backend.get( defaultCubeTexture ).texture;
  51108. }
  51109. /**
  51110. * Uploads cube texture image data to the GPU memory.
  51111. *
  51112. * @private
  51113. * @param {CubeTexture} texture - The cube texture.
  51114. * @param {GPUTexture} textureGPU - The GPU texture.
  51115. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51116. */
  51117. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  51118. const images = texture.images;
  51119. const mipmaps = texture.mipmaps;
  51120. for ( let i = 0; i < 6; i ++ ) {
  51121. const image = images[ i ];
  51122. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  51123. if ( image.isDataTexture ) {
  51124. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  51125. } else {
  51126. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  51127. }
  51128. for ( let j = 0; j < mipmaps.length; j ++ ) {
  51129. const mipmap = mipmaps[ j ];
  51130. const image = mipmap.images[ i ];
  51131. if ( image.isDataTexture ) {
  51132. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  51133. } else {
  51134. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  51135. }
  51136. }
  51137. }
  51138. }
  51139. /**
  51140. * Uploads texture image data to the GPU memory.
  51141. *
  51142. * @private
  51143. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  51144. * @param {GPUTexture} textureGPU - The GPU texture.
  51145. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51146. * @param {number} originDepth - The origin depth.
  51147. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  51148. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  51149. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  51150. */
  51151. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  51152. const device = this.backend.device;
  51153. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  51154. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  51155. device.queue.copyExternalImageToTexture(
  51156. {
  51157. source: image,
  51158. flipY: flipY
  51159. }, {
  51160. texture: textureGPU,
  51161. mipLevel: mipLevel,
  51162. origin: { x: 0, y: 0, z: originDepth },
  51163. premultipliedAlpha: premultiplyAlpha
  51164. }, {
  51165. width: width,
  51166. height: height,
  51167. depthOrArrayLayers: 1
  51168. }
  51169. );
  51170. }
  51171. /**
  51172. * Returns the pass utils singleton.
  51173. *
  51174. * @private
  51175. * @return {WebGPUTexturePassUtils} The utils instance.
  51176. */
  51177. _getPassUtils() {
  51178. let passUtils = this._passUtils;
  51179. if ( passUtils === null ) {
  51180. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  51181. }
  51182. return passUtils;
  51183. }
  51184. /**
  51185. * Generates mipmaps for the given GPU texture.
  51186. *
  51187. * @private
  51188. * @param {GPUTexture} textureGPU - The GPU texture object.
  51189. * @param {Object} textureDescriptorGPU - The texture descriptor.
  51190. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  51191. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  51192. */
  51193. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0, encoder = null ) {
  51194. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer, encoder );
  51195. }
  51196. /**
  51197. * Flip the contents of the given GPU texture along its vertical axis.
  51198. *
  51199. * @private
  51200. * @param {GPUTexture} textureGPU - The GPU texture object.
  51201. * @param {Object} textureDescriptorGPU - The texture descriptor.
  51202. * @param {number} [originDepth=0] - The origin depth.
  51203. */
  51204. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  51205. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  51206. }
  51207. /**
  51208. * Uploads texture buffer data to the GPU memory.
  51209. *
  51210. * @private
  51211. * @param {Object} image - An object defining the image buffer data.
  51212. * @param {GPUTexture} textureGPU - The GPU texture.
  51213. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51214. * @param {number} originDepth - The origin depth.
  51215. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  51216. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  51217. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  51218. */
  51219. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  51220. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  51221. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  51222. const device = this.backend.device;
  51223. const data = image.data;
  51224. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  51225. const bytesPerRow = image.width * bytesPerTexel;
  51226. device.queue.writeTexture(
  51227. {
  51228. texture: textureGPU,
  51229. mipLevel: mipLevel,
  51230. origin: { x: 0, y: 0, z: originDepth }
  51231. },
  51232. data,
  51233. {
  51234. offset: image.width * image.height * bytesPerTexel * depth,
  51235. bytesPerRow
  51236. },
  51237. {
  51238. width: image.width,
  51239. height: image.height,
  51240. depthOrArrayLayers: 1
  51241. } );
  51242. if ( flipY === true ) {
  51243. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  51244. }
  51245. }
  51246. /**
  51247. * Uploads compressed texture data to the GPU memory.
  51248. *
  51249. * @private
  51250. * @param {Array<Object>} mipmaps - An array with mipmap data.
  51251. * @param {GPUTexture} textureGPU - The GPU texture.
  51252. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51253. */
  51254. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  51255. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  51256. const device = this.backend.device;
  51257. const blockData = this._getBlockData( textureDescriptorGPU.format );
  51258. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  51259. for ( let i = 0; i < mipmaps.length; i ++ ) {
  51260. const mipmap = mipmaps[ i ];
  51261. const width = mipmap.width;
  51262. const height = mipmap.height;
  51263. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  51264. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  51265. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  51266. for ( let j = 0; j < depth; j ++ ) {
  51267. device.queue.writeTexture(
  51268. {
  51269. texture: textureGPU,
  51270. mipLevel: i,
  51271. origin: { x: 0, y: 0, z: j }
  51272. },
  51273. mipmap.data,
  51274. {
  51275. offset: j * bytesPerImage,
  51276. bytesPerRow,
  51277. rowsPerImage: Math.ceil( height / blockData.height )
  51278. },
  51279. {
  51280. width: Math.ceil( width / blockData.width ) * blockData.width,
  51281. height: Math.ceil( height / blockData.height ) * blockData.height,
  51282. depthOrArrayLayers: 1
  51283. }
  51284. );
  51285. }
  51286. }
  51287. }
  51288. /**
  51289. * This method is only relevant for compressed texture formats. It returns a block
  51290. * data descriptor for the given GPU compressed texture format.
  51291. *
  51292. * @private
  51293. * @param {string} format - The GPU compressed texture format.
  51294. * @return {Object} The block data descriptor.
  51295. */
  51296. _getBlockData( format ) {
  51297. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  51298. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  51299. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  51300. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  51301. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  51302. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  51303. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  51304. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  51305. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  51306. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  51307. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  51308. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  51309. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  51310. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  51311. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  51312. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  51313. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  51314. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  51315. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  51316. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  51317. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  51318. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  51319. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  51320. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  51321. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  51322. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  51323. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  51324. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  51325. }
  51326. /**
  51327. * Converts the three.js uv wrapping constants to GPU address mode constants.
  51328. *
  51329. * @private
  51330. * @param {number} value - The three.js constant defining a uv wrapping mode.
  51331. * @return {string} The GPU address mode.
  51332. */
  51333. _convertAddressMode( value ) {
  51334. let addressMode = GPUAddressMode.ClampToEdge;
  51335. if ( value === RepeatWrapping ) {
  51336. addressMode = GPUAddressMode.Repeat;
  51337. } else if ( value === MirroredRepeatWrapping ) {
  51338. addressMode = GPUAddressMode.MirrorRepeat;
  51339. }
  51340. return addressMode;
  51341. }
  51342. /**
  51343. * Converts the three.js filter constants to GPU filter constants.
  51344. *
  51345. * @private
  51346. * @param {number} value - The three.js constant defining a filter mode.
  51347. * @return {string} The GPU filter mode.
  51348. */
  51349. _convertFilterMode( value ) {
  51350. let filterMode = GPUFilterMode.Linear;
  51351. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  51352. filterMode = GPUFilterMode.Nearest;
  51353. }
  51354. return filterMode;
  51355. }
  51356. /**
  51357. * Returns the bytes-per-texel value for the given GPU texture format.
  51358. *
  51359. * @private
  51360. * @param {string} format - The GPU texture format.
  51361. * @return {number} The bytes-per-texel.
  51362. */
  51363. _getBytesPerTexel( format ) {
  51364. // 8-bit formats
  51365. if ( format === GPUTextureFormat.R8Unorm ||
  51366. format === GPUTextureFormat.R8Snorm ||
  51367. format === GPUTextureFormat.R8Uint ||
  51368. format === GPUTextureFormat.R8Sint ) return 1;
  51369. // 16-bit formats
  51370. if ( format === GPUTextureFormat.R16Uint ||
  51371. format === GPUTextureFormat.R16Sint ||
  51372. format === GPUTextureFormat.R16Float ||
  51373. format === GPUTextureFormat.RG8Unorm ||
  51374. format === GPUTextureFormat.RG8Snorm ||
  51375. format === GPUTextureFormat.RG8Uint ||
  51376. format === GPUTextureFormat.RG8Sint ) return 2;
  51377. // 32-bit formats
  51378. if ( format === GPUTextureFormat.R32Uint ||
  51379. format === GPUTextureFormat.R32Sint ||
  51380. format === GPUTextureFormat.R32Float ||
  51381. format === GPUTextureFormat.RG16Uint ||
  51382. format === GPUTextureFormat.RG16Sint ||
  51383. format === GPUTextureFormat.RG16Float ||
  51384. format === GPUTextureFormat.RGBA8Unorm ||
  51385. format === GPUTextureFormat.RGBA8UnormSRGB ||
  51386. format === GPUTextureFormat.RGBA8Snorm ||
  51387. format === GPUTextureFormat.RGBA8Uint ||
  51388. format === GPUTextureFormat.RGBA8Sint ||
  51389. format === GPUTextureFormat.BGRA8Unorm ||
  51390. format === GPUTextureFormat.BGRA8UnormSRGB ||
  51391. // Packed 32-bit formats
  51392. format === GPUTextureFormat.RGB9E5UFloat ||
  51393. format === GPUTextureFormat.RGB10A2Unorm ||
  51394. format === GPUTextureFormat.RG11B10UFloat ||
  51395. format === GPUTextureFormat.Depth32Float ||
  51396. format === GPUTextureFormat.Depth24Plus ||
  51397. format === GPUTextureFormat.Depth24PlusStencil8 ||
  51398. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  51399. // 64-bit formats
  51400. if ( format === GPUTextureFormat.RG32Uint ||
  51401. format === GPUTextureFormat.RG32Sint ||
  51402. format === GPUTextureFormat.RG32Float ||
  51403. format === GPUTextureFormat.RGBA16Uint ||
  51404. format === GPUTextureFormat.RGBA16Sint ||
  51405. format === GPUTextureFormat.RGBA16Float ) return 8;
  51406. // 128-bit formats
  51407. if ( format === GPUTextureFormat.RGBA32Uint ||
  51408. format === GPUTextureFormat.RGBA32Sint ||
  51409. format === GPUTextureFormat.RGBA32Float ) return 16;
  51410. }
  51411. /**
  51412. * Returns the corresponding typed array type for the given GPU texture format.
  51413. *
  51414. * @private
  51415. * @param {string} format - The GPU texture format.
  51416. * @return {TypedArray.constructor} The typed array type.
  51417. */
  51418. _getTypedArrayType( format ) {
  51419. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  51420. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  51421. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  51422. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  51423. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  51424. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  51425. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  51426. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  51427. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  51428. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  51429. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  51430. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  51431. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  51432. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  51433. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  51434. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  51435. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  51436. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  51437. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  51438. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  51439. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  51440. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  51441. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  51442. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  51443. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  51444. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  51445. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  51446. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  51447. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  51448. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  51449. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  51450. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  51451. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  51452. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  51453. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  51454. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  51455. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  51456. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  51457. }
  51458. /**
  51459. * Returns the GPU dimensions for the given texture.
  51460. *
  51461. * @private
  51462. * @param {Texture} texture - The texture.
  51463. * @return {string} The GPU dimension.
  51464. */
  51465. _getDimension( texture ) {
  51466. let dimension;
  51467. if ( texture.is3DTexture || texture.isData3DTexture ) {
  51468. dimension = GPUTextureDimension.ThreeD;
  51469. } else {
  51470. dimension = GPUTextureDimension.TwoD;
  51471. }
  51472. return dimension;
  51473. }
  51474. }
  51475. /**
  51476. * Returns the GPU format for the given texture.
  51477. *
  51478. * @param {Texture} texture - The texture.
  51479. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  51480. * It is not necessary to apply the device for most formats.
  51481. * @return {string} The GPU format.
  51482. */
  51483. function getFormat( texture, device = null ) {
  51484. const format = texture.format;
  51485. const type = texture.type;
  51486. const colorSpace = texture.colorSpace;
  51487. const transfer = ColorManagement.getTransfer( colorSpace );
  51488. let formatGPU;
  51489. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  51490. switch ( format ) {
  51491. case RGB_S3TC_DXT1_Format:
  51492. case RGBA_S3TC_DXT1_Format:
  51493. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  51494. break;
  51495. case RGBA_S3TC_DXT3_Format:
  51496. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  51497. break;
  51498. case RGBA_S3TC_DXT5_Format:
  51499. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  51500. break;
  51501. case RED_RGTC1_Format:
  51502. formatGPU = GPUTextureFormat.BC4RUnorm;
  51503. break;
  51504. case SIGNED_RED_RGTC1_Format:
  51505. formatGPU = GPUTextureFormat.BC4RSnorm;
  51506. break;
  51507. case RED_GREEN_RGTC2_Format:
  51508. formatGPU = GPUTextureFormat.BC5RGUnorm;
  51509. break;
  51510. case SIGNED_RED_GREEN_RGTC2_Format:
  51511. formatGPU = GPUTextureFormat.BC5RGSnorm;
  51512. break;
  51513. case RGBA_BPTC_Format:
  51514. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  51515. break;
  51516. case RGB_ETC2_Format:
  51517. case RGB_ETC1_Format:
  51518. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  51519. break;
  51520. case RGBA_ETC2_EAC_Format:
  51521. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  51522. break;
  51523. case R11_EAC_Format:
  51524. formatGPU = GPUTextureFormat.EACR11Unorm;
  51525. break;
  51526. case SIGNED_R11_EAC_Format:
  51527. formatGPU = GPUTextureFormat.EACR11Snorm;
  51528. break;
  51529. case RG11_EAC_Format:
  51530. formatGPU = GPUTextureFormat.EACRG11Unorm;
  51531. break;
  51532. case SIGNED_RG11_EAC_Format:
  51533. formatGPU = GPUTextureFormat.EACRG11Snorm;
  51534. break;
  51535. case RGBA_ASTC_4x4_Format:
  51536. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  51537. break;
  51538. case RGBA_ASTC_5x4_Format:
  51539. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  51540. break;
  51541. case RGBA_ASTC_5x5_Format:
  51542. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  51543. break;
  51544. case RGBA_ASTC_6x5_Format:
  51545. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  51546. break;
  51547. case RGBA_ASTC_6x6_Format:
  51548. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  51549. break;
  51550. case RGBA_ASTC_8x5_Format:
  51551. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  51552. break;
  51553. case RGBA_ASTC_8x6_Format:
  51554. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  51555. break;
  51556. case RGBA_ASTC_8x8_Format:
  51557. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  51558. break;
  51559. case RGBA_ASTC_10x5_Format:
  51560. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  51561. break;
  51562. case RGBA_ASTC_10x6_Format:
  51563. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  51564. break;
  51565. case RGBA_ASTC_10x8_Format:
  51566. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  51567. break;
  51568. case RGBA_ASTC_10x10_Format:
  51569. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  51570. break;
  51571. case RGBA_ASTC_12x10_Format:
  51572. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  51573. break;
  51574. case RGBA_ASTC_12x12_Format:
  51575. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  51576. break;
  51577. case RGBAFormat:
  51578. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  51579. break;
  51580. default:
  51581. error( 'WebGPURenderer: Unsupported texture format.', format );
  51582. }
  51583. } else {
  51584. switch ( format ) {
  51585. case RGBAFormat:
  51586. switch ( type ) {
  51587. case ByteType:
  51588. formatGPU = GPUTextureFormat.RGBA8Snorm;
  51589. break;
  51590. case ShortType:
  51591. formatGPU = GPUTextureFormat.RGBA16Sint;
  51592. break;
  51593. case UnsignedShortType:
  51594. formatGPU = GPUTextureFormat.RGBA16Uint;
  51595. break;
  51596. case UnsignedIntType:
  51597. formatGPU = GPUTextureFormat.RGBA32Uint;
  51598. break;
  51599. case IntType:
  51600. formatGPU = GPUTextureFormat.RGBA32Sint;
  51601. break;
  51602. case UnsignedByteType:
  51603. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  51604. break;
  51605. case HalfFloatType:
  51606. formatGPU = GPUTextureFormat.RGBA16Float;
  51607. break;
  51608. case FloatType:
  51609. formatGPU = GPUTextureFormat.RGBA32Float;
  51610. break;
  51611. default:
  51612. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  51613. }
  51614. break;
  51615. case RGBFormat:
  51616. switch ( type ) {
  51617. case UnsignedInt5999Type:
  51618. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  51619. break;
  51620. case UnsignedInt101111Type:
  51621. formatGPU = GPUTextureFormat.RG11B10UFloat;
  51622. break;
  51623. default:
  51624. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  51625. }
  51626. break;
  51627. case RedFormat:
  51628. switch ( type ) {
  51629. case ByteType:
  51630. formatGPU = GPUTextureFormat.R8Snorm;
  51631. break;
  51632. case ShortType:
  51633. formatGPU = GPUTextureFormat.R16Sint;
  51634. break;
  51635. case UnsignedShortType:
  51636. formatGPU = GPUTextureFormat.R16Uint;
  51637. break;
  51638. case UnsignedIntType:
  51639. formatGPU = GPUTextureFormat.R32Uint;
  51640. break;
  51641. case IntType:
  51642. formatGPU = GPUTextureFormat.R32Sint;
  51643. break;
  51644. case UnsignedByteType:
  51645. formatGPU = GPUTextureFormat.R8Unorm;
  51646. break;
  51647. case HalfFloatType:
  51648. formatGPU = GPUTextureFormat.R16Float;
  51649. break;
  51650. case FloatType:
  51651. formatGPU = GPUTextureFormat.R32Float;
  51652. break;
  51653. default:
  51654. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  51655. }
  51656. break;
  51657. case RGFormat:
  51658. switch ( type ) {
  51659. case ByteType:
  51660. formatGPU = GPUTextureFormat.RG8Snorm;
  51661. break;
  51662. case ShortType:
  51663. formatGPU = GPUTextureFormat.RG16Sint;
  51664. break;
  51665. case UnsignedShortType:
  51666. formatGPU = GPUTextureFormat.RG16Uint;
  51667. break;
  51668. case UnsignedIntType:
  51669. formatGPU = GPUTextureFormat.RG32Uint;
  51670. break;
  51671. case IntType:
  51672. formatGPU = GPUTextureFormat.RG32Sint;
  51673. break;
  51674. case UnsignedByteType:
  51675. formatGPU = GPUTextureFormat.RG8Unorm;
  51676. break;
  51677. case HalfFloatType:
  51678. formatGPU = GPUTextureFormat.RG16Float;
  51679. break;
  51680. case FloatType:
  51681. formatGPU = GPUTextureFormat.RG32Float;
  51682. break;
  51683. default:
  51684. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  51685. }
  51686. break;
  51687. case DepthFormat:
  51688. switch ( type ) {
  51689. case UnsignedShortType:
  51690. formatGPU = GPUTextureFormat.Depth16Unorm;
  51691. break;
  51692. case UnsignedIntType:
  51693. formatGPU = GPUTextureFormat.Depth24Plus;
  51694. break;
  51695. case FloatType:
  51696. formatGPU = GPUTextureFormat.Depth32Float;
  51697. break;
  51698. default:
  51699. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  51700. }
  51701. break;
  51702. case DepthStencilFormat:
  51703. switch ( type ) {
  51704. case UnsignedInt248Type:
  51705. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  51706. break;
  51707. case FloatType:
  51708. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  51709. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  51710. }
  51711. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  51712. break;
  51713. default:
  51714. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  51715. }
  51716. break;
  51717. case RedIntegerFormat:
  51718. switch ( type ) {
  51719. case IntType:
  51720. formatGPU = GPUTextureFormat.R32Sint;
  51721. break;
  51722. case UnsignedIntType:
  51723. formatGPU = GPUTextureFormat.R32Uint;
  51724. break;
  51725. default:
  51726. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  51727. }
  51728. break;
  51729. case RGIntegerFormat:
  51730. switch ( type ) {
  51731. case IntType:
  51732. formatGPU = GPUTextureFormat.RG32Sint;
  51733. break;
  51734. case UnsignedIntType:
  51735. formatGPU = GPUTextureFormat.RG32Uint;
  51736. break;
  51737. default:
  51738. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  51739. }
  51740. break;
  51741. case RGBAIntegerFormat:
  51742. switch ( type ) {
  51743. case IntType:
  51744. formatGPU = GPUTextureFormat.RGBA32Sint;
  51745. break;
  51746. case UnsignedIntType:
  51747. formatGPU = GPUTextureFormat.RGBA32Uint;
  51748. break;
  51749. default:
  51750. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  51751. }
  51752. break;
  51753. default:
  51754. error( 'WebGPURenderer: Unsupported texture format.', format );
  51755. }
  51756. }
  51757. return formatGPU;
  51758. }
  51759. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  51760. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  51761. const wgslTypeLib$1 = {
  51762. 'f32': 'float',
  51763. 'i32': 'int',
  51764. 'u32': 'uint',
  51765. 'bool': 'bool',
  51766. 'vec2<f32>': 'vec2',
  51767. 'vec2<i32>': 'ivec2',
  51768. 'vec2<u32>': 'uvec2',
  51769. 'vec2<bool>': 'bvec2',
  51770. 'vec2f': 'vec2',
  51771. 'vec2i': 'ivec2',
  51772. 'vec2u': 'uvec2',
  51773. 'vec2b': 'bvec2',
  51774. 'vec3<f32>': 'vec3',
  51775. 'vec3<i32>': 'ivec3',
  51776. 'vec3<u32>': 'uvec3',
  51777. 'vec3<bool>': 'bvec3',
  51778. 'vec3f': 'vec3',
  51779. 'vec3i': 'ivec3',
  51780. 'vec3u': 'uvec3',
  51781. 'vec3b': 'bvec3',
  51782. 'vec4<f32>': 'vec4',
  51783. 'vec4<i32>': 'ivec4',
  51784. 'vec4<u32>': 'uvec4',
  51785. 'vec4<bool>': 'bvec4',
  51786. 'vec4f': 'vec4',
  51787. 'vec4i': 'ivec4',
  51788. 'vec4u': 'uvec4',
  51789. 'vec4b': 'bvec4',
  51790. 'mat2x2<f32>': 'mat2',
  51791. 'mat2x2f': 'mat2',
  51792. 'mat3x3<f32>': 'mat3',
  51793. 'mat3x3f': 'mat3',
  51794. 'mat4x4<f32>': 'mat4',
  51795. 'mat4x4f': 'mat4',
  51796. 'sampler': 'sampler',
  51797. 'texture_1d': 'texture',
  51798. 'texture_2d': 'texture',
  51799. 'texture_2d_array': 'texture',
  51800. 'texture_multisampled_2d': 'cubeTexture',
  51801. 'texture_depth_2d': 'depthTexture',
  51802. 'texture_depth_2d_array': 'depthTexture',
  51803. 'texture_depth_multisampled_2d': 'depthTexture',
  51804. 'texture_depth_cube': 'depthTexture',
  51805. 'texture_depth_cube_array': 'depthTexture',
  51806. 'texture_3d': 'texture3D',
  51807. 'texture_cube': 'cubeTexture',
  51808. 'texture_cube_array': 'cubeTexture',
  51809. 'texture_storage_1d': 'storageTexture',
  51810. 'texture_storage_2d': 'storageTexture',
  51811. 'texture_storage_2d_array': 'storageTexture',
  51812. 'texture_storage_3d': 'storageTexture'
  51813. };
  51814. const parse = ( source ) => {
  51815. source = source.trim();
  51816. const declaration = source.match( declarationRegexp );
  51817. if ( declaration !== null && declaration.length === 4 ) {
  51818. const inputsCode = declaration[ 2 ];
  51819. const propsMatches = [];
  51820. let match = null;
  51821. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  51822. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  51823. }
  51824. // Process matches to correctly pair names and types
  51825. const inputs = [];
  51826. for ( let i = 0; i < propsMatches.length; i ++ ) {
  51827. const { name, type } = propsMatches[ i ];
  51828. let resolvedType = type;
  51829. if ( resolvedType.startsWith( 'ptr' ) ) {
  51830. resolvedType = 'pointer';
  51831. } else {
  51832. if ( resolvedType.startsWith( 'texture' ) ) {
  51833. resolvedType = type.split( '<' )[ 0 ];
  51834. }
  51835. resolvedType = wgslTypeLib$1[ resolvedType ];
  51836. }
  51837. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  51838. }
  51839. const blockCode = source.substring( declaration[ 0 ].length );
  51840. const outputType = declaration[ 3 ] || 'void';
  51841. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  51842. const type = wgslTypeLib$1[ outputType ] || outputType;
  51843. return {
  51844. type,
  51845. inputs,
  51846. name,
  51847. inputsCode,
  51848. blockCode,
  51849. outputType
  51850. };
  51851. } else {
  51852. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  51853. }
  51854. };
  51855. /**
  51856. * This class represents a WSL node function.
  51857. *
  51858. * @augments NodeFunction
  51859. */
  51860. class WGSLNodeFunction extends NodeFunction {
  51861. /**
  51862. * Constructs a new WGSL node function.
  51863. *
  51864. * @param {string} source - The WGSL source.
  51865. */
  51866. constructor( source ) {
  51867. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  51868. super( type, inputs, name );
  51869. this.inputsCode = inputsCode;
  51870. this.blockCode = blockCode;
  51871. this.outputType = outputType;
  51872. }
  51873. /**
  51874. * This method returns the WGSL code of the node function.
  51875. *
  51876. * @param {string} [name=this.name] - The function's name.
  51877. * @return {string} The shader code.
  51878. */
  51879. getCode( name = this.name ) {
  51880. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  51881. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  51882. }
  51883. }
  51884. /**
  51885. * A WGSL node parser.
  51886. *
  51887. * @augments NodeParser
  51888. */
  51889. class WGSLNodeParser extends NodeParser {
  51890. /**
  51891. * The method parses the given WGSL code an returns a node function.
  51892. *
  51893. * @param {string} source - The WGSL code.
  51894. * @return {WGSLNodeFunction} A node function.
  51895. */
  51896. parseFunction( source ) {
  51897. return new WGSLNodeFunction( source );
  51898. }
  51899. }
  51900. const accessNames = {
  51901. [ NodeAccess.READ_ONLY ]: 'read',
  51902. [ NodeAccess.WRITE_ONLY ]: 'write',
  51903. [ NodeAccess.READ_WRITE ]: 'read_write'
  51904. };
  51905. const wrapNames = {
  51906. [ RepeatWrapping ]: 'repeat',
  51907. [ ClampToEdgeWrapping ]: 'clamp',
  51908. [ MirroredRepeatWrapping ]: 'mirror'
  51909. };
  51910. const gpuShaderStageLib = {
  51911. 'vertex': GPUShaderStage.VERTEX,
  51912. 'fragment': GPUShaderStage.FRAGMENT,
  51913. 'compute': GPUShaderStage.COMPUTE
  51914. };
  51915. const supports = {
  51916. instance: true,
  51917. swizzleAssign: false,
  51918. storageBuffer: true
  51919. };
  51920. const wgslFnOpLib = {
  51921. '^^': 'tsl_xor'
  51922. };
  51923. const wgslTypeLib = {
  51924. float: 'f32',
  51925. int: 'i32',
  51926. uint: 'u32',
  51927. bool: 'bool',
  51928. color: 'vec3<f32>',
  51929. vec2: 'vec2<f32>',
  51930. ivec2: 'vec2<i32>',
  51931. uvec2: 'vec2<u32>',
  51932. bvec2: 'vec2<bool>',
  51933. vec3: 'vec3<f32>',
  51934. ivec3: 'vec3<i32>',
  51935. uvec3: 'vec3<u32>',
  51936. bvec3: 'vec3<bool>',
  51937. vec4: 'vec4<f32>',
  51938. ivec4: 'vec4<i32>',
  51939. uvec4: 'vec4<u32>',
  51940. bvec4: 'vec4<bool>',
  51941. mat2: 'mat2x2<f32>',
  51942. mat3: 'mat3x3<f32>',
  51943. mat4: 'mat4x4<f32>'
  51944. };
  51945. const wgslCodeCache = {};
  51946. const wgslPolyfill = {
  51947. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  51948. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  51949. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  51950. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  51951. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  51952. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  51953. 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 ); }' ),
  51954. 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 ); }' ),
  51955. 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 ); }' ),
  51956. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  51957. 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 ); }' ),
  51958. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  51959. biquadraticTexture: new CodeNode( /* wgsl */`
  51960. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  51961. let res = vec2f( iRes );
  51962. let uvScaled = coord * res;
  51963. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  51964. // https://www.shadertoy.com/view/WtyXRy
  51965. let uv = uvWrapping - 0.5;
  51966. let iuv = floor( uv );
  51967. let f = fract( uv );
  51968. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  51969. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  51970. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  51971. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  51972. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  51973. }
  51974. ` )
  51975. };
  51976. const wgslMethods = {
  51977. dFdx: 'dpdx',
  51978. dFdy: '- dpdy',
  51979. mod_float: 'tsl_mod_float',
  51980. mod_vec2: 'tsl_mod_vec2',
  51981. mod_vec3: 'tsl_mod_vec3',
  51982. mod_vec4: 'tsl_mod_vec4',
  51983. equals_bool: 'tsl_equals_bool',
  51984. equals_bvec2: 'tsl_equals_bvec2',
  51985. equals_bvec3: 'tsl_equals_bvec3',
  51986. equals_bvec4: 'tsl_equals_bvec4',
  51987. inversesqrt: 'inverseSqrt',
  51988. bitcast: 'bitcast<f32>',
  51989. floatpack_snorm_2x16: 'pack2x16snorm',
  51990. floatpack_unorm_2x16: 'pack2x16unorm',
  51991. floatpack_float16_2x16: 'pack2x16float',
  51992. floatunpack_snorm_2x16: 'unpack2x16snorm',
  51993. floatunpack_unorm_2x16: 'unpack2x16unorm',
  51994. floatunpack_float16_2x16: 'unpack2x16float'
  51995. };
  51996. //
  51997. let diagnostics = '';
  51998. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  51999. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  52000. }
  52001. /**
  52002. * A node builder targeting WGSL.
  52003. *
  52004. * This module generates WGSL shader code from node materials and also
  52005. * generates the respective bindings and vertex buffer definitions. These
  52006. * data are later used by the renderer to create render and compute pipelines
  52007. * for render objects.
  52008. *
  52009. * @augments NodeBuilder
  52010. */
  52011. class WGSLNodeBuilder extends NodeBuilder {
  52012. /**
  52013. * Constructs a new WGSL node builder renderer.
  52014. *
  52015. * @param {Object3D} object - The 3D object.
  52016. * @param {Renderer} renderer - The renderer.
  52017. */
  52018. constructor( object, renderer ) {
  52019. super( object, renderer, new WGSLNodeParser() );
  52020. /**
  52021. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  52022. * another dictionary which manages UBOs per group ('render','frame','object').
  52023. *
  52024. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  52025. */
  52026. this.uniformGroups = {};
  52027. /**
  52028. * A dictionary that holds for each shader stage a Map of builtins.
  52029. *
  52030. * @type {Object<string,Map<string,Object>>}
  52031. */
  52032. this.builtins = {};
  52033. /**
  52034. * A dictionary that holds for each shader stage a Set of directives.
  52035. *
  52036. * @type {Object<string,Set<string>>}
  52037. */
  52038. this.directives = {};
  52039. /**
  52040. * A map for managing scope arrays. Only relevant for when using
  52041. * {@link WorkgroupInfoNode} in context of compute shaders.
  52042. *
  52043. * @type {Map<string,Object>}
  52044. */
  52045. this.scopedArrays = new Map();
  52046. }
  52047. /**
  52048. * Generates the WGSL snippet for sampled textures.
  52049. *
  52050. * @private
  52051. * @param {Texture} texture - The texture.
  52052. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52053. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52054. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52055. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52056. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52057. * @return {string} The WGSL snippet.
  52058. */
  52059. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52060. if ( shaderStage === 'fragment' ) {
  52061. if ( depthSnippet ) {
  52062. if ( offsetSnippet ) {
  52063. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  52064. }
  52065. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  52066. } else {
  52067. if ( offsetSnippet ) {
  52068. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  52069. }
  52070. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  52071. }
  52072. } else {
  52073. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  52074. }
  52075. }
  52076. /**
  52077. * Generates the WGSL snippet when sampling textures with explicit mip level.
  52078. *
  52079. * @private
  52080. * @param {Texture} texture - The texture.
  52081. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52082. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52083. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52084. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52085. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52086. * @return {string} The WGSL snippet.
  52087. */
  52088. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52089. if ( this.isUnfilterable( texture ) === false ) {
  52090. if ( offsetSnippet ) {
  52091. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52092. }
  52093. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  52094. } else if ( this.isFilteredTexture( texture ) ) {
  52095. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  52096. } else {
  52097. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  52098. }
  52099. }
  52100. /**
  52101. * Generates a wrap function used in context of textures.
  52102. *
  52103. * @param {Texture} texture - The texture to generate the function for.
  52104. * @return {string} The name of the generated function.
  52105. */
  52106. generateWrapFunction( texture ) {
  52107. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.is3DTexture || texture.isData3DTexture ? '3d' : '2d' }T`;
  52108. let nodeCode = wgslCodeCache[ functionName ];
  52109. if ( nodeCode === undefined ) {
  52110. const includes = [];
  52111. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  52112. const coordType = texture.is3DTexture || texture.isData3DTexture ? 'vec3f' : 'vec2f';
  52113. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  52114. const addWrapSnippet = ( wrap, axis ) => {
  52115. if ( wrap === RepeatWrapping ) {
  52116. includes.push( wgslPolyfill.repeatWrapping_float );
  52117. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  52118. } else if ( wrap === ClampToEdgeWrapping ) {
  52119. includes.push( wgslPolyfill.clampWrapping_float );
  52120. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  52121. } else if ( wrap === MirroredRepeatWrapping ) {
  52122. includes.push( wgslPolyfill.mirrorWrapping_float );
  52123. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  52124. } else {
  52125. code += `\t\tcoord.${ axis }`;
  52126. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  52127. }
  52128. };
  52129. addWrapSnippet( texture.wrapS, 'x' );
  52130. code += ',\n';
  52131. addWrapSnippet( texture.wrapT, 'y' );
  52132. if ( texture.is3DTexture || texture.isData3DTexture ) {
  52133. code += ',\n';
  52134. addWrapSnippet( texture.wrapR, 'z' );
  52135. }
  52136. code += '\n\t);\n\n}\n';
  52137. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  52138. }
  52139. nodeCode.build( this );
  52140. return functionName;
  52141. }
  52142. /**
  52143. * Generates the array declaration string.
  52144. *
  52145. * @param {string} type - The type.
  52146. * @param {?number} [count] - The count.
  52147. * @return {string} The generated value as a shader string.
  52148. */
  52149. generateArrayDeclaration( type, count ) {
  52150. return `array< ${ this.getType( type ) }, ${ count } >`;
  52151. }
  52152. /**
  52153. * Generates a WGSL variable that holds the texture dimension of the given texture.
  52154. * It also returns information about the number of layers (elements) of an arrayed
  52155. * texture as well as the cube face count of cube textures.
  52156. *
  52157. * @param {Texture} texture - The texture to generate the function for.
  52158. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  52159. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52160. * @return {string} The name of the dimension variable.
  52161. */
  52162. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  52163. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  52164. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  52165. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  52166. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  52167. let textureDimensionsParams;
  52168. let dimensionType;
  52169. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  52170. const isMultisampled = primarySamples > 1;
  52171. if ( texture.is3DTexture || texture.isData3DTexture ) {
  52172. dimensionType = 'vec3<u32>';
  52173. } else {
  52174. // Regular 2D textures, depth textures, etc.
  52175. dimensionType = 'vec2<u32>';
  52176. }
  52177. // Build parameters string based on texture type and multisampling
  52178. if ( isMultisampled || texture.isStorageTexture ) {
  52179. textureDimensionsParams = textureProperty;
  52180. } else {
  52181. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  52182. }
  52183. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  52184. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  52185. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.is3DTexture || texture.isData3DTexture ) {
  52186. textureData.arrayLayerCount = new VarNode(
  52187. new ExpressionNode(
  52188. `textureNumLayers(${textureProperty})`,
  52189. 'u32'
  52190. )
  52191. );
  52192. }
  52193. // For cube textures, we know it's always 6 faces
  52194. if ( texture.isTextureCube ) {
  52195. textureData.cubeFaceCount = new VarNode(
  52196. new ExpressionNode( '6u', 'u32' )
  52197. );
  52198. }
  52199. }
  52200. return textureDimensionNode.build( this );
  52201. }
  52202. /**
  52203. * Generates the WGSL snippet for a manual filtered texture.
  52204. *
  52205. * @param {Texture} texture - The texture.
  52206. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52207. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52208. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52209. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52210. * @return {string} The WGSL snippet.
  52211. */
  52212. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  52213. this._include( 'biquadraticTexture' );
  52214. const wrapFunction = this.generateWrapFunction( texture );
  52215. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  52216. if ( offsetSnippet ) {
  52217. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  52218. }
  52219. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  52220. }
  52221. /**
  52222. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  52223. * Since it's a lookup, no sampling or filtering is applied.
  52224. *
  52225. * @param {Texture} texture - The texture.
  52226. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52227. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52228. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52229. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52230. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52231. * @return {string} The WGSL snippet.
  52232. */
  52233. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  52234. const wrapFunction = this.generateWrapFunction( texture );
  52235. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  52236. const vecType = texture.is3DTexture || texture.isData3DTexture ? 'vec3' : 'vec2';
  52237. if ( offsetSnippet ) {
  52238. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  52239. }
  52240. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  52241. return this.generateTextureLoad( texture, textureProperty, coordSnippet, levelSnippet, depthSnippet, null );
  52242. }
  52243. /**
  52244. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  52245. *
  52246. * @param {Texture} texture - The texture.
  52247. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52248. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52249. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52250. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52251. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52252. * @return {string} The WGSL snippet.
  52253. */
  52254. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52255. if ( levelSnippet === null ) levelSnippet = '0u';
  52256. if ( offsetSnippet ) {
  52257. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  52258. }
  52259. let snippet;
  52260. if ( depthSnippet ) {
  52261. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  52262. } else {
  52263. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  52264. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  52265. snippet += '.x';
  52266. }
  52267. }
  52268. return snippet;
  52269. }
  52270. /**
  52271. * Generates the WGSL snippet that writes a single texel to a texture.
  52272. *
  52273. * @param {Texture} texture - The texture.
  52274. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52275. * @param {string} uvIndexSnippet - 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} valueSnippet - A WGSL snippet that represent the new texel value.
  52278. * @return {string} The WGSL snippet.
  52279. */
  52280. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  52281. let snippet;
  52282. if ( depthSnippet ) {
  52283. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  52284. } else {
  52285. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  52286. }
  52287. return snippet;
  52288. }
  52289. /**
  52290. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  52291. *
  52292. * @param {Texture} texture - The texture.
  52293. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  52294. */
  52295. isSampleCompare( texture ) {
  52296. return texture.isDepthTexture === true && texture.compareFunction !== null;
  52297. }
  52298. /**
  52299. * Returns `true` if the given texture is unfilterable.
  52300. *
  52301. * @param {Texture} texture - The texture.
  52302. * @return {boolean} Whether the given texture is unfilterable or not.
  52303. */
  52304. isUnfilterable( texture ) {
  52305. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  52306. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  52307. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  52308. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  52309. }
  52310. /**
  52311. * Generates the WGSL snippet for sampling/loading the given texture.
  52312. *
  52313. * @param {Texture} texture - The texture.
  52314. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52315. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52316. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52317. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52318. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52319. * @return {string} The WGSL snippet.
  52320. */
  52321. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52322. let snippet = null;
  52323. if ( this.isUnfilterable( texture ) ) {
  52324. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  52325. } else {
  52326. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  52327. }
  52328. return snippet;
  52329. }
  52330. /**
  52331. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  52332. *
  52333. * @param {Texture} texture - The texture.
  52334. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52335. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52336. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  52337. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52338. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52339. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52340. * @return {string} The WGSL snippet.
  52341. */
  52342. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52343. if ( shaderStage === 'fragment' ) {
  52344. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  52345. if ( offsetSnippet ) {
  52346. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  52347. }
  52348. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  52349. } else {
  52350. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  52351. }
  52352. }
  52353. /**
  52354. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  52355. * against a reference value.
  52356. *
  52357. * @param {Texture} texture - The texture.
  52358. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52359. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52360. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  52361. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52362. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52363. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52364. * @return {string} The WGSL snippet.
  52365. */
  52366. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52367. if ( shaderStage === 'fragment' ) {
  52368. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  52369. if ( offsetSnippet ) {
  52370. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  52371. }
  52372. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  52373. }
  52374. if ( offsetSnippet ) {
  52375. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  52376. }
  52377. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  52378. } else {
  52379. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  52380. }
  52381. }
  52382. /**
  52383. * Generates the WGSL snippet when sampling textures with explicit mip level.
  52384. *
  52385. * @param {Texture} texture - The texture.
  52386. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52387. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52388. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52389. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52390. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52391. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52392. * @return {string} The WGSL snippet.
  52393. */
  52394. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52395. if ( this.isUnfilterable( texture ) === false ) {
  52396. if ( offsetSnippet ) {
  52397. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52398. }
  52399. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  52400. } else if ( this.isFilteredTexture( texture ) ) {
  52401. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  52402. } else {
  52403. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  52404. }
  52405. }
  52406. /**
  52407. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  52408. *
  52409. * @param {Texture} texture - The texture.
  52410. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52411. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52412. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  52413. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52414. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52415. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52416. * @return {string} The WGSL snippet.
  52417. */
  52418. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52419. if ( shaderStage === 'fragment' ) {
  52420. if ( offsetSnippet ) {
  52421. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  52422. }
  52423. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  52424. } else {
  52425. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  52426. }
  52427. }
  52428. /**
  52429. * Returns a WGSL snippet that represents the property name of the given node.
  52430. *
  52431. * @param {Node} node - The node.
  52432. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52433. * @return {string} The property name.
  52434. */
  52435. getPropertyName( node, shaderStage = this.shaderStage ) {
  52436. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  52437. if ( shaderStage === 'vertex' ) {
  52438. return `varyings.${ node.name }`;
  52439. }
  52440. } else if ( node.isNodeUniform === true ) {
  52441. const name = node.name;
  52442. const type = node.type;
  52443. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  52444. return name;
  52445. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  52446. if ( this.isCustomStruct( node ) ) {
  52447. return name;
  52448. }
  52449. return name + '.value';
  52450. } else {
  52451. return node.groupNode.name + '.' + name;
  52452. }
  52453. }
  52454. return super.getPropertyName( node );
  52455. }
  52456. /**
  52457. * Returns the output struct name.
  52458. *
  52459. * @return {string} The name of the output struct.
  52460. */
  52461. getOutputStructName() {
  52462. return 'output';
  52463. }
  52464. /**
  52465. * Returns the native shader operator name for a given generic name.
  52466. *
  52467. * @param {string} op - The operator name to resolve.
  52468. * @return {?string} The resolved operator name.
  52469. */
  52470. getFunctionOperator( op ) {
  52471. const fnOp = wgslFnOpLib[ op ];
  52472. if ( fnOp !== undefined ) {
  52473. this._include( fnOp );
  52474. return fnOp;
  52475. }
  52476. return null;
  52477. }
  52478. /**
  52479. * Returns the node access for the given node and shader stage.
  52480. *
  52481. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  52482. * @param {string} shaderStage - The shader stage.
  52483. * @return {string} The node access.
  52484. */
  52485. getNodeAccess( node, shaderStage ) {
  52486. if ( shaderStage !== 'compute' ) {
  52487. if ( node.isAtomic === true ) {
  52488. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  52489. return NodeAccess.READ_WRITE;
  52490. }
  52491. return NodeAccess.READ_ONLY;
  52492. }
  52493. return node.access;
  52494. }
  52495. /**
  52496. * Returns A WGSL snippet representing the storage access.
  52497. *
  52498. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  52499. * @param {string} shaderStage - The shader stage.
  52500. * @return {string} The WGSL snippet representing the storage access.
  52501. */
  52502. getStorageAccess( node, shaderStage ) {
  52503. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  52504. }
  52505. /**
  52506. * This method is one of the more important ones since it's responsible
  52507. * for generating a matching binding instance for the given uniform node.
  52508. *
  52509. * These bindings are later used in the renderer to create bind groups
  52510. * and layouts.
  52511. *
  52512. * @param {UniformNode} node - The uniform node.
  52513. * @param {string} type - The node data type.
  52514. * @param {string} shaderStage - The shader stage.
  52515. * @param {?string} [name=null] - An optional uniform name.
  52516. * @return {NodeUniform} The node uniform object.
  52517. */
  52518. getUniformFromNode( node, type, shaderStage, name = null ) {
  52519. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  52520. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  52521. if ( nodeData.uniformGPU === undefined ) {
  52522. let uniformGPU;
  52523. const group = node.groupNode;
  52524. const groupName = group.name;
  52525. const bindings = this.getBindGroupArray( groupName, shaderStage );
  52526. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  52527. let texture = null;
  52528. const access = this.getNodeAccess( node, shaderStage );
  52529. if ( type === 'texture' || type === 'storageTexture' ) {
  52530. if ( node.value.is3DTexture === true ) {
  52531. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  52532. } else {
  52533. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  52534. }
  52535. } else if ( type === 'cubeTexture' ) {
  52536. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  52537. } else if ( type === 'texture3D' ) {
  52538. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  52539. }
  52540. texture.store = node.isStorageTextureNode === true;
  52541. texture.mipLevel = texture.store ? node.mipLevel : 0;
  52542. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52543. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  52544. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  52545. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52546. bindings.push( sampler, texture );
  52547. uniformGPU = [ sampler, texture ];
  52548. } else {
  52549. bindings.push( texture );
  52550. uniformGPU = [ texture ];
  52551. }
  52552. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  52553. const sharedData = this.getSharedDataFromNode( node );
  52554. let buffer = sharedData.buffer;
  52555. if ( buffer === undefined ) {
  52556. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  52557. buffer = new bufferClass( node, group );
  52558. sharedData.buffer = buffer;
  52559. }
  52560. buffer.setVisibility( buffer.getVisibility() | gpuShaderStageLib[ shaderStage ] );
  52561. bindings.push( buffer );
  52562. uniformGPU = buffer;
  52563. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  52564. } else {
  52565. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  52566. let uniformsGroup = uniformsStage[ groupName ];
  52567. if ( uniformsGroup === undefined ) {
  52568. uniformsGroup = new NodeUniformsGroup( groupName, group );
  52569. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52570. uniformsStage[ groupName ] = uniformsGroup;
  52571. bindings.push( uniformsGroup );
  52572. }
  52573. uniformGPU = this.getNodeUniform( uniformNode, type );
  52574. uniformsGroup.addUniform( uniformGPU );
  52575. }
  52576. nodeData.uniformGPU = uniformGPU;
  52577. }
  52578. return uniformNode;
  52579. }
  52580. /**
  52581. * This method should be used whenever builtins are required in nodes.
  52582. * The internal builtins data structure will make sure builtins are
  52583. * defined in the WGSL source.
  52584. *
  52585. * @param {string} name - The builtin name.
  52586. * @param {string} property - The property name.
  52587. * @param {string} type - The node data type.
  52588. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52589. * @return {string} The property name.
  52590. */
  52591. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  52592. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  52593. if ( map.has( name ) === false ) {
  52594. map.set( name, {
  52595. name,
  52596. property,
  52597. type
  52598. } );
  52599. }
  52600. return property;
  52601. }
  52602. /**
  52603. * Returns `true` if the given builtin is defined in the given shader stage.
  52604. *
  52605. * @param {string} name - The builtin name.
  52606. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52607. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  52608. */
  52609. hasBuiltin( name, shaderStage = this.shaderStage ) {
  52610. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  52611. }
  52612. /**
  52613. * Returns the vertex index builtin.
  52614. *
  52615. * @return {string} The vertex index.
  52616. */
  52617. getVertexIndex() {
  52618. if ( this.shaderStage === 'vertex' ) {
  52619. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  52620. }
  52621. return 'vertexIndex';
  52622. }
  52623. /**
  52624. * Builds the given shader node.
  52625. *
  52626. * @param {ShaderNodeInternal} shaderNode - The shader node.
  52627. * @return {string} The WGSL function code.
  52628. */
  52629. buildFunctionCode( shaderNode ) {
  52630. const layout = shaderNode.layout;
  52631. const flowData = this.flowShaderNode( shaderNode );
  52632. const parameters = [];
  52633. for ( const input of layout.inputs ) {
  52634. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  52635. }
  52636. //
  52637. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  52638. ${ flowData.vars }
  52639. ${ flowData.code }
  52640. `;
  52641. if ( flowData.result ) {
  52642. code += `\treturn ${ flowData.result };\n`;
  52643. }
  52644. code += '\n}\n';
  52645. //
  52646. return code;
  52647. }
  52648. /**
  52649. * Contextually returns either the vertex stage instance index builtin
  52650. * or the linearized index of an compute invocation within a grid of workgroups.
  52651. *
  52652. * @return {string} The instance index.
  52653. */
  52654. getInstanceIndex() {
  52655. if ( this.shaderStage === 'vertex' ) {
  52656. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  52657. }
  52658. return 'instanceIndex';
  52659. }
  52660. /**
  52661. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  52662. *
  52663. * @return {string} The invocation local index.
  52664. */
  52665. getInvocationLocalIndex() {
  52666. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  52667. }
  52668. /**
  52669. * Returns a builtin representing the size of a subgroup within the current shader.
  52670. *
  52671. * @return {string} The subgroup size.
  52672. */
  52673. getSubgroupSize() {
  52674. this.enableSubGroups();
  52675. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  52676. }
  52677. /**
  52678. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  52679. *
  52680. * @return {string} The invocation subgroup index.
  52681. */
  52682. getInvocationSubgroupIndex() {
  52683. this.enableSubGroups();
  52684. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  52685. }
  52686. /**
  52687. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  52688. *
  52689. * @return {string} The subgroup index.
  52690. */
  52691. getSubgroupIndex() {
  52692. this.enableSubGroups();
  52693. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  52694. }
  52695. /**
  52696. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  52697. *
  52698. * @return {null} Null.
  52699. */
  52700. getDrawIndex() {
  52701. return null;
  52702. }
  52703. /**
  52704. * Returns the front facing builtin.
  52705. *
  52706. * @return {string} The front facing builtin.
  52707. */
  52708. getFrontFacing() {
  52709. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  52710. }
  52711. /**
  52712. * Returns the frag coord builtin.
  52713. *
  52714. * @return {string} The frag coord builtin.
  52715. */
  52716. getFragCoord() {
  52717. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  52718. }
  52719. /**
  52720. * Returns the frag depth builtin.
  52721. *
  52722. * @return {string} The frag depth builtin.
  52723. */
  52724. getFragDepth() {
  52725. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  52726. }
  52727. /**
  52728. * Returns the clip distances builtin.
  52729. *
  52730. * @return {string} The clip distances builtin.
  52731. */
  52732. getClipDistance() {
  52733. return 'varyings.hw_clip_distances';
  52734. }
  52735. /**
  52736. * Whether to flip texture data along its vertical axis or not.
  52737. *
  52738. * @return {boolean} Returns always `false` in context of WGSL.
  52739. */
  52740. isFlipY() {
  52741. return false;
  52742. }
  52743. /**
  52744. * Enables the given directive for the given shader stage.
  52745. *
  52746. * @param {string} name - The directive name.
  52747. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  52748. */
  52749. enableDirective( name, shaderStage = this.shaderStage ) {
  52750. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  52751. stage.add( name );
  52752. }
  52753. /**
  52754. * Returns the directives of the given shader stage as a WGSL string.
  52755. *
  52756. * @param {string} shaderStage - The shader stage.
  52757. * @return {string} A WGSL snippet that enables the directives of the given stage.
  52758. */
  52759. getDirectives( shaderStage ) {
  52760. const snippets = [];
  52761. const directives = this.directives[ shaderStage ];
  52762. if ( directives !== undefined ) {
  52763. for ( const directive of directives ) {
  52764. snippets.push( `enable ${directive};` );
  52765. }
  52766. }
  52767. return snippets.join( '\n' );
  52768. }
  52769. /**
  52770. * Enables the 'subgroups' directive.
  52771. */
  52772. enableSubGroups() {
  52773. this.enableDirective( 'subgroups' );
  52774. }
  52775. /**
  52776. * Enables the 'subgroups-f16' directive.
  52777. */
  52778. enableSubgroupsF16() {
  52779. this.enableDirective( 'subgroups-f16' );
  52780. }
  52781. /**
  52782. * Enables the 'clip_distances' directive.
  52783. */
  52784. enableClipDistances() {
  52785. this.enableDirective( 'clip_distances' );
  52786. }
  52787. /**
  52788. * Enables the 'f16' directive.
  52789. */
  52790. enableShaderF16() {
  52791. this.enableDirective( 'f16' );
  52792. }
  52793. /**
  52794. * Enables the 'dual_source_blending' directive.
  52795. */
  52796. enableDualSourceBlending() {
  52797. this.enableDirective( 'dual_source_blending' );
  52798. }
  52799. /**
  52800. * Enables hardware clipping.
  52801. *
  52802. * @param {string} planeCount - The clipping plane count.
  52803. */
  52804. enableHardwareClipping( planeCount ) {
  52805. this.enableClipDistances();
  52806. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  52807. }
  52808. /**
  52809. * Returns the builtins of the given shader stage as a WGSL string.
  52810. *
  52811. * @param {string} shaderStage - The shader stage.
  52812. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  52813. */
  52814. getBuiltins( shaderStage ) {
  52815. const snippets = [];
  52816. const builtins = this.builtins[ shaderStage ];
  52817. if ( builtins !== undefined ) {
  52818. for ( const { name, property, type } of builtins.values() ) {
  52819. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  52820. }
  52821. }
  52822. return snippets.join( ',\n\t' );
  52823. }
  52824. /**
  52825. * This method should be used when a new scoped buffer is used in context of
  52826. * compute shaders. It adds the array to the internal data structure which is
  52827. * later used to generate the respective WGSL.
  52828. *
  52829. * @param {string} name - The array name.
  52830. * @param {string} scope - The scope.
  52831. * @param {string} bufferType - The buffer type.
  52832. * @param {string} bufferCount - The buffer count.
  52833. * @return {string} The array name.
  52834. */
  52835. getScopedArray( name, scope, bufferType, bufferCount ) {
  52836. if ( this.scopedArrays.has( name ) === false ) {
  52837. this.scopedArrays.set( name, {
  52838. name,
  52839. scope,
  52840. bufferType,
  52841. bufferCount
  52842. } );
  52843. }
  52844. return name;
  52845. }
  52846. /**
  52847. * Returns the scoped arrays of the given shader stage as a WGSL string.
  52848. *
  52849. * @param {string} shaderStage - The shader stage.
  52850. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  52851. * Returns `undefined` when used in the vertex or fragment stage.
  52852. */
  52853. getScopedArrays( shaderStage ) {
  52854. if ( shaderStage !== 'compute' ) {
  52855. return;
  52856. }
  52857. const snippets = [];
  52858. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  52859. const type = this.getType( bufferType );
  52860. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  52861. }
  52862. return snippets.join( '\n' );
  52863. }
  52864. /**
  52865. * Returns the shader attributes of the given shader stage as a WGSL string.
  52866. *
  52867. * @param {string} shaderStage - The shader stage.
  52868. * @return {string} The WGSL snippet that defines the shader attributes.
  52869. */
  52870. getAttributes( shaderStage ) {
  52871. const snippets = [];
  52872. if ( shaderStage === 'compute' ) {
  52873. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  52874. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  52875. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  52876. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  52877. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  52878. this.enableDirective( 'subgroups', shaderStage );
  52879. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  52880. }
  52881. }
  52882. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  52883. const builtins = this.getBuiltins( 'attribute' );
  52884. if ( builtins ) snippets.push( builtins );
  52885. const attributes = this.getAttributesArray();
  52886. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  52887. const attribute = attributes[ index ];
  52888. const name = attribute.name;
  52889. const type = this.getType( attribute.type );
  52890. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  52891. }
  52892. }
  52893. return snippets.join( ',\n\t' );
  52894. }
  52895. /**
  52896. * Returns the members of the given struct type node as a WGSL string.
  52897. *
  52898. * @param {StructTypeNode} struct - The struct type node.
  52899. * @return {string} The WGSL snippet that defines the struct members.
  52900. */
  52901. getStructMembers( struct ) {
  52902. const snippets = [];
  52903. for ( const member of struct.members ) {
  52904. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  52905. let type = this.getType( member.type );
  52906. if ( member.atomic ) {
  52907. type = 'atomic< ' + type + ' >';
  52908. }
  52909. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  52910. }
  52911. if ( struct.output ) {
  52912. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  52913. }
  52914. return snippets.join( ',\n' );
  52915. }
  52916. /**
  52917. * Returns the structs of the given shader stage as a WGSL string.
  52918. *
  52919. * @param {string} shaderStage - The shader stage.
  52920. * @return {string} The WGSL snippet that defines the structs.
  52921. */
  52922. getStructs( shaderStage ) {
  52923. let result = '';
  52924. const structs = this.structs[ shaderStage ];
  52925. if ( structs.length > 0 ) {
  52926. const snippets = [];
  52927. for ( const struct of structs ) {
  52928. let snippet = `struct ${ struct.name } {\n`;
  52929. snippet += this.getStructMembers( struct );
  52930. snippet += '\n};';
  52931. snippets.push( snippet );
  52932. }
  52933. result = '\n' + snippets.join( '\n\n' ) + '\n';
  52934. }
  52935. return result;
  52936. }
  52937. /**
  52938. * Returns a WGSL string representing a variable.
  52939. *
  52940. * @param {string} type - The variable's type.
  52941. * @param {string} name - The variable's name.
  52942. * @param {?number} [count=null] - The array length.
  52943. * @return {string} The WGSL snippet that defines a variable.
  52944. */
  52945. getVar( type, name, count = null ) {
  52946. let snippet = `var ${ name } : `;
  52947. if ( count !== null ) {
  52948. snippet += this.generateArrayDeclaration( type, count );
  52949. } else {
  52950. snippet += this.getType( type );
  52951. }
  52952. return snippet;
  52953. }
  52954. /**
  52955. * Returns the variables of the given shader stage as a WGSL string.
  52956. *
  52957. * @param {string} shaderStage - The shader stage.
  52958. * @return {string} The WGSL snippet that defines the variables.
  52959. */
  52960. getVars( shaderStage ) {
  52961. const snippets = [];
  52962. const vars = this.vars[ shaderStage ];
  52963. if ( vars !== undefined ) {
  52964. for ( const variable of vars ) {
  52965. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  52966. }
  52967. }
  52968. return `\n${ snippets.join( '\n' ) }\n`;
  52969. }
  52970. /**
  52971. * Returns the varyings of the given shader stage as a WGSL string.
  52972. *
  52973. * @param {string} shaderStage - The shader stage.
  52974. * @return {string} The WGSL snippet that defines the varyings.
  52975. */
  52976. getVaryings( shaderStage ) {
  52977. const snippets = [];
  52978. if ( shaderStage === 'vertex' ) {
  52979. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  52980. }
  52981. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  52982. const varyings = this.varyings;
  52983. const vars = this.vars[ shaderStage ];
  52984. for ( let index = 0; index < varyings.length; index ++ ) {
  52985. const varying = varyings[ index ];
  52986. if ( varying.needsInterpolation ) {
  52987. let attributesSnippet = `@location( ${index} )`;
  52988. if ( varying.interpolationType ) {
  52989. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  52990. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  52991. // Otherwise, optimize interpolation when sensible
  52992. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  52993. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  52994. }
  52995. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  52996. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  52997. vars.push( varying );
  52998. }
  52999. }
  53000. }
  53001. const builtins = this.getBuiltins( shaderStage );
  53002. if ( builtins ) snippets.push( builtins );
  53003. const code = snippets.join( ',\n\t' );
  53004. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  53005. }
  53006. isCustomStruct( nodeUniform ) {
  53007. const attribute = nodeUniform.value;
  53008. const bufferNode = nodeUniform.node;
  53009. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  53010. const isStructArray =
  53011. ( bufferNode.value && bufferNode.value.array ) &&
  53012. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  53013. return isAttributeStructType && ! isStructArray;
  53014. }
  53015. /**
  53016. * Returns the uniforms of the given shader stage as a WGSL string.
  53017. *
  53018. * @param {string} shaderStage - The shader stage.
  53019. * @return {string} The WGSL snippet that defines the uniforms.
  53020. */
  53021. getUniforms( shaderStage ) {
  53022. const uniforms = this.uniforms[ shaderStage ];
  53023. const bindingSnippets = [];
  53024. const bufferSnippets = [];
  53025. const structSnippets = [];
  53026. const uniformGroups = {};
  53027. for ( const uniform of uniforms ) {
  53028. const groupName = uniform.groupNode.name;
  53029. const uniformIndexes = this.bindingsIndexes[ groupName ];
  53030. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  53031. const texture = uniform.node.value;
  53032. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  53033. if ( this.isSampleCompare( texture ) ) {
  53034. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  53035. } else {
  53036. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  53037. }
  53038. }
  53039. let textureType;
  53040. let multisampled = '';
  53041. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  53042. if ( primarySamples > 1 ) {
  53043. multisampled = '_multisampled';
  53044. }
  53045. if ( texture.isCubeTexture === true ) {
  53046. textureType = 'texture_cube<f32>';
  53047. } else if ( texture.isDepthTexture === true ) {
  53048. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  53049. textureType = `texture${ multisampled }_2d<f32>`;
  53050. } else {
  53051. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  53052. }
  53053. } else if ( uniform.node.isStorageTextureNode === true ) {
  53054. const format = getFormat( texture );
  53055. const access = this.getStorageAccess( uniform.node, shaderStage );
  53056. const is3D = uniform.node.value.is3DTexture;
  53057. const isArrayTexture = uniform.node.value.isArrayTexture;
  53058. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  53059. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  53060. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  53061. textureType = 'texture_2d_array<f32>';
  53062. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  53063. textureType = 'texture_3d<f32>';
  53064. } else {
  53065. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  53066. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  53067. }
  53068. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  53069. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  53070. const bufferNode = uniform.node;
  53071. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  53072. const bufferCount = bufferNode.bufferCount;
  53073. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  53074. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  53075. if ( this.isCustomStruct( uniform ) ) {
  53076. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  53077. } else {
  53078. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  53079. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  53080. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  53081. }
  53082. } else {
  53083. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  53084. const groupName = uniform.groupNode.name;
  53085. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  53086. index: uniformIndexes.binding ++,
  53087. id: uniformIndexes.group,
  53088. snippets: []
  53089. } );
  53090. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  53091. }
  53092. }
  53093. for ( const name in uniformGroups ) {
  53094. const group = uniformGroups[ name ];
  53095. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  53096. }
  53097. let code = bindingSnippets.join( '\n' );
  53098. code += bufferSnippets.join( '\n' );
  53099. code += structSnippets.join( '\n' );
  53100. return code;
  53101. }
  53102. /**
  53103. * Controls the code build of the shader stages.
  53104. */
  53105. buildCode() {
  53106. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  53107. this.sortBindingGroups();
  53108. for ( const shaderStage in shadersData ) {
  53109. this.shaderStage = shaderStage;
  53110. const stageData = shadersData[ shaderStage ];
  53111. stageData.uniforms = this.getUniforms( shaderStage );
  53112. stageData.attributes = this.getAttributes( shaderStage );
  53113. stageData.varyings = this.getVaryings( shaderStage );
  53114. stageData.structs = this.getStructs( shaderStage );
  53115. stageData.vars = this.getVars( shaderStage );
  53116. stageData.codes = this.getCodes( shaderStage );
  53117. stageData.directives = this.getDirectives( shaderStage );
  53118. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  53119. //
  53120. let flow = '// code\n\n';
  53121. flow += this.flowCode[ shaderStage ];
  53122. const flowNodes = this.flowNodes[ shaderStage ];
  53123. const mainNode = flowNodes[ flowNodes.length - 1 ];
  53124. const outputNode = mainNode.outputNode;
  53125. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  53126. for ( const node of flowNodes ) {
  53127. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  53128. const slotName = node.name;
  53129. if ( slotName ) {
  53130. if ( flow.length > 0 ) flow += '\n';
  53131. flow += `\t// flow -> ${ slotName }\n`;
  53132. }
  53133. flow += `${ flowSlotData.code }\n\t`;
  53134. if ( node === mainNode && shaderStage !== 'compute' ) {
  53135. flow += '// result\n\n\t';
  53136. if ( shaderStage === 'vertex' ) {
  53137. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  53138. } else if ( shaderStage === 'fragment' ) {
  53139. if ( isOutputStruct ) {
  53140. stageData.returnType = outputNode.getNodeType( this );
  53141. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  53142. flow += `return ${ flowSlotData.result };`;
  53143. } else {
  53144. let structSnippet = '\t@location(0) color: vec4<f32>';
  53145. const builtins = this.getBuiltins( 'output' );
  53146. if ( builtins ) structSnippet += ',\n\t' + builtins;
  53147. stageData.returnType = 'OutputStruct';
  53148. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  53149. stageData.structs += '\nvar<private> output : OutputStruct;';
  53150. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  53151. }
  53152. }
  53153. }
  53154. }
  53155. stageData.flow = flow;
  53156. }
  53157. this.shaderStage = null;
  53158. if ( this.material !== null ) {
  53159. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  53160. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  53161. } else {
  53162. // Early strictly validated in computeNode
  53163. const workgroupSize = this.object.workgroupSize;
  53164. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  53165. }
  53166. }
  53167. /**
  53168. * Returns the native shader method name for a given generic name.
  53169. *
  53170. * @param {string} method - The method name to resolve.
  53171. * @param {?string} [output=null] - An optional output.
  53172. * @return {string} The resolved WGSL method name.
  53173. */
  53174. getMethod( method, output = null ) {
  53175. let wgslMethod;
  53176. if ( output !== null ) {
  53177. wgslMethod = this._getWGSLMethod( method + '_' + output );
  53178. }
  53179. if ( wgslMethod === undefined ) {
  53180. wgslMethod = this._getWGSLMethod( method );
  53181. }
  53182. return wgslMethod || method;
  53183. }
  53184. /**
  53185. * Returns the bitcast method name for a given input and outputType.
  53186. *
  53187. * @param {string} type - The output type to bitcast to.
  53188. * @return {string} The resolved WGSL bitcast invocation.
  53189. */
  53190. getBitcastMethod( type ) {
  53191. const dataType = this.getType( type );
  53192. return `bitcast<${ dataType }>`;
  53193. }
  53194. /**
  53195. * Returns the float packing method name for a given numeric encoding.
  53196. *
  53197. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  53198. * @returns {string} The resolve WGSL float packing method name.
  53199. */
  53200. getFloatPackingMethod( encoding ) {
  53201. return this.getMethod( `floatpack_${ encoding }_2x16` );
  53202. }
  53203. /**
  53204. * Returns the float unpacking method name for a given numeric encoding.
  53205. *
  53206. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  53207. * @returns {string} The resolve WGSL float unpacking method name.
  53208. */
  53209. getFloatUnpackingMethod( encoding ) {
  53210. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  53211. }
  53212. /**
  53213. * Returns the native snippet for a ternary operation.
  53214. *
  53215. * @param {string} condSnippet - The condition determining which expression gets resolved.
  53216. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  53217. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  53218. * @return {string} The resolved method name.
  53219. */
  53220. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  53221. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  53222. }
  53223. /**
  53224. * Returns the WGSL type of the given node data type.
  53225. *
  53226. * @param {string} type - The node data type.
  53227. * @return {string} The WGSL type.
  53228. */
  53229. getType( type ) {
  53230. return wgslTypeLib[ type ] || type;
  53231. }
  53232. /**
  53233. * Whether the requested feature is available or not.
  53234. *
  53235. * @param {string} name - The requested feature.
  53236. * @return {boolean} Whether the requested feature is supported or not.
  53237. */
  53238. isAvailable( name ) {
  53239. let result = supports[ name ];
  53240. if ( result === undefined ) {
  53241. if ( name === 'float32Filterable' ) {
  53242. result = this.renderer.hasFeature( 'float32-filterable' );
  53243. } else if ( name === 'clipDistance' ) {
  53244. result = this.renderer.hasFeature( 'clip-distances' );
  53245. }
  53246. supports[ name ] = result;
  53247. }
  53248. return result;
  53249. }
  53250. /**
  53251. * Returns the native shader method name for a given generic name.
  53252. *
  53253. * @private
  53254. * @param {string} method - The method name to resolve.
  53255. * @return {string} The resolved WGSL method name.
  53256. */
  53257. _getWGSLMethod( method ) {
  53258. if ( wgslPolyfill[ method ] !== undefined ) {
  53259. this._include( method );
  53260. }
  53261. return wgslMethods[ method ];
  53262. }
  53263. /**
  53264. * Includes the given method name into the current
  53265. * function node.
  53266. *
  53267. * @private
  53268. * @param {string} name - The method name to include.
  53269. * @return {CodeNode} The respective code node.
  53270. */
  53271. _include( name ) {
  53272. const codeNode = wgslPolyfill[ name ];
  53273. codeNode.build( this );
  53274. this.addInclude( codeNode );
  53275. return codeNode;
  53276. }
  53277. /**
  53278. * Returns a WGSL vertex shader based on the given shader data.
  53279. *
  53280. * @private
  53281. * @param {Object} shaderData - The shader data.
  53282. * @return {string} The vertex shader.
  53283. */
  53284. _getWGSLVertexCode( shaderData ) {
  53285. return `${ this.getSignature() }
  53286. // directives
  53287. ${shaderData.directives}
  53288. // structs
  53289. ${shaderData.structs}
  53290. // uniforms
  53291. ${shaderData.uniforms}
  53292. // varyings
  53293. ${shaderData.varyings}
  53294. var<private> varyings : VaryingsStruct;
  53295. // codes
  53296. ${shaderData.codes}
  53297. @vertex
  53298. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  53299. // vars
  53300. ${shaderData.vars}
  53301. // flow
  53302. ${shaderData.flow}
  53303. return varyings;
  53304. }
  53305. `;
  53306. }
  53307. /**
  53308. * Returns a WGSL fragment shader based on the given shader data.
  53309. *
  53310. * @private
  53311. * @param {Object} shaderData - The shader data.
  53312. * @return {string} The vertex shader.
  53313. */
  53314. _getWGSLFragmentCode( shaderData ) {
  53315. return `${ this.getSignature() }
  53316. // global
  53317. ${ diagnostics }
  53318. // structs
  53319. ${shaderData.structs}
  53320. // uniforms
  53321. ${shaderData.uniforms}
  53322. // codes
  53323. ${shaderData.codes}
  53324. @fragment
  53325. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  53326. // vars
  53327. ${shaderData.vars}
  53328. // flow
  53329. ${shaderData.flow}
  53330. }
  53331. `;
  53332. }
  53333. /**
  53334. * Returns a WGSL compute shader based on the given shader data.
  53335. *
  53336. * @private
  53337. * @param {Object} shaderData - The shader data.
  53338. * @param {string} workgroupSize - The workgroup size.
  53339. * @return {string} The vertex shader.
  53340. */
  53341. _getWGSLComputeCode( shaderData, workgroupSize ) {
  53342. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  53343. return `${ this.getSignature() }
  53344. // directives
  53345. ${ shaderData.directives }
  53346. // system
  53347. var<private> instanceIndex : u32;
  53348. // locals
  53349. ${ shaderData.scopedArrays }
  53350. // structs
  53351. ${ shaderData.structs }
  53352. // uniforms
  53353. ${ shaderData.uniforms }
  53354. // codes
  53355. ${ shaderData.codes }
  53356. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  53357. fn main( ${ shaderData.attributes } ) {
  53358. // system
  53359. instanceIndex = globalId.x
  53360. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  53361. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  53362. // vars
  53363. ${ shaderData.vars }
  53364. // flow
  53365. ${ shaderData.flow }
  53366. }
  53367. `;
  53368. }
  53369. /**
  53370. * Returns a WGSL struct based on the given name and variables.
  53371. *
  53372. * @private
  53373. * @param {string} name - The struct name.
  53374. * @param {string} vars - The struct variables.
  53375. * @return {string} The WGSL snippet representing a struct.
  53376. */
  53377. _getWGSLStruct( name, vars ) {
  53378. return `
  53379. struct ${name} {
  53380. ${vars}
  53381. };`;
  53382. }
  53383. /**
  53384. * Returns a WGSL struct binding.
  53385. *
  53386. * @private
  53387. * @param {string} name - The struct name.
  53388. * @param {string} vars - The struct variables.
  53389. * @param {string} access - The access.
  53390. * @param {number} [binding=0] - The binding index.
  53391. * @param {number} [group=0] - The group index.
  53392. * @return {string} The WGSL snippet representing a struct binding.
  53393. */
  53394. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  53395. const structName = name + 'Struct';
  53396. const structSnippet = this._getWGSLStruct( structName, vars );
  53397. return `${structSnippet}
  53398. @binding( ${ binding } ) @group( ${ group } )
  53399. var<${access}> ${ name } : ${ structName };`;
  53400. }
  53401. }
  53402. /**
  53403. * A WebGPU backend utility module with common helpers.
  53404. *
  53405. * @private
  53406. */
  53407. class WebGPUUtils {
  53408. /**
  53409. * Constructs a new utility object.
  53410. *
  53411. * @param {WebGPUBackend} backend - The WebGPU backend.
  53412. */
  53413. constructor( backend ) {
  53414. /**
  53415. * A reference to the WebGPU backend.
  53416. *
  53417. * @type {WebGPUBackend}
  53418. */
  53419. this.backend = backend;
  53420. }
  53421. /**
  53422. * Returns the depth/stencil GPU format for the given render context.
  53423. *
  53424. * @param {RenderContext} renderContext - The render context.
  53425. * @return {string} The depth/stencil GPU texture format.
  53426. */
  53427. getCurrentDepthStencilFormat( renderContext ) {
  53428. let format;
  53429. if ( renderContext.depthTexture !== null ) {
  53430. format = this.getTextureFormatGPU( renderContext.depthTexture );
  53431. } else if ( renderContext.depth && renderContext.stencil ) {
  53432. format = GPUTextureFormat.Depth24PlusStencil8;
  53433. } else if ( renderContext.depth ) {
  53434. format = GPUTextureFormat.Depth24Plus;
  53435. }
  53436. return format;
  53437. }
  53438. /**
  53439. * Returns the GPU format for the given texture.
  53440. *
  53441. * @param {Texture} texture - The texture.
  53442. * @return {string} The GPU texture format.
  53443. */
  53444. getTextureFormatGPU( texture ) {
  53445. return this.backend.get( texture ).format;
  53446. }
  53447. /**
  53448. * Returns an object that defines the multi-sampling state of the given texture.
  53449. *
  53450. * @param {Texture} texture - The texture.
  53451. * @return {Object} The multi-sampling state.
  53452. */
  53453. getTextureSampleData( texture ) {
  53454. let samples;
  53455. if ( texture.isFramebufferTexture ) {
  53456. samples = 1;
  53457. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  53458. const renderer = this.backend.renderer;
  53459. const renderTarget = renderer.getRenderTarget();
  53460. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  53461. } else if ( texture.renderTarget ) {
  53462. samples = texture.renderTarget.samples;
  53463. }
  53464. samples = samples || 1;
  53465. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  53466. const primarySamples = isMSAA ? 1 : samples;
  53467. return { samples, primarySamples, isMSAA };
  53468. }
  53469. /**
  53470. * Returns the default color attachment's GPU format of the current render context.
  53471. *
  53472. * @param {RenderContext} renderContext - The render context.
  53473. * @return {string} The GPU texture format of the default color attachment.
  53474. */
  53475. getCurrentColorFormat( renderContext ) {
  53476. let format;
  53477. if ( renderContext.textures !== null ) {
  53478. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  53479. } else {
  53480. format = this.getPreferredCanvasFormat(); // default context format
  53481. }
  53482. return format;
  53483. }
  53484. /**
  53485. * Returns the GPU formats of all color attachments of the current render context.
  53486. *
  53487. * @param {RenderContext} renderContext - The render context.
  53488. * @return {Array<string>} The GPU texture formats of all color attachments.
  53489. */
  53490. getCurrentColorFormats( renderContext ) {
  53491. if ( renderContext.textures !== null ) {
  53492. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  53493. } else {
  53494. return [ this.getPreferredCanvasFormat() ]; // default context format
  53495. }
  53496. }
  53497. /**
  53498. * Returns the output color space of the current render context.
  53499. *
  53500. * @param {RenderContext} renderContext - The render context.
  53501. * @return {string} The output color space.
  53502. */
  53503. getCurrentColorSpace( renderContext ) {
  53504. if ( renderContext.textures !== null ) {
  53505. return renderContext.textures[ 0 ].colorSpace;
  53506. }
  53507. return this.backend.renderer.outputColorSpace;
  53508. }
  53509. /**
  53510. * Returns GPU primitive topology for the given object and material.
  53511. *
  53512. * @param {Object3D} object - The 3D object.
  53513. * @param {Material} material - The material.
  53514. * @return {string} The GPU primitive topology.
  53515. */
  53516. getPrimitiveTopology( object, material ) {
  53517. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  53518. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  53519. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  53520. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  53521. }
  53522. /**
  53523. * Returns a modified sample count from the given sample count value.
  53524. *
  53525. * That is required since WebGPU only supports either 1 or 4.
  53526. *
  53527. * @param {number} sampleCount - The input sample count.
  53528. * @return {number} The (potentially updated) output sample count.
  53529. */
  53530. getSampleCount( sampleCount ) {
  53531. return sampleCount >= 4 ? 4 : 1;
  53532. }
  53533. /**
  53534. * Returns the sample count of the given render context.
  53535. *
  53536. * @param {RenderContext} renderContext - The render context.
  53537. * @return {number} The sample count.
  53538. */
  53539. getSampleCountRenderContext( renderContext ) {
  53540. if ( renderContext.textures !== null ) {
  53541. return this.getSampleCount( renderContext.sampleCount );
  53542. }
  53543. return this.getSampleCount( this.backend.renderer.currentSamples );
  53544. }
  53545. /**
  53546. * Returns the preferred canvas format.
  53547. *
  53548. * There is a separate method for this so it's possible to
  53549. * honor edge cases for specific devices.
  53550. *
  53551. * @return {string} The GPU texture format of the canvas.
  53552. */
  53553. getPreferredCanvasFormat() {
  53554. const outputType = this.backend.parameters.outputType;
  53555. if ( outputType === undefined ) {
  53556. return navigator.gpu.getPreferredCanvasFormat();
  53557. } else if ( outputType === UnsignedByteType ) {
  53558. return GPUTextureFormat.BGRA8Unorm;
  53559. } else if ( outputType === HalfFloatType ) {
  53560. return GPUTextureFormat.RGBA16Float;
  53561. } else {
  53562. throw new Error( 'Unsupported outputType' );
  53563. }
  53564. }
  53565. }
  53566. const typedArraysToVertexFormatPrefix = new Map( [
  53567. [ Int8Array, [ 'sint8', 'snorm8' ]],
  53568. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  53569. [ Int16Array, [ 'sint16', 'snorm16' ]],
  53570. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  53571. [ Int32Array, [ 'sint32', 'snorm32' ]],
  53572. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  53573. [ Float32Array, [ 'float32', ]],
  53574. ] );
  53575. if ( typeof Float16Array !== 'undefined' ) {
  53576. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  53577. }
  53578. const typedAttributeToVertexFormatPrefix = new Map( [
  53579. [ Float16BufferAttribute, [ 'float16', ]],
  53580. ] );
  53581. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  53582. [ Int32Array, 'sint32' ],
  53583. [ Int16Array, 'sint32' ], // patch for INT16
  53584. [ Uint32Array, 'uint32' ],
  53585. [ Uint16Array, 'uint32' ], // patch for UINT16
  53586. [ Float32Array, 'float32' ]
  53587. ] );
  53588. /**
  53589. * A WebGPU backend utility module for managing shader attributes.
  53590. *
  53591. * @private
  53592. */
  53593. class WebGPUAttributeUtils {
  53594. /**
  53595. * Constructs a new utility object.
  53596. *
  53597. * @param {WebGPUBackend} backend - The WebGPU backend.
  53598. */
  53599. constructor( backend ) {
  53600. /**
  53601. * A reference to the WebGPU backend.
  53602. *
  53603. * @type {WebGPUBackend}
  53604. */
  53605. this.backend = backend;
  53606. }
  53607. /**
  53608. * Creates the GPU buffer for the given buffer attribute.
  53609. *
  53610. * @param {BufferAttribute} attribute - The buffer attribute.
  53611. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  53612. */
  53613. createAttribute( attribute, usage ) {
  53614. const bufferAttribute = this._getBufferAttribute( attribute );
  53615. const backend = this.backend;
  53616. const bufferData = backend.get( bufferAttribute );
  53617. let buffer = bufferData.buffer;
  53618. if ( buffer === undefined ) {
  53619. const device = backend.device;
  53620. let array = bufferAttribute.array;
  53621. // patch for INT16 and UINT16
  53622. if ( attribute.normalized === false ) {
  53623. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  53624. array = new Int32Array( array );
  53625. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  53626. array = new Uint32Array( array );
  53627. if ( usage & GPUBufferUsage.INDEX ) {
  53628. for ( let i = 0; i < array.length; i ++ ) {
  53629. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  53630. }
  53631. }
  53632. }
  53633. }
  53634. bufferAttribute.array = array;
  53635. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  53636. array = new array.constructor( bufferAttribute.count * 4 );
  53637. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  53638. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  53639. }
  53640. // Update BufferAttribute
  53641. bufferAttribute.itemSize = 4;
  53642. bufferAttribute.array = array;
  53643. bufferData._force3to4BytesAlignment = true;
  53644. }
  53645. // ensure 4 byte alignment
  53646. const byteLength = array.byteLength;
  53647. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  53648. buffer = device.createBuffer( {
  53649. label: bufferAttribute.name,
  53650. size: size,
  53651. usage: usage,
  53652. mappedAtCreation: true
  53653. } );
  53654. new array.constructor( buffer.getMappedRange() ).set( array );
  53655. buffer.unmap();
  53656. bufferData.buffer = buffer;
  53657. }
  53658. }
  53659. /**
  53660. * Updates the GPU buffer of the given buffer attribute.
  53661. *
  53662. * @param {BufferAttribute} attribute - The buffer attribute.
  53663. */
  53664. updateAttribute( attribute ) {
  53665. const bufferAttribute = this._getBufferAttribute( attribute );
  53666. const backend = this.backend;
  53667. const device = backend.device;
  53668. const bufferData = backend.get( bufferAttribute );
  53669. const buffer = backend.get( bufferAttribute ).buffer;
  53670. let array = bufferAttribute.array;
  53671. // if storage buffer ensure 4 byte alignment
  53672. if ( bufferData._force3to4BytesAlignment === true ) {
  53673. array = new array.constructor( bufferAttribute.count * 4 );
  53674. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  53675. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  53676. }
  53677. bufferAttribute.array = array;
  53678. }
  53679. const updateRanges = bufferAttribute.updateRanges;
  53680. if ( updateRanges.length === 0 ) {
  53681. // Not using update ranges
  53682. device.queue.writeBuffer(
  53683. buffer,
  53684. 0,
  53685. array,
  53686. 0
  53687. );
  53688. } else {
  53689. const isTyped = isTypedArray( array );
  53690. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  53691. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  53692. const range = updateRanges[ i ];
  53693. let dataOffset, size;
  53694. if ( bufferData._force3to4BytesAlignment === true ) {
  53695. const vertexStart = Math.floor( range.start / 3 );
  53696. const vertexCount = Math.ceil( range.count / 3 );
  53697. dataOffset = vertexStart * 4 * byteOffsetFactor;
  53698. size = vertexCount * 4 * byteOffsetFactor;
  53699. } else {
  53700. dataOffset = range.start * byteOffsetFactor;
  53701. size = range.count * byteOffsetFactor;
  53702. }
  53703. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  53704. device.queue.writeBuffer(
  53705. buffer,
  53706. bufferOffset,
  53707. array,
  53708. dataOffset,
  53709. size
  53710. );
  53711. }
  53712. bufferAttribute.clearUpdateRanges();
  53713. }
  53714. }
  53715. /**
  53716. * This method creates the vertex buffer layout data which are
  53717. * require when creating a render pipeline for the given render object.
  53718. *
  53719. * @param {RenderObject} renderObject - The render object.
  53720. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  53721. */
  53722. createShaderVertexBuffers( renderObject ) {
  53723. const attributes = renderObject.getAttributes();
  53724. const vertexBuffers = new Map();
  53725. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  53726. const geometryAttribute = attributes[ slot ];
  53727. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  53728. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  53729. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  53730. if ( vertexBufferLayout === undefined ) {
  53731. let arrayStride, stepMode;
  53732. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  53733. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  53734. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  53735. } else {
  53736. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  53737. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  53738. }
  53739. // patch for INT16 and UINT16
  53740. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  53741. arrayStride = 4;
  53742. }
  53743. vertexBufferLayout = {
  53744. arrayStride,
  53745. attributes: [],
  53746. stepMode
  53747. };
  53748. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  53749. }
  53750. const format = this._getVertexFormat( geometryAttribute );
  53751. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  53752. vertexBufferLayout.attributes.push( {
  53753. shaderLocation: slot,
  53754. offset,
  53755. format
  53756. } );
  53757. }
  53758. return Array.from( vertexBuffers.values() );
  53759. }
  53760. /**
  53761. * Destroys the GPU buffer of the given buffer attribute.
  53762. *
  53763. * @param {BufferAttribute} attribute - The buffer attribute.
  53764. */
  53765. destroyAttribute( attribute ) {
  53766. const backend = this.backend;
  53767. const data = backend.get( this._getBufferAttribute( attribute ) );
  53768. data.buffer.destroy();
  53769. backend.delete( attribute );
  53770. }
  53771. /**
  53772. * This method performs a readback operation by moving buffer data from
  53773. * a storage buffer attribute from the GPU to the CPU.
  53774. *
  53775. * @async
  53776. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  53777. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  53778. */
  53779. async getArrayBufferAsync( attribute ) {
  53780. const backend = this.backend;
  53781. const device = backend.device;
  53782. const data = backend.get( this._getBufferAttribute( attribute ) );
  53783. const bufferGPU = data.buffer;
  53784. const size = bufferGPU.size;
  53785. const readBufferGPU = device.createBuffer( {
  53786. label: `${ attribute.name }_readback`,
  53787. size,
  53788. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  53789. } );
  53790. const cmdEncoder = device.createCommandEncoder( {
  53791. label: `readback_encoder_${ attribute.name }`
  53792. } );
  53793. cmdEncoder.copyBufferToBuffer(
  53794. bufferGPU,
  53795. 0,
  53796. readBufferGPU,
  53797. 0,
  53798. size
  53799. );
  53800. const gpuCommands = cmdEncoder.finish();
  53801. device.queue.submit( [ gpuCommands ] );
  53802. await readBufferGPU.mapAsync( GPUMapMode.READ );
  53803. const arrayBuffer = readBufferGPU.getMappedRange();
  53804. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  53805. readBufferGPU.unmap();
  53806. return dstBuffer.buffer;
  53807. }
  53808. /**
  53809. * Returns the vertex format of the given buffer attribute.
  53810. *
  53811. * @private
  53812. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  53813. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  53814. */
  53815. _getVertexFormat( geometryAttribute ) {
  53816. const { itemSize, normalized } = geometryAttribute;
  53817. const ArrayType = geometryAttribute.array.constructor;
  53818. const AttributeType = geometryAttribute.constructor;
  53819. let format;
  53820. if ( itemSize === 1 ) {
  53821. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  53822. } else {
  53823. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  53824. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  53825. if ( prefix ) {
  53826. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  53827. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  53828. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  53829. if ( paddedItemSize % 1 ) {
  53830. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  53831. }
  53832. format = `${prefix}x${paddedItemSize}`;
  53833. }
  53834. }
  53835. if ( ! format ) {
  53836. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  53837. }
  53838. return format;
  53839. }
  53840. /**
  53841. * Utility method for handling interleaved buffer attributes correctly.
  53842. * To process them, their `InterleavedBuffer` is returned.
  53843. *
  53844. * @private
  53845. * @param {BufferAttribute} attribute - The attribute.
  53846. * @return {BufferAttribute|InterleavedBuffer}
  53847. */
  53848. _getBufferAttribute( attribute ) {
  53849. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  53850. return attribute;
  53851. }
  53852. }
  53853. /**
  53854. * A WebGPU backend utility module for managing bindings.
  53855. *
  53856. * When reading the documentation it's helpful to keep in mind that
  53857. * all class definitions starting with 'GPU*' are modules from the
  53858. * WebGPU API. So for example `BindGroup` is a class from the engine
  53859. * whereas `GPUBindGroup` is a class from WebGPU.
  53860. *
  53861. * @private
  53862. */
  53863. class WebGPUBindingUtils {
  53864. /**
  53865. * Constructs a new utility object.
  53866. *
  53867. * @param {WebGPUBackend} backend - The WebGPU backend.
  53868. */
  53869. constructor( backend ) {
  53870. /**
  53871. * A reference to the WebGPU backend.
  53872. *
  53873. * @type {WebGPUBackend}
  53874. */
  53875. this.backend = backend;
  53876. /**
  53877. * A cache for managing bind group layouts.
  53878. *
  53879. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  53880. */
  53881. this.bindGroupLayoutCache = new WeakMap();
  53882. }
  53883. /**
  53884. * Creates a GPU bind group layout for the given bind group.
  53885. *
  53886. * @param {BindGroup} bindGroup - The bind group.
  53887. * @return {GPUBindGroupLayout} The GPU bind group layout.
  53888. */
  53889. createBindingsLayout( bindGroup ) {
  53890. const backend = this.backend;
  53891. const device = backend.device;
  53892. const entries = [];
  53893. let index = 0;
  53894. for ( const binding of bindGroup.bindings ) {
  53895. const bindingGPU = {
  53896. binding: index ++,
  53897. visibility: binding.visibility
  53898. };
  53899. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  53900. const buffer = {}; // GPUBufferBindingLayout
  53901. if ( binding.isStorageBuffer ) {
  53902. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  53903. // compute
  53904. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  53905. buffer.type = GPUBufferBindingType.Storage;
  53906. } else {
  53907. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  53908. }
  53909. } else {
  53910. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  53911. }
  53912. }
  53913. bindingGPU.buffer = buffer;
  53914. } else if ( binding.isSampledTexture && binding.store ) {
  53915. const storageTexture = {}; // GPUStorageTextureBindingLayout
  53916. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  53917. const access = binding.access;
  53918. if ( access === NodeAccess.READ_WRITE ) {
  53919. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  53920. } else if ( access === NodeAccess.WRITE_ONLY ) {
  53921. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  53922. } else {
  53923. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  53924. }
  53925. if ( binding.texture.isArrayTexture ) {
  53926. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  53927. } else if ( binding.texture.is3DTexture ) {
  53928. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  53929. }
  53930. bindingGPU.storageTexture = storageTexture;
  53931. } else if ( binding.isSampledTexture ) {
  53932. const texture = {}; // GPUTextureBindingLayout
  53933. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  53934. if ( primarySamples > 1 ) {
  53935. texture.multisampled = true;
  53936. if ( ! binding.texture.isDepthTexture ) {
  53937. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  53938. }
  53939. }
  53940. if ( binding.texture.isDepthTexture ) {
  53941. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  53942. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  53943. } else {
  53944. texture.sampleType = GPUTextureSampleType.Depth;
  53945. }
  53946. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  53947. const type = binding.texture.type;
  53948. if ( type === IntType ) {
  53949. texture.sampleType = GPUTextureSampleType.SInt;
  53950. } else if ( type === UnsignedIntType ) {
  53951. texture.sampleType = GPUTextureSampleType.UInt;
  53952. } else if ( type === FloatType ) {
  53953. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  53954. texture.sampleType = GPUTextureSampleType.Float;
  53955. } else {
  53956. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  53957. }
  53958. }
  53959. }
  53960. if ( binding.isSampledCubeTexture ) {
  53961. texture.viewDimension = GPUTextureViewDimension.Cube;
  53962. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  53963. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  53964. } else if ( binding.isSampledTexture3D ) {
  53965. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  53966. }
  53967. bindingGPU.texture = texture;
  53968. } else if ( binding.isSampler ) {
  53969. const sampler = {}; // GPUSamplerBindingLayout
  53970. if ( binding.texture.isDepthTexture ) {
  53971. if ( binding.texture.compareFunction !== null ) {
  53972. sampler.type = GPUSamplerBindingType.Comparison;
  53973. } else if ( backend.compatibilityMode ) {
  53974. sampler.type = GPUSamplerBindingType.NonFiltering;
  53975. }
  53976. }
  53977. bindingGPU.sampler = sampler;
  53978. } else {
  53979. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  53980. }
  53981. entries.push( bindingGPU );
  53982. }
  53983. return device.createBindGroupLayout( { entries } );
  53984. }
  53985. /**
  53986. * Creates bindings from the given bind group definition.
  53987. *
  53988. * @param {BindGroup} bindGroup - The bind group.
  53989. * @param {Array<BindGroup>} bindings - Array of bind groups.
  53990. * @param {number} cacheIndex - The cache index.
  53991. * @param {number} version - The version.
  53992. */
  53993. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  53994. const { backend, bindGroupLayoutCache } = this;
  53995. const bindingsData = backend.get( bindGroup );
  53996. // setup (static) binding layout and (dynamic) binding group
  53997. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  53998. if ( bindLayoutGPU === undefined ) {
  53999. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  54000. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  54001. }
  54002. let bindGroupGPU;
  54003. if ( cacheIndex > 0 ) {
  54004. if ( bindingsData.groups === undefined ) {
  54005. bindingsData.groups = [];
  54006. bindingsData.versions = [];
  54007. }
  54008. if ( bindingsData.versions[ cacheIndex ] === version ) {
  54009. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  54010. }
  54011. }
  54012. if ( bindGroupGPU === undefined ) {
  54013. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  54014. if ( cacheIndex > 0 ) {
  54015. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  54016. bindingsData.versions[ cacheIndex ] = version;
  54017. }
  54018. }
  54019. bindingsData.group = bindGroupGPU;
  54020. bindingsData.layout = bindLayoutGPU;
  54021. }
  54022. /**
  54023. * Updates a buffer binding.
  54024. *
  54025. * @param {Buffer} binding - The buffer binding to update.
  54026. */
  54027. updateBinding( binding ) {
  54028. const backend = this.backend;
  54029. const device = backend.device;
  54030. const array = binding.buffer; // cpu
  54031. const buffer = backend.get( binding ).buffer; // gpu
  54032. const updateRanges = binding.updateRanges;
  54033. if ( updateRanges.length === 0 ) {
  54034. device.queue.writeBuffer(
  54035. buffer,
  54036. 0,
  54037. array,
  54038. 0
  54039. );
  54040. } else {
  54041. const isTyped = isTypedArray( array );
  54042. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  54043. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  54044. const range = updateRanges[ i ];
  54045. const dataOffset = range.start * byteOffsetFactor;
  54046. const size = range.count * byteOffsetFactor;
  54047. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  54048. device.queue.writeBuffer(
  54049. buffer,
  54050. bufferOffset,
  54051. array,
  54052. dataOffset,
  54053. size
  54054. );
  54055. }
  54056. binding.clearUpdateRanges();
  54057. }
  54058. }
  54059. /**
  54060. * Creates a GPU bind group for the camera index.
  54061. *
  54062. * @param {Uint32Array} data - The index data.
  54063. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  54064. * @return {GPUBindGroup} The GPU bind group.
  54065. */
  54066. createBindGroupIndex( data, layout ) {
  54067. const backend = this.backend;
  54068. const device = backend.device;
  54069. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  54070. const index = data[ 0 ];
  54071. const buffer = device.createBuffer( {
  54072. label: 'bindingCameraIndex_' + index,
  54073. size: 16, // uint(4) * 4
  54074. usage: usage
  54075. } );
  54076. device.queue.writeBuffer( buffer, 0, data, 0 );
  54077. const entries = [ { binding: 0, resource: { buffer } } ];
  54078. return device.createBindGroup( {
  54079. label: 'bindGroupCameraIndex_' + index,
  54080. layout,
  54081. entries
  54082. } );
  54083. }
  54084. /**
  54085. * Creates a GPU bind group for the given bind group and GPU layout.
  54086. *
  54087. * @param {BindGroup} bindGroup - The bind group.
  54088. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  54089. * @return {GPUBindGroup} The GPU bind group.
  54090. */
  54091. createBindGroup( bindGroup, layoutGPU ) {
  54092. const backend = this.backend;
  54093. const device = backend.device;
  54094. let bindingPoint = 0;
  54095. const entriesGPU = [];
  54096. for ( const binding of bindGroup.bindings ) {
  54097. if ( binding.isUniformBuffer ) {
  54098. const bindingData = backend.get( binding );
  54099. if ( bindingData.buffer === undefined ) {
  54100. const byteLength = binding.byteLength;
  54101. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  54102. const visibilities = [];
  54103. if ( binding.visibility & GPUShaderStage.VERTEX ) {
  54104. visibilities.push( 'vertex' );
  54105. }
  54106. if ( binding.visibility & GPUShaderStage.FRAGMENT ) {
  54107. visibilities.push( 'fragment' );
  54108. }
  54109. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  54110. visibilities.push( 'compute' );
  54111. }
  54112. const bufferVisibility = `(${visibilities.join( ',' )})`;
  54113. const bufferGPU = device.createBuffer( {
  54114. label: `bindingBuffer${binding.id}_${binding.name}_${bufferVisibility}`,
  54115. size: byteLength,
  54116. usage: usage
  54117. } );
  54118. bindingData.buffer = bufferGPU;
  54119. }
  54120. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  54121. } else if ( binding.isStorageBuffer ) {
  54122. const bindingData = backend.get( binding );
  54123. if ( bindingData.buffer === undefined ) {
  54124. const attribute = binding.attribute;
  54125. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  54126. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  54127. bindingData.buffer = backend.get( attribute ).buffer;
  54128. }
  54129. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  54130. } else if ( binding.isSampledTexture ) {
  54131. const textureData = backend.get( binding.texture );
  54132. let resourceGPU;
  54133. if ( textureData.externalTexture !== undefined ) {
  54134. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  54135. } else {
  54136. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  54137. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  54138. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  54139. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  54140. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  54141. }
  54142. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  54143. resourceGPU = textureData[ propertyName ];
  54144. if ( resourceGPU === undefined ) {
  54145. const aspectGPU = GPUTextureAspect.All;
  54146. let dimensionViewGPU;
  54147. if ( binding.isSampledCubeTexture ) {
  54148. dimensionViewGPU = GPUTextureViewDimension.Cube;
  54149. } else if ( binding.isSampledTexture3D ) {
  54150. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  54151. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  54152. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  54153. } else {
  54154. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  54155. }
  54156. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount, baseMipLevel } );
  54157. }
  54158. }
  54159. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  54160. } else if ( binding.isSampler ) {
  54161. const textureGPU = backend.get( binding.texture );
  54162. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  54163. }
  54164. bindingPoint ++;
  54165. }
  54166. return device.createBindGroup( {
  54167. label: 'bindGroup_' + bindGroup.name,
  54168. layout: layoutGPU,
  54169. entries: entriesGPU
  54170. } );
  54171. }
  54172. }
  54173. /**
  54174. * A WebGPU backend utility module for managing pipelines.
  54175. *
  54176. * @private
  54177. */
  54178. class WebGPUPipelineUtils {
  54179. /**
  54180. * Constructs a new utility object.
  54181. *
  54182. * @param {WebGPUBackend} backend - The WebGPU backend.
  54183. */
  54184. constructor( backend ) {
  54185. /**
  54186. * A reference to the WebGPU backend.
  54187. *
  54188. * @type {WebGPUBackend}
  54189. */
  54190. this.backend = backend;
  54191. /**
  54192. * A Weak Map that tracks the active pipeline for render or compute passes.
  54193. *
  54194. * @private
  54195. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  54196. */
  54197. this._activePipelines = new WeakMap();
  54198. }
  54199. /**
  54200. * Sets the given pipeline for the given pass. The method makes sure to only set the
  54201. * pipeline when necessary.
  54202. *
  54203. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  54204. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  54205. */
  54206. setPipeline( pass, pipeline ) {
  54207. const currentPipeline = this._activePipelines.get( pass );
  54208. if ( currentPipeline !== pipeline ) {
  54209. pass.setPipeline( pipeline );
  54210. this._activePipelines.set( pass, pipeline );
  54211. }
  54212. }
  54213. /**
  54214. * Returns the sample count derived from the given render context.
  54215. *
  54216. * @private
  54217. * @param {RenderContext} renderContext - The render context.
  54218. * @return {number} The sample count.
  54219. */
  54220. _getSampleCount( renderContext ) {
  54221. return this.backend.utils.getSampleCountRenderContext( renderContext );
  54222. }
  54223. /**
  54224. * Creates a render pipeline for the given render object.
  54225. *
  54226. * @param {RenderObject} renderObject - The render object.
  54227. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  54228. */
  54229. createRenderPipeline( renderObject, promises ) {
  54230. const { object, material, geometry, pipeline } = renderObject;
  54231. const { vertexProgram, fragmentProgram } = pipeline;
  54232. const backend = this.backend;
  54233. const device = backend.device;
  54234. const utils = backend.utils;
  54235. const pipelineData = backend.get( pipeline );
  54236. // bind group layouts
  54237. const bindGroupLayouts = [];
  54238. for ( const bindGroup of renderObject.getBindings() ) {
  54239. const bindingsData = backend.get( bindGroup );
  54240. bindGroupLayouts.push( bindingsData.layout );
  54241. }
  54242. // vertex buffers
  54243. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  54244. // blending
  54245. let blending;
  54246. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  54247. blending = this._getBlending( material );
  54248. }
  54249. // stencil
  54250. let stencilFront = {};
  54251. if ( material.stencilWrite === true ) {
  54252. stencilFront = {
  54253. compare: this._getStencilCompare( material ),
  54254. failOp: this._getStencilOperation( material.stencilFail ),
  54255. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  54256. passOp: this._getStencilOperation( material.stencilZPass )
  54257. };
  54258. }
  54259. const colorWriteMask = this._getColorWriteMask( material );
  54260. const targets = [];
  54261. if ( renderObject.context.textures !== null ) {
  54262. const textures = renderObject.context.textures;
  54263. for ( let i = 0; i < textures.length; i ++ ) {
  54264. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  54265. if ( i === 0 ) {
  54266. targets.push( {
  54267. format: colorFormat,
  54268. blend: blending,
  54269. writeMask: colorWriteMask
  54270. } );
  54271. } else {
  54272. targets.push( {
  54273. format: colorFormat,
  54274. writeMask: colorWriteMask
  54275. } );
  54276. }
  54277. }
  54278. } else {
  54279. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  54280. targets.push( {
  54281. format: colorFormat,
  54282. blend: blending,
  54283. writeMask: colorWriteMask
  54284. } );
  54285. }
  54286. const vertexModule = backend.get( vertexProgram ).module;
  54287. const fragmentModule = backend.get( fragmentProgram ).module;
  54288. const primitiveState = this._getPrimitiveState( object, geometry, material );
  54289. const depthCompare = this._getDepthCompare( material );
  54290. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  54291. const sampleCount = this._getSampleCount( renderObject.context );
  54292. const pipelineDescriptor = {
  54293. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  54294. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  54295. fragment: Object.assign( {}, fragmentModule, { targets } ),
  54296. primitive: primitiveState,
  54297. multisample: {
  54298. count: sampleCount,
  54299. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  54300. },
  54301. layout: device.createPipelineLayout( {
  54302. bindGroupLayouts
  54303. } )
  54304. };
  54305. const depthStencil = {};
  54306. const renderDepth = renderObject.context.depth;
  54307. const renderStencil = renderObject.context.stencil;
  54308. if ( renderDepth === true || renderStencil === true ) {
  54309. if ( renderDepth === true ) {
  54310. depthStencil.format = depthStencilFormat;
  54311. depthStencil.depthWriteEnabled = material.depthWrite;
  54312. depthStencil.depthCompare = depthCompare;
  54313. }
  54314. if ( renderStencil === true ) {
  54315. depthStencil.stencilFront = stencilFront;
  54316. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  54317. depthStencil.stencilReadMask = material.stencilFuncMask;
  54318. depthStencil.stencilWriteMask = material.stencilWriteMask;
  54319. }
  54320. if ( material.polygonOffset === true ) {
  54321. depthStencil.depthBias = material.polygonOffsetUnits;
  54322. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  54323. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  54324. }
  54325. pipelineDescriptor.depthStencil = depthStencil;
  54326. }
  54327. // create pipeline
  54328. device.pushErrorScope( 'validation' );
  54329. if ( promises === null ) {
  54330. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  54331. device.popErrorScope().then( ( err ) => {
  54332. if ( err !== null ) {
  54333. pipelineData.error = true;
  54334. error( err.message );
  54335. }
  54336. } );
  54337. } else {
  54338. const p = new Promise( async ( resolve /*, reject*/ ) => {
  54339. try {
  54340. pipelineData.pipeline = await device.createRenderPipelineAsync( pipelineDescriptor );
  54341. } catch ( err ) { }
  54342. const errorScope = await device.popErrorScope();
  54343. if ( errorScope !== null ) {
  54344. pipelineData.error = true;
  54345. error( errorScope.message );
  54346. }
  54347. resolve();
  54348. } );
  54349. promises.push( p );
  54350. }
  54351. }
  54352. /**
  54353. * Creates GPU render bundle encoder for the given render context.
  54354. *
  54355. * @param {RenderContext} renderContext - The render context.
  54356. * @param {?string} [label='renderBundleEncoder'] - The label.
  54357. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  54358. */
  54359. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  54360. const backend = this.backend;
  54361. const { utils, device } = backend;
  54362. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  54363. const colorFormats = utils.getCurrentColorFormats( renderContext );
  54364. const sampleCount = this._getSampleCount( renderContext );
  54365. const descriptor = {
  54366. label,
  54367. colorFormats,
  54368. depthStencilFormat,
  54369. sampleCount
  54370. };
  54371. return device.createRenderBundleEncoder( descriptor );
  54372. }
  54373. /**
  54374. * Creates a compute pipeline for the given compute node.
  54375. *
  54376. * @param {ComputePipeline} pipeline - The compute pipeline.
  54377. * @param {Array<BindGroup>} bindings - The bindings.
  54378. */
  54379. createComputePipeline( pipeline, bindings ) {
  54380. const backend = this.backend;
  54381. const device = backend.device;
  54382. const computeProgram = backend.get( pipeline.computeProgram ).module;
  54383. const pipelineGPU = backend.get( pipeline );
  54384. // bind group layouts
  54385. const bindGroupLayouts = [];
  54386. for ( const bindingsGroup of bindings ) {
  54387. const bindingsData = backend.get( bindingsGroup );
  54388. bindGroupLayouts.push( bindingsData.layout );
  54389. }
  54390. pipelineGPU.pipeline = device.createComputePipeline( {
  54391. compute: computeProgram,
  54392. layout: device.createPipelineLayout( {
  54393. bindGroupLayouts
  54394. } )
  54395. } );
  54396. }
  54397. /**
  54398. * Returns the blending state as a descriptor object required
  54399. * for the pipeline creation.
  54400. *
  54401. * @private
  54402. * @param {Material} material - The material.
  54403. * @return {Object} The blending state.
  54404. */
  54405. _getBlending( material ) {
  54406. let color, alpha;
  54407. const blending = material.blending;
  54408. const blendSrc = material.blendSrc;
  54409. const blendDst = material.blendDst;
  54410. const blendEquation = material.blendEquation;
  54411. if ( blending === CustomBlending ) {
  54412. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  54413. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  54414. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  54415. color = {
  54416. srcFactor: this._getBlendFactor( blendSrc ),
  54417. dstFactor: this._getBlendFactor( blendDst ),
  54418. operation: this._getBlendOperation( blendEquation )
  54419. };
  54420. alpha = {
  54421. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  54422. dstFactor: this._getBlendFactor( blendDstAlpha ),
  54423. operation: this._getBlendOperation( blendEquationAlpha )
  54424. };
  54425. } else {
  54426. const premultipliedAlpha = material.premultipliedAlpha;
  54427. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  54428. color = {
  54429. srcFactor: srcRGB,
  54430. dstFactor: dstRGB,
  54431. operation: GPUBlendOperation.Add
  54432. };
  54433. alpha = {
  54434. srcFactor: srcAlpha,
  54435. dstFactor: dstAlpha,
  54436. operation: GPUBlendOperation.Add
  54437. };
  54438. };
  54439. if ( premultipliedAlpha ) {
  54440. switch ( blending ) {
  54441. case NormalBlending:
  54442. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  54443. break;
  54444. case AdditiveBlending:
  54445. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  54446. break;
  54447. case SubtractiveBlending:
  54448. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  54449. break;
  54450. case MultiplyBlending:
  54451. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  54452. break;
  54453. }
  54454. } else {
  54455. switch ( blending ) {
  54456. case NormalBlending:
  54457. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  54458. break;
  54459. case AdditiveBlending:
  54460. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  54461. break;
  54462. case SubtractiveBlending:
  54463. error( 'WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  54464. break;
  54465. case MultiplyBlending:
  54466. error( 'WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  54467. break;
  54468. }
  54469. }
  54470. }
  54471. if ( color !== undefined && alpha !== undefined ) {
  54472. return { color, alpha };
  54473. } else {
  54474. error( 'WebGPURenderer: Invalid blending: ', blending );
  54475. }
  54476. }
  54477. /**
  54478. * Returns the GPU blend factor which is required for the pipeline creation.
  54479. *
  54480. * @private
  54481. * @param {number} blend - The blend factor as a three.js constant.
  54482. * @return {string} The GPU blend factor.
  54483. */
  54484. _getBlendFactor( blend ) {
  54485. let blendFactor;
  54486. switch ( blend ) {
  54487. case ZeroFactor:
  54488. blendFactor = GPUBlendFactor.Zero;
  54489. break;
  54490. case OneFactor:
  54491. blendFactor = GPUBlendFactor.One;
  54492. break;
  54493. case SrcColorFactor:
  54494. blendFactor = GPUBlendFactor.Src;
  54495. break;
  54496. case OneMinusSrcColorFactor:
  54497. blendFactor = GPUBlendFactor.OneMinusSrc;
  54498. break;
  54499. case SrcAlphaFactor:
  54500. blendFactor = GPUBlendFactor.SrcAlpha;
  54501. break;
  54502. case OneMinusSrcAlphaFactor:
  54503. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  54504. break;
  54505. case DstColorFactor:
  54506. blendFactor = GPUBlendFactor.Dst;
  54507. break;
  54508. case OneMinusDstColorFactor:
  54509. blendFactor = GPUBlendFactor.OneMinusDst;
  54510. break;
  54511. case DstAlphaFactor:
  54512. blendFactor = GPUBlendFactor.DstAlpha;
  54513. break;
  54514. case OneMinusDstAlphaFactor:
  54515. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  54516. break;
  54517. case SrcAlphaSaturateFactor:
  54518. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  54519. break;
  54520. case BlendColorFactor:
  54521. blendFactor = GPUBlendFactor.Constant;
  54522. break;
  54523. case OneMinusBlendColorFactor:
  54524. blendFactor = GPUBlendFactor.OneMinusConstant;
  54525. break;
  54526. default:
  54527. error( 'WebGPURenderer: Blend factor not supported.', blend );
  54528. }
  54529. return blendFactor;
  54530. }
  54531. /**
  54532. * Returns the GPU stencil compare function which is required for the pipeline creation.
  54533. *
  54534. * @private
  54535. * @param {Material} material - The material.
  54536. * @return {string} The GPU stencil compare function.
  54537. */
  54538. _getStencilCompare( material ) {
  54539. let stencilCompare;
  54540. const stencilFunc = material.stencilFunc;
  54541. switch ( stencilFunc ) {
  54542. case NeverStencilFunc:
  54543. stencilCompare = GPUCompareFunction.Never;
  54544. break;
  54545. case AlwaysStencilFunc:
  54546. stencilCompare = GPUCompareFunction.Always;
  54547. break;
  54548. case LessStencilFunc:
  54549. stencilCompare = GPUCompareFunction.Less;
  54550. break;
  54551. case LessEqualStencilFunc:
  54552. stencilCompare = GPUCompareFunction.LessEqual;
  54553. break;
  54554. case EqualStencilFunc:
  54555. stencilCompare = GPUCompareFunction.Equal;
  54556. break;
  54557. case GreaterEqualStencilFunc:
  54558. stencilCompare = GPUCompareFunction.GreaterEqual;
  54559. break;
  54560. case GreaterStencilFunc:
  54561. stencilCompare = GPUCompareFunction.Greater;
  54562. break;
  54563. case NotEqualStencilFunc:
  54564. stencilCompare = GPUCompareFunction.NotEqual;
  54565. break;
  54566. default:
  54567. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  54568. }
  54569. return stencilCompare;
  54570. }
  54571. /**
  54572. * Returns the GPU stencil operation which is required for the pipeline creation.
  54573. *
  54574. * @private
  54575. * @param {number} op - A three.js constant defining the stencil operation.
  54576. * @return {string} The GPU stencil operation.
  54577. */
  54578. _getStencilOperation( op ) {
  54579. let stencilOperation;
  54580. switch ( op ) {
  54581. case KeepStencilOp:
  54582. stencilOperation = GPUStencilOperation.Keep;
  54583. break;
  54584. case ZeroStencilOp:
  54585. stencilOperation = GPUStencilOperation.Zero;
  54586. break;
  54587. case ReplaceStencilOp:
  54588. stencilOperation = GPUStencilOperation.Replace;
  54589. break;
  54590. case InvertStencilOp:
  54591. stencilOperation = GPUStencilOperation.Invert;
  54592. break;
  54593. case IncrementStencilOp:
  54594. stencilOperation = GPUStencilOperation.IncrementClamp;
  54595. break;
  54596. case DecrementStencilOp:
  54597. stencilOperation = GPUStencilOperation.DecrementClamp;
  54598. break;
  54599. case IncrementWrapStencilOp:
  54600. stencilOperation = GPUStencilOperation.IncrementWrap;
  54601. break;
  54602. case DecrementWrapStencilOp:
  54603. stencilOperation = GPUStencilOperation.DecrementWrap;
  54604. break;
  54605. default:
  54606. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  54607. }
  54608. return stencilOperation;
  54609. }
  54610. /**
  54611. * Returns the GPU blend operation which is required for the pipeline creation.
  54612. *
  54613. * @private
  54614. * @param {number} blendEquation - A three.js constant defining the blend equation.
  54615. * @return {string} The GPU blend operation.
  54616. */
  54617. _getBlendOperation( blendEquation ) {
  54618. let blendOperation;
  54619. switch ( blendEquation ) {
  54620. case AddEquation:
  54621. blendOperation = GPUBlendOperation.Add;
  54622. break;
  54623. case SubtractEquation:
  54624. blendOperation = GPUBlendOperation.Subtract;
  54625. break;
  54626. case ReverseSubtractEquation:
  54627. blendOperation = GPUBlendOperation.ReverseSubtract;
  54628. break;
  54629. case MinEquation:
  54630. blendOperation = GPUBlendOperation.Min;
  54631. break;
  54632. case MaxEquation:
  54633. blendOperation = GPUBlendOperation.Max;
  54634. break;
  54635. default:
  54636. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  54637. }
  54638. return blendOperation;
  54639. }
  54640. /**
  54641. * Returns the primitive state as a descriptor object required
  54642. * for the pipeline creation.
  54643. *
  54644. * @private
  54645. * @param {Object3D} object - The 3D object.
  54646. * @param {BufferGeometry} geometry - The geometry.
  54647. * @param {Material} material - The material.
  54648. * @return {Object} The primitive state.
  54649. */
  54650. _getPrimitiveState( object, geometry, material ) {
  54651. const descriptor = {};
  54652. const utils = this.backend.utils;
  54653. //
  54654. descriptor.topology = utils.getPrimitiveTopology( object, material );
  54655. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  54656. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  54657. }
  54658. //
  54659. let flipSided = ( material.side === BackSide );
  54660. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  54661. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  54662. //
  54663. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  54664. return descriptor;
  54665. }
  54666. /**
  54667. * Returns the GPU color write mask which is required for the pipeline creation.
  54668. *
  54669. * @private
  54670. * @param {Material} material - The material.
  54671. * @return {number} The GPU color write mask.
  54672. */
  54673. _getColorWriteMask( material ) {
  54674. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  54675. }
  54676. /**
  54677. * Returns the GPU depth compare function which is required for the pipeline creation.
  54678. *
  54679. * @private
  54680. * @param {Material} material - The material.
  54681. * @return {string} The GPU depth compare function.
  54682. */
  54683. _getDepthCompare( material ) {
  54684. let depthCompare;
  54685. if ( material.depthTest === false ) {
  54686. depthCompare = GPUCompareFunction.Always;
  54687. } else {
  54688. const depthFunc = material.depthFunc;
  54689. switch ( depthFunc ) {
  54690. case NeverDepth:
  54691. depthCompare = GPUCompareFunction.Never;
  54692. break;
  54693. case AlwaysDepth:
  54694. depthCompare = GPUCompareFunction.Always;
  54695. break;
  54696. case LessDepth:
  54697. depthCompare = GPUCompareFunction.Less;
  54698. break;
  54699. case LessEqualDepth:
  54700. depthCompare = GPUCompareFunction.LessEqual;
  54701. break;
  54702. case EqualDepth:
  54703. depthCompare = GPUCompareFunction.Equal;
  54704. break;
  54705. case GreaterEqualDepth:
  54706. depthCompare = GPUCompareFunction.GreaterEqual;
  54707. break;
  54708. case GreaterDepth:
  54709. depthCompare = GPUCompareFunction.Greater;
  54710. break;
  54711. case NotEqualDepth:
  54712. depthCompare = GPUCompareFunction.NotEqual;
  54713. break;
  54714. default:
  54715. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  54716. }
  54717. }
  54718. return depthCompare;
  54719. }
  54720. }
  54721. /**
  54722. * Manages a pool of WebGPU timestamp queries for performance measurement.
  54723. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  54724. *
  54725. * @augments TimestampQueryPool
  54726. */
  54727. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  54728. /**
  54729. * Creates a new WebGPU timestamp query pool.
  54730. *
  54731. * @param {GPUDevice} device - The WebGPU device to create queries on.
  54732. * @param {string} type - The type identifier for this query pool.
  54733. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  54734. */
  54735. constructor( device, type, maxQueries = 2048 ) {
  54736. super( maxQueries );
  54737. this.device = device;
  54738. this.type = type;
  54739. this.querySet = this.device.createQuerySet( {
  54740. type: 'timestamp',
  54741. count: this.maxQueries,
  54742. label: `queryset_global_timestamp_${type}`
  54743. } );
  54744. const bufferSize = this.maxQueries * 8;
  54745. this.resolveBuffer = this.device.createBuffer( {
  54746. label: `buffer_timestamp_resolve_${type}`,
  54747. size: bufferSize,
  54748. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  54749. } );
  54750. this.resultBuffer = this.device.createBuffer( {
  54751. label: `buffer_timestamp_result_${type}`,
  54752. size: bufferSize,
  54753. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  54754. } );
  54755. }
  54756. /**
  54757. * Allocates a pair of queries for a given render context.
  54758. *
  54759. * @param {string} uid - A unique identifier for the render context.
  54760. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  54761. */
  54762. allocateQueriesForContext( uid ) {
  54763. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  54764. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  54765. 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() } ).` );
  54766. return null;
  54767. }
  54768. const baseOffset = this.currentQueryIndex;
  54769. this.currentQueryIndex += 2;
  54770. this.queryOffsets.set( uid, baseOffset );
  54771. return baseOffset;
  54772. }
  54773. /**
  54774. * Asynchronously resolves all pending queries and returns the total duration.
  54775. * If there's already a pending resolve operation, returns that promise instead.
  54776. *
  54777. * @async
  54778. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  54779. */
  54780. async resolveQueriesAsync() {
  54781. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  54782. return this.lastValue;
  54783. }
  54784. if ( this.pendingResolve ) {
  54785. return this.pendingResolve;
  54786. }
  54787. this.pendingResolve = this._resolveQueries();
  54788. try {
  54789. const result = await this.pendingResolve;
  54790. return result;
  54791. } finally {
  54792. this.pendingResolve = null;
  54793. }
  54794. }
  54795. /**
  54796. * Internal method to resolve queries and calculate total duration.
  54797. *
  54798. * @async
  54799. * @private
  54800. * @returns {Promise<number>} The total duration in milliseconds.
  54801. */
  54802. async _resolveQueries() {
  54803. if ( this.isDisposed ) {
  54804. return this.lastValue;
  54805. }
  54806. try {
  54807. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  54808. return this.lastValue;
  54809. }
  54810. const currentOffsets = new Map( this.queryOffsets );
  54811. const queryCount = this.currentQueryIndex;
  54812. const bytesUsed = queryCount * 8;
  54813. // Reset state before GPU work
  54814. this.currentQueryIndex = 0;
  54815. this.queryOffsets.clear();
  54816. const commandEncoder = this.device.createCommandEncoder();
  54817. commandEncoder.resolveQuerySet(
  54818. this.querySet,
  54819. 0,
  54820. queryCount,
  54821. this.resolveBuffer,
  54822. 0
  54823. );
  54824. commandEncoder.copyBufferToBuffer(
  54825. this.resolveBuffer,
  54826. 0,
  54827. this.resultBuffer,
  54828. 0,
  54829. bytesUsed
  54830. );
  54831. const commandBuffer = commandEncoder.finish();
  54832. this.device.queue.submit( [ commandBuffer ] );
  54833. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  54834. return this.lastValue;
  54835. }
  54836. // Create and track the mapping operation
  54837. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  54838. if ( this.isDisposed ) {
  54839. if ( this.resultBuffer.mapState === 'mapped' ) {
  54840. this.resultBuffer.unmap();
  54841. }
  54842. return this.lastValue;
  54843. }
  54844. //
  54845. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  54846. const framesDuration = {};
  54847. const frames = [];
  54848. for ( const [ uid, baseOffset ] of currentOffsets ) {
  54849. const match = uid.match( /^(.*):f(\d+)$/ );
  54850. const frame = parseInt( match[ 2 ] );
  54851. if ( frames.includes( frame ) === false ) {
  54852. frames.push( frame );
  54853. }
  54854. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  54855. const startTime = times[ baseOffset ];
  54856. const endTime = times[ baseOffset + 1 ];
  54857. const duration = Number( endTime - startTime ) / 1e6;
  54858. this.timestamps.set( uid, duration );
  54859. framesDuration[ frame ] += duration;
  54860. }
  54861. // Return the total duration of the last frame
  54862. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  54863. this.resultBuffer.unmap();
  54864. this.lastValue = totalDuration;
  54865. this.frames = frames;
  54866. return totalDuration;
  54867. } catch ( e ) {
  54868. error( 'Error resolving queries:', e );
  54869. if ( this.resultBuffer.mapState === 'mapped' ) {
  54870. this.resultBuffer.unmap();
  54871. }
  54872. return this.lastValue;
  54873. }
  54874. }
  54875. /**
  54876. * Dispose of the query pool.
  54877. *
  54878. * @async
  54879. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  54880. */
  54881. async dispose() {
  54882. if ( this.isDisposed ) {
  54883. return;
  54884. }
  54885. this.isDisposed = true;
  54886. // Wait for pending resolve operation
  54887. if ( this.pendingResolve ) {
  54888. try {
  54889. await this.pendingResolve;
  54890. } catch ( e ) {
  54891. error( 'Error waiting for pending resolve:', e );
  54892. }
  54893. }
  54894. // Ensure buffer is unmapped before destroying
  54895. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  54896. try {
  54897. this.resultBuffer.unmap();
  54898. } catch ( e ) {
  54899. error( 'Error unmapping buffer:', e );
  54900. }
  54901. }
  54902. // Destroy resources
  54903. if ( this.querySet ) {
  54904. this.querySet.destroy();
  54905. this.querySet = null;
  54906. }
  54907. if ( this.resolveBuffer ) {
  54908. this.resolveBuffer.destroy();
  54909. this.resolveBuffer = null;
  54910. }
  54911. if ( this.resultBuffer ) {
  54912. this.resultBuffer.destroy();
  54913. this.resultBuffer = null;
  54914. }
  54915. this.queryOffsets.clear();
  54916. this.pendingResolve = null;
  54917. }
  54918. }
  54919. /*// debugger tools
  54920. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  54921. //*/
  54922. /**
  54923. * A backend implementation targeting WebGPU.
  54924. *
  54925. * @private
  54926. * @augments Backend
  54927. */
  54928. class WebGPUBackend extends Backend {
  54929. /**
  54930. * WebGPUBackend options.
  54931. *
  54932. * @typedef {Object} WebGPUBackend~Options
  54933. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  54934. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  54935. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  54936. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  54937. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  54938. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  54939. * @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.
  54940. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  54941. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  54942. * @property {string} [powerPreference=undefined] - The power preference.
  54943. * @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.
  54944. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  54945. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  54946. */
  54947. /**
  54948. * Constructs a new WebGPU backend.
  54949. *
  54950. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  54951. */
  54952. constructor( parameters = {} ) {
  54953. super( parameters );
  54954. /**
  54955. * This flag can be used for type testing.
  54956. *
  54957. * @type {boolean}
  54958. * @readonly
  54959. * @default true
  54960. */
  54961. this.isWebGPUBackend = true;
  54962. // some parameters require default values other than "undefined"
  54963. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  54964. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  54965. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  54966. /**
  54967. * Indicates whether the backend is in compatibility mode or not.
  54968. * @type {boolean}
  54969. * @default false
  54970. */
  54971. this.compatibilityMode = this.parameters.compatibilityMode;
  54972. /**
  54973. * A reference to the device.
  54974. *
  54975. * @type {?GPUDevice}
  54976. * @default null
  54977. */
  54978. this.device = null;
  54979. /**
  54980. * A reference to the default render pass descriptor.
  54981. *
  54982. * @type {?Object}
  54983. * @default null
  54984. */
  54985. this.defaultRenderPassdescriptor = null;
  54986. /**
  54987. * A reference to a backend module holding common utility functions.
  54988. *
  54989. * @type {WebGPUUtils}
  54990. */
  54991. this.utils = new WebGPUUtils( this );
  54992. /**
  54993. * A reference to a backend module holding shader attribute-related
  54994. * utility functions.
  54995. *
  54996. * @type {WebGPUAttributeUtils}
  54997. */
  54998. this.attributeUtils = new WebGPUAttributeUtils( this );
  54999. /**
  55000. * A reference to a backend module holding shader binding-related
  55001. * utility functions.
  55002. *
  55003. * @type {WebGPUBindingUtils}
  55004. */
  55005. this.bindingUtils = new WebGPUBindingUtils( this );
  55006. /**
  55007. * A reference to a backend module holding shader pipeline-related
  55008. * utility functions.
  55009. *
  55010. * @type {WebGPUPipelineUtils}
  55011. */
  55012. this.pipelineUtils = new WebGPUPipelineUtils( this );
  55013. /**
  55014. * A reference to a backend module holding shader texture-related
  55015. * utility functions.
  55016. *
  55017. * @type {WebGPUTextureUtils}
  55018. */
  55019. this.textureUtils = new WebGPUTextureUtils( this );
  55020. /**
  55021. * A map that manages the resolve buffers for occlusion queries.
  55022. *
  55023. * @type {Map<number,GPUBuffer>}
  55024. */
  55025. this.occludedResolveCache = new Map();
  55026. }
  55027. /**
  55028. * Initializes the backend so it is ready for usage.
  55029. *
  55030. * @async
  55031. * @param {Renderer} renderer - The renderer.
  55032. * @return {Promise} A Promise that resolves when the backend has been initialized.
  55033. */
  55034. async init( renderer ) {
  55035. await super.init( renderer );
  55036. //
  55037. const parameters = this.parameters;
  55038. // create the device if it is not passed with parameters
  55039. let device;
  55040. if ( parameters.device === undefined ) {
  55041. const adapterOptions = {
  55042. powerPreference: parameters.powerPreference,
  55043. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  55044. };
  55045. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  55046. if ( adapter === null ) {
  55047. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  55048. }
  55049. // feature support
  55050. const features = Object.values( GPUFeatureName );
  55051. const supportedFeatures = [];
  55052. for ( const name of features ) {
  55053. if ( adapter.features.has( name ) ) {
  55054. supportedFeatures.push( name );
  55055. }
  55056. }
  55057. const deviceDescriptor = {
  55058. requiredFeatures: supportedFeatures,
  55059. requiredLimits: parameters.requiredLimits
  55060. };
  55061. device = await adapter.requestDevice( deviceDescriptor );
  55062. } else {
  55063. device = parameters.device;
  55064. }
  55065. device.lost.then( ( info ) => {
  55066. const deviceLossInfo = {
  55067. api: 'WebGPU',
  55068. message: info.message || 'Unknown reason',
  55069. reason: info.reason || null,
  55070. originalEvent: info
  55071. };
  55072. renderer.onDeviceLost( deviceLossInfo );
  55073. } );
  55074. this.device = device;
  55075. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  55076. this.updateSize();
  55077. }
  55078. /**
  55079. * A reference to the context.
  55080. *
  55081. * @type {?GPUCanvasContext}
  55082. * @default null
  55083. */
  55084. get context() {
  55085. const canvasTarget = this.renderer.getCanvasTarget();
  55086. const canvasData = this.get( canvasTarget );
  55087. let context = canvasData.context;
  55088. if ( context === undefined ) {
  55089. const parameters = this.parameters;
  55090. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  55091. context = parameters.context;
  55092. } else {
  55093. context = canvasTarget.domElement.getContext( 'webgpu' );
  55094. }
  55095. // OffscreenCanvas does not have setAttribute, see #22811
  55096. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  55097. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  55098. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  55099. context.configure( {
  55100. device: this.device,
  55101. format: this.utils.getPreferredCanvasFormat(),
  55102. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  55103. alphaMode: alphaMode,
  55104. toneMapping: {
  55105. mode: toneMappingMode
  55106. }
  55107. } );
  55108. canvasData.context = context;
  55109. }
  55110. return context;
  55111. }
  55112. /**
  55113. * The coordinate system of the backend.
  55114. *
  55115. * @type {number}
  55116. * @readonly
  55117. */
  55118. get coordinateSystem() {
  55119. return WebGPUCoordinateSystem;
  55120. }
  55121. /**
  55122. * This method performs a readback operation by moving buffer data from
  55123. * a storage buffer attribute from the GPU to the CPU.
  55124. *
  55125. * @async
  55126. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  55127. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  55128. */
  55129. async getArrayBufferAsync( attribute ) {
  55130. return await this.attributeUtils.getArrayBufferAsync( attribute );
  55131. }
  55132. /**
  55133. * Returns the backend's rendering context.
  55134. *
  55135. * @return {GPUCanvasContext} The rendering context.
  55136. */
  55137. getContext() {
  55138. return this.context;
  55139. }
  55140. /**
  55141. * Returns the default render pass descriptor.
  55142. *
  55143. * In WebGPU, the default framebuffer must be configured
  55144. * like custom framebuffers so the backend needs a render
  55145. * pass descriptor even when rendering directly to screen.
  55146. *
  55147. * @private
  55148. * @return {Object} The render pass descriptor.
  55149. */
  55150. _getDefaultRenderPassDescriptor() {
  55151. const renderer = this.renderer;
  55152. const canvasTarget = renderer.getCanvasTarget();
  55153. const canvasData = this.get( canvasTarget );
  55154. const samples = renderer.currentSamples;
  55155. let descriptor = canvasData.descriptor;
  55156. if ( descriptor === undefined || canvasData.samples !== samples ) {
  55157. descriptor = {
  55158. colorAttachments: [ {
  55159. view: null
  55160. } ]
  55161. };
  55162. if ( renderer.depth === true || renderer.stencil === true ) {
  55163. descriptor.depthStencilAttachment = {
  55164. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  55165. };
  55166. }
  55167. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55168. if ( samples > 0 ) {
  55169. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  55170. } else {
  55171. colorAttachment.resolveTarget = undefined;
  55172. }
  55173. canvasData.descriptor = descriptor;
  55174. canvasData.samples = samples;
  55175. }
  55176. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55177. if ( samples > 0 ) {
  55178. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  55179. } else {
  55180. colorAttachment.view = this.context.getCurrentTexture().createView();
  55181. }
  55182. return descriptor;
  55183. }
  55184. /**
  55185. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  55186. *
  55187. * @param {RenderContext} renderContext - The render context.
  55188. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  55189. *
  55190. * @private
  55191. */
  55192. _isRenderCameraDepthArray( renderContext ) {
  55193. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  55194. }
  55195. /**
  55196. * Returns the render pass descriptor for the given render context.
  55197. *
  55198. * @private
  55199. * @param {RenderContext} renderContext - The render context.
  55200. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  55201. * @return {Object} The render pass descriptor.
  55202. */
  55203. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  55204. const renderTarget = renderContext.renderTarget;
  55205. const renderTargetData = this.get( renderTarget );
  55206. let descriptors = renderTargetData.descriptors;
  55207. if ( descriptors === undefined ||
  55208. renderTargetData.width !== renderTarget.width ||
  55209. renderTargetData.height !== renderTarget.height ||
  55210. renderTargetData.samples !== renderTarget.samples
  55211. ) {
  55212. descriptors = {};
  55213. renderTargetData.descriptors = descriptors;
  55214. }
  55215. const cacheKey = renderContext.getCacheKey();
  55216. let descriptorBase = descriptors[ cacheKey ];
  55217. if ( descriptorBase === undefined ) {
  55218. const textures = renderContext.textures;
  55219. const textureViews = [];
  55220. let sliceIndex;
  55221. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  55222. for ( let i = 0; i < textures.length; i ++ ) {
  55223. const textureData = this.get( textures[ i ] );
  55224. const viewDescriptor = {
  55225. label: `colorAttachment_${ i }`,
  55226. baseMipLevel: renderContext.activeMipmapLevel,
  55227. mipLevelCount: 1,
  55228. baseArrayLayer: renderContext.activeCubeFace,
  55229. arrayLayerCount: 1,
  55230. dimension: GPUTextureViewDimension.TwoD
  55231. };
  55232. if ( renderTarget.isRenderTarget3D ) {
  55233. sliceIndex = renderContext.activeCubeFace;
  55234. viewDescriptor.baseArrayLayer = 0;
  55235. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  55236. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  55237. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  55238. if ( isRenderCameraDepthArray === true ) {
  55239. const cameras = renderContext.camera.cameras;
  55240. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  55241. const layerViewDescriptor = {
  55242. ...viewDescriptor,
  55243. baseArrayLayer: layer,
  55244. arrayLayerCount: 1,
  55245. dimension: GPUTextureViewDimension.TwoD
  55246. };
  55247. const textureView = textureData.texture.createView( layerViewDescriptor );
  55248. textureViews.push( {
  55249. view: textureView,
  55250. resolveTarget: undefined,
  55251. depthSlice: undefined
  55252. } );
  55253. }
  55254. } else {
  55255. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  55256. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  55257. }
  55258. }
  55259. if ( isRenderCameraDepthArray !== true ) {
  55260. const textureView = textureData.texture.createView( viewDescriptor );
  55261. let view, resolveTarget;
  55262. if ( textureData.msaaTexture !== undefined ) {
  55263. view = textureData.msaaTexture.createView();
  55264. resolveTarget = textureView;
  55265. } else {
  55266. view = textureView;
  55267. resolveTarget = undefined;
  55268. }
  55269. textureViews.push( {
  55270. view,
  55271. resolveTarget,
  55272. depthSlice: sliceIndex
  55273. } );
  55274. }
  55275. }
  55276. descriptorBase = { textureViews };
  55277. if ( renderContext.depth ) {
  55278. const depthTextureData = this.get( renderContext.depthTexture );
  55279. const options = {};
  55280. if ( renderContext.depthTexture.isArrayTexture ) {
  55281. options.dimension = GPUTextureViewDimension.TwoD;
  55282. options.arrayLayerCount = 1;
  55283. options.baseArrayLayer = renderContext.activeCubeFace;
  55284. }
  55285. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  55286. }
  55287. descriptors[ cacheKey ] = descriptorBase;
  55288. renderTargetData.width = renderTarget.width;
  55289. renderTargetData.height = renderTarget.height;
  55290. renderTargetData.samples = renderTarget.samples;
  55291. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  55292. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  55293. }
  55294. const descriptor = {
  55295. colorAttachments: []
  55296. };
  55297. // Apply dynamic properties to cached views
  55298. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  55299. const viewInfo = descriptorBase.textureViews[ i ];
  55300. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  55301. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  55302. clearValue = colorAttachmentsConfig.clearValue;
  55303. }
  55304. descriptor.colorAttachments.push( {
  55305. view: viewInfo.view,
  55306. depthSlice: viewInfo.depthSlice,
  55307. resolveTarget: viewInfo.resolveTarget,
  55308. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  55309. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  55310. clearValue: clearValue
  55311. } );
  55312. }
  55313. if ( descriptorBase.depthStencilView ) {
  55314. descriptor.depthStencilAttachment = {
  55315. view: descriptorBase.depthStencilView
  55316. };
  55317. }
  55318. return descriptor;
  55319. }
  55320. /**
  55321. * This method is executed at the beginning of a render call and prepares
  55322. * the WebGPU state for upcoming render calls
  55323. *
  55324. * @param {RenderContext} renderContext - The render context.
  55325. */
  55326. beginRender( renderContext ) {
  55327. const renderContextData = this.get( renderContext );
  55328. //
  55329. const device = this.device;
  55330. const occlusionQueryCount = renderContext.occlusionQueryCount;
  55331. let occlusionQuerySet;
  55332. if ( occlusionQueryCount > 0 ) {
  55333. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  55334. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  55335. // Get a reference to the array of objects with queries. The renderContextData property
  55336. // can be changed by another render pass before the buffer.mapAsyc() completes.
  55337. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  55338. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  55339. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  55340. //
  55341. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  55342. renderContextData.occlusionQuerySet = occlusionQuerySet;
  55343. renderContextData.occlusionQueryIndex = 0;
  55344. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  55345. renderContextData.lastOcclusionObject = null;
  55346. }
  55347. let descriptor;
  55348. if ( renderContext.textures === null ) {
  55349. descriptor = this._getDefaultRenderPassDescriptor();
  55350. } else {
  55351. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  55352. }
  55353. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  55354. descriptor.occlusionQuerySet = occlusionQuerySet;
  55355. const depthStencilAttachment = descriptor.depthStencilAttachment;
  55356. if ( renderContext.textures !== null ) {
  55357. const colorAttachments = descriptor.colorAttachments;
  55358. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  55359. const colorAttachment = colorAttachments[ i ];
  55360. if ( renderContext.clearColor ) {
  55361. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  55362. colorAttachment.loadOp = GPULoadOp.Clear;
  55363. } else {
  55364. colorAttachment.loadOp = GPULoadOp.Load;
  55365. }
  55366. colorAttachment.storeOp = GPUStoreOp.Store;
  55367. }
  55368. } else {
  55369. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55370. if ( renderContext.clearColor ) {
  55371. colorAttachment.clearValue = renderContext.clearColorValue;
  55372. colorAttachment.loadOp = GPULoadOp.Clear;
  55373. } else {
  55374. colorAttachment.loadOp = GPULoadOp.Load;
  55375. }
  55376. colorAttachment.storeOp = GPUStoreOp.Store;
  55377. }
  55378. //
  55379. if ( renderContext.depth ) {
  55380. if ( renderContext.clearDepth ) {
  55381. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  55382. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  55383. } else {
  55384. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  55385. }
  55386. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  55387. }
  55388. if ( renderContext.stencil ) {
  55389. if ( renderContext.clearStencil ) {
  55390. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  55391. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  55392. } else {
  55393. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  55394. }
  55395. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  55396. }
  55397. //
  55398. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  55399. // shadow arrays - prepare bundle encoders for each camera in an array camera
  55400. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  55401. const cameras = renderContext.camera.cameras;
  55402. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  55403. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  55404. } else {
  55405. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  55406. }
  55407. // Create bundle encoders for each layer
  55408. renderContextData.bundleEncoders = [];
  55409. renderContextData.bundleSets = [];
  55410. // Create separate bundle encoders for each camera in the array
  55411. for ( let i = 0; i < cameras.length; i ++ ) {
  55412. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  55413. renderContext,
  55414. 'renderBundleArrayCamera_' + i
  55415. );
  55416. // Initialize state tracking for this bundle
  55417. const bundleSets = {
  55418. attributes: {},
  55419. bindingGroups: [],
  55420. pipeline: null,
  55421. index: null
  55422. };
  55423. renderContextData.bundleEncoders.push( bundleEncoder );
  55424. renderContextData.bundleSets.push( bundleSets );
  55425. }
  55426. // We'll complete the bundles in finishRender
  55427. renderContextData.currentPass = null;
  55428. } else {
  55429. const currentPass = encoder.beginRenderPass( descriptor );
  55430. renderContextData.currentPass = currentPass;
  55431. if ( renderContext.viewport ) {
  55432. this.updateViewport( renderContext );
  55433. }
  55434. if ( renderContext.scissor ) {
  55435. this.updateScissor( renderContext );
  55436. }
  55437. }
  55438. //
  55439. renderContextData.descriptor = descriptor;
  55440. renderContextData.encoder = encoder;
  55441. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  55442. renderContextData.renderBundles = [];
  55443. }
  55444. /**
  55445. * This method creates layer descriptors for each camera in an array camera
  55446. * to prepare for rendering to a depth array texture.
  55447. *
  55448. * @param {RenderContext} renderContext - The render context.
  55449. * @param {Object} renderContextData - The render context data.
  55450. * @param {Object} descriptor - The render pass descriptor.
  55451. * @param {ArrayCamera} cameras - The array camera.
  55452. *
  55453. * @private
  55454. */
  55455. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  55456. const depthStencilAttachment = descriptor.depthStencilAttachment;
  55457. renderContextData.layerDescriptors = [];
  55458. const depthTextureData = this.get( renderContext.depthTexture );
  55459. if ( ! depthTextureData.viewCache ) {
  55460. depthTextureData.viewCache = [];
  55461. }
  55462. for ( let i = 0; i < cameras.length; i ++ ) {
  55463. const layerDescriptor = {
  55464. ...descriptor,
  55465. colorAttachments: [ {
  55466. ...descriptor.colorAttachments[ 0 ],
  55467. view: descriptor.colorAttachments[ i ].view
  55468. } ]
  55469. };
  55470. if ( descriptor.depthStencilAttachment ) {
  55471. const layerIndex = i;
  55472. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  55473. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  55474. dimension: GPUTextureViewDimension.TwoD,
  55475. baseArrayLayer: i,
  55476. arrayLayerCount: 1
  55477. } );
  55478. }
  55479. layerDescriptor.depthStencilAttachment = {
  55480. view: depthTextureData.viewCache[ layerIndex ],
  55481. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  55482. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  55483. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  55484. };
  55485. if ( renderContext.stencil ) {
  55486. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  55487. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  55488. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  55489. }
  55490. } else {
  55491. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  55492. }
  55493. renderContextData.layerDescriptors.push( layerDescriptor );
  55494. }
  55495. }
  55496. /**
  55497. * This method updates the layer descriptors for each camera in an array camera
  55498. * to prepare for rendering to a depth array texture.
  55499. *
  55500. * @param {RenderContext} renderContext - The render context.
  55501. * @param {Object} renderContextData - The render context data.
  55502. * @param {ArrayCamera} cameras - The array camera.
  55503. *
  55504. */
  55505. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  55506. for ( let i = 0; i < cameras.length; i ++ ) {
  55507. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  55508. if ( layerDescriptor.depthStencilAttachment ) {
  55509. const depthAttachment = layerDescriptor.depthStencilAttachment;
  55510. if ( renderContext.depth ) {
  55511. if ( renderContext.clearDepth ) {
  55512. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  55513. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  55514. } else {
  55515. depthAttachment.depthLoadOp = GPULoadOp.Load;
  55516. }
  55517. }
  55518. if ( renderContext.stencil ) {
  55519. if ( renderContext.clearStencil ) {
  55520. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  55521. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  55522. } else {
  55523. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  55524. }
  55525. }
  55526. }
  55527. }
  55528. }
  55529. /**
  55530. * This method is executed at the end of a render call and finalizes work
  55531. * after draw calls.
  55532. *
  55533. * @param {RenderContext} renderContext - The render context.
  55534. */
  55535. finishRender( renderContext ) {
  55536. const renderContextData = this.get( renderContext );
  55537. const occlusionQueryCount = renderContext.occlusionQueryCount;
  55538. if ( renderContextData.renderBundles.length > 0 ) {
  55539. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  55540. }
  55541. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  55542. renderContextData.currentPass.endOcclusionQuery();
  55543. }
  55544. // shadow arrays - Execute bundles for each layer
  55545. const encoder = renderContextData.encoder;
  55546. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  55547. const bundles = [];
  55548. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  55549. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  55550. bundles.push( bundleEncoder.finish() );
  55551. }
  55552. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  55553. if ( i < bundles.length ) {
  55554. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  55555. const renderPass = encoder.beginRenderPass( layerDescriptor );
  55556. if ( renderContext.viewport ) {
  55557. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  55558. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  55559. }
  55560. if ( renderContext.scissor ) {
  55561. const { x, y, width, height } = renderContext.scissorValue;
  55562. renderPass.setScissorRect( x, y, width, height );
  55563. }
  55564. renderPass.executeBundles( [ bundles[ i ] ] );
  55565. renderPass.end();
  55566. }
  55567. }
  55568. } else if ( renderContextData.currentPass ) {
  55569. renderContextData.currentPass.end();
  55570. }
  55571. if ( occlusionQueryCount > 0 ) {
  55572. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  55573. //
  55574. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  55575. if ( queryResolveBuffer === undefined ) {
  55576. queryResolveBuffer = this.device.createBuffer(
  55577. {
  55578. size: bufferSize,
  55579. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  55580. }
  55581. );
  55582. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  55583. }
  55584. //
  55585. const readBuffer = this.device.createBuffer(
  55586. {
  55587. size: bufferSize,
  55588. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  55589. }
  55590. );
  55591. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  55592. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  55593. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  55594. renderContextData.occlusionQueryBuffer = readBuffer;
  55595. //
  55596. this.resolveOccludedAsync( renderContext );
  55597. }
  55598. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  55599. //
  55600. if ( renderContext.textures !== null ) {
  55601. const textures = renderContext.textures;
  55602. for ( let i = 0; i < textures.length; i ++ ) {
  55603. const texture = textures[ i ];
  55604. if ( texture.generateMipmaps === true ) {
  55605. this.textureUtils.generateMipmaps( texture );
  55606. }
  55607. }
  55608. }
  55609. }
  55610. /**
  55611. * Returns `true` if the given 3D object is fully occluded by other
  55612. * 3D objects in the scene.
  55613. *
  55614. * @param {RenderContext} renderContext - The render context.
  55615. * @param {Object3D} object - The 3D object to test.
  55616. * @return {boolean} Whether the 3D object is fully occluded or not.
  55617. */
  55618. isOccluded( renderContext, object ) {
  55619. const renderContextData = this.get( renderContext );
  55620. return renderContextData.occluded && renderContextData.occluded.has( object );
  55621. }
  55622. /**
  55623. * This method processes the result of occlusion queries and writes it
  55624. * into render context data.
  55625. *
  55626. * @async
  55627. * @param {RenderContext} renderContext - The render context.
  55628. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  55629. */
  55630. async resolveOccludedAsync( renderContext ) {
  55631. const renderContextData = this.get( renderContext );
  55632. // handle occlusion query results
  55633. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  55634. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  55635. const occluded = new WeakSet();
  55636. renderContextData.currentOcclusionQueryObjects = null;
  55637. renderContextData.currentOcclusionQueryBuffer = null;
  55638. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  55639. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  55640. const results = new BigUint64Array( buffer );
  55641. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  55642. if ( results[ i ] === BigInt( 0 ) ) {
  55643. occluded.add( currentOcclusionQueryObjects[ i ] );
  55644. }
  55645. }
  55646. currentOcclusionQueryBuffer.destroy();
  55647. renderContextData.occluded = occluded;
  55648. }
  55649. }
  55650. /**
  55651. * Updates the viewport with the values from the given render context.
  55652. *
  55653. * @param {RenderContext} renderContext - The render context.
  55654. */
  55655. updateViewport( renderContext ) {
  55656. const { currentPass } = this.get( renderContext );
  55657. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  55658. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  55659. }
  55660. /**
  55661. * Updates the scissor with the values from the given render context.
  55662. *
  55663. * @param {RenderContext} renderContext - The render context.
  55664. */
  55665. updateScissor( renderContext ) {
  55666. const { currentPass } = this.get( renderContext );
  55667. const { x, y, width, height } = renderContext.scissorValue;
  55668. currentPass.setScissorRect( x, y, width, height );
  55669. }
  55670. /**
  55671. * Returns the clear color and alpha into a single
  55672. * color object.
  55673. *
  55674. * @return {Color4} The clear color.
  55675. */
  55676. getClearColor() {
  55677. const clearColor = super.getClearColor();
  55678. // only premultiply alpha when alphaMode is "premultiplied"
  55679. if ( this.renderer.alpha === true ) {
  55680. clearColor.r *= clearColor.a;
  55681. clearColor.g *= clearColor.a;
  55682. clearColor.b *= clearColor.a;
  55683. }
  55684. return clearColor;
  55685. }
  55686. /**
  55687. * Performs a clear operation.
  55688. *
  55689. * @param {boolean} color - Whether the color buffer should be cleared or not.
  55690. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  55691. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  55692. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  55693. */
  55694. clear( color, depth, stencil, renderTargetContext = null ) {
  55695. const device = this.device;
  55696. const renderer = this.renderer;
  55697. let colorAttachments = [];
  55698. let depthStencilAttachment;
  55699. let clearValue;
  55700. let supportsDepth;
  55701. let supportsStencil;
  55702. if ( color ) {
  55703. const clearColor = this.getClearColor();
  55704. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  55705. }
  55706. if ( renderTargetContext === null ) {
  55707. supportsDepth = renderer.depth;
  55708. supportsStencil = renderer.stencil;
  55709. const descriptor = this._getDefaultRenderPassDescriptor();
  55710. if ( color ) {
  55711. colorAttachments = descriptor.colorAttachments;
  55712. const colorAttachment = colorAttachments[ 0 ];
  55713. colorAttachment.clearValue = clearValue;
  55714. colorAttachment.loadOp = GPULoadOp.Clear;
  55715. colorAttachment.storeOp = GPUStoreOp.Store;
  55716. }
  55717. if ( supportsDepth || supportsStencil ) {
  55718. depthStencilAttachment = descriptor.depthStencilAttachment;
  55719. }
  55720. } else {
  55721. supportsDepth = renderTargetContext.depth;
  55722. supportsStencil = renderTargetContext.stencil;
  55723. const clearConfig = {
  55724. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  55725. clearValue: color ? clearValue : undefined
  55726. };
  55727. if ( supportsDepth ) {
  55728. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  55729. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  55730. clearConfig.depthStoreOp = GPUStoreOp.Store;
  55731. }
  55732. if ( supportsStencil ) {
  55733. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  55734. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  55735. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  55736. }
  55737. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  55738. colorAttachments = descriptor.colorAttachments;
  55739. depthStencilAttachment = descriptor.depthStencilAttachment;
  55740. }
  55741. if ( supportsDepth && depthStencilAttachment ) {
  55742. if ( depth ) {
  55743. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  55744. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  55745. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  55746. } else {
  55747. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  55748. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  55749. }
  55750. }
  55751. //
  55752. if ( supportsStencil && depthStencilAttachment ) {
  55753. if ( stencil ) {
  55754. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  55755. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  55756. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  55757. } else {
  55758. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  55759. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  55760. }
  55761. }
  55762. //
  55763. const encoder = device.createCommandEncoder( { label: 'clear' } );
  55764. const currentPass = encoder.beginRenderPass( {
  55765. colorAttachments,
  55766. depthStencilAttachment
  55767. } );
  55768. currentPass.end();
  55769. device.queue.submit( [ encoder.finish() ] );
  55770. }
  55771. // compute
  55772. /**
  55773. * This method is executed at the beginning of a compute call and
  55774. * prepares the state for upcoming compute tasks.
  55775. *
  55776. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  55777. */
  55778. beginCompute( computeGroup ) {
  55779. const groupGPU = this.get( computeGroup );
  55780. //
  55781. const descriptor = {
  55782. label: 'computeGroup_' + computeGroup.id
  55783. };
  55784. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  55785. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  55786. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  55787. }
  55788. /**
  55789. * Executes a compute command for the given compute node.
  55790. *
  55791. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  55792. * @param {Node} computeNode - The compute node.
  55793. * @param {Array<BindGroup>} bindings - The bindings.
  55794. * @param {ComputePipeline} pipeline - The compute pipeline.
  55795. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  55796. * - A single number representing count, or
  55797. * - An array [x, y, z] representing dispatch size, or
  55798. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  55799. */
  55800. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  55801. const computeNodeData = this.get( computeNode );
  55802. const { passEncoderGPU } = this.get( computeGroup );
  55803. // pipeline
  55804. const pipelineGPU = this.get( pipeline ).pipeline;
  55805. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  55806. // bind groups
  55807. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  55808. const bindGroup = bindings[ i ];
  55809. const bindingsData = this.get( bindGroup );
  55810. passEncoderGPU.setBindGroup( i, bindingsData.group );
  55811. }
  55812. if ( dispatchSize === null ) {
  55813. dispatchSize = computeNode.count;
  55814. }
  55815. // When the dispatchSize is set with a StorageBuffer from the GPU.
  55816. if ( dispatchSize && typeof dispatchSize === 'object' && dispatchSize.isIndirectStorageBufferAttribute ) {
  55817. const dispatchBuffer = this.get( dispatchSize ).buffer;
  55818. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  55819. return;
  55820. }
  55821. if ( typeof dispatchSize === 'number' ) {
  55822. // If a single number is given, we calculate the dispatch size based on the workgroup size
  55823. const count = dispatchSize;
  55824. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  55825. // cache dispatch size to avoid recalculating it every time
  55826. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  55827. computeNodeData.count = count;
  55828. const workgroupSize = computeNode.workgroupSize;
  55829. let size = workgroupSize[ 0 ];
  55830. for ( let i = 1; i < workgroupSize.length; i ++ )
  55831. size *= workgroupSize[ i ];
  55832. const dispatchCount = Math.ceil( count / size );
  55833. //
  55834. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  55835. dispatchSize = [ dispatchCount, 1, 1 ];
  55836. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  55837. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  55838. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  55839. }
  55840. computeNodeData.dispatchSize = dispatchSize;
  55841. }
  55842. dispatchSize = computeNodeData.dispatchSize;
  55843. }
  55844. //
  55845. passEncoderGPU.dispatchWorkgroups(
  55846. dispatchSize[ 0 ],
  55847. dispatchSize[ 1 ] || 1,
  55848. dispatchSize[ 2 ] || 1
  55849. );
  55850. }
  55851. /**
  55852. * This method is executed at the end of a compute call and
  55853. * finalizes work after compute tasks.
  55854. *
  55855. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  55856. */
  55857. finishCompute( computeGroup ) {
  55858. const groupData = this.get( computeGroup );
  55859. groupData.passEncoderGPU.end();
  55860. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  55861. }
  55862. // render object
  55863. /**
  55864. * Executes a draw command for the given render object.
  55865. *
  55866. * @param {RenderObject} renderObject - The render object to draw.
  55867. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  55868. */
  55869. draw( renderObject, info ) {
  55870. const { object, material, context, pipeline } = renderObject;
  55871. const bindings = renderObject.getBindings();
  55872. const renderContextData = this.get( context );
  55873. const pipelineData = this.get( pipeline );
  55874. const pipelineGPU = pipelineData.pipeline;
  55875. if ( pipelineData.error === true ) return;
  55876. const index = renderObject.getIndex();
  55877. const hasIndex = ( index !== null );
  55878. const drawParams = renderObject.getDrawParameters();
  55879. if ( drawParams === null ) return;
  55880. // pipeline
  55881. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  55882. // pipeline
  55883. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  55884. currentSets.pipeline = pipelineGPU;
  55885. // bind groups
  55886. const currentBindingGroups = currentSets.bindingGroups;
  55887. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  55888. const bindGroup = bindings[ i ];
  55889. const bindingsData = this.get( bindGroup );
  55890. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  55891. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  55892. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  55893. }
  55894. }
  55895. // attributes
  55896. // index
  55897. if ( hasIndex === true ) {
  55898. if ( currentSets.index !== index ) {
  55899. const buffer = this.get( index ).buffer;
  55900. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  55901. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  55902. currentSets.index = index;
  55903. }
  55904. }
  55905. // vertex buffers
  55906. const vertexBuffers = renderObject.getVertexBuffers();
  55907. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  55908. const vertexBuffer = vertexBuffers[ i ];
  55909. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  55910. const buffer = this.get( vertexBuffer ).buffer;
  55911. passEncoderGPU.setVertexBuffer( i, buffer );
  55912. currentSets.attributes[ i ] = vertexBuffer;
  55913. }
  55914. }
  55915. // stencil
  55916. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  55917. passEncoderGPU.setStencilReference( material.stencilRef );
  55918. renderContextData.currentStencilRef = material.stencilRef;
  55919. }
  55920. };
  55921. // Define draw function
  55922. const draw = ( passEncoderGPU, currentSets ) => {
  55923. setPipelineAndBindings( passEncoderGPU, currentSets );
  55924. if ( object.isBatchedMesh === true ) {
  55925. const starts = object._multiDrawStarts;
  55926. const counts = object._multiDrawCounts;
  55927. const drawCount = object._multiDrawCount;
  55928. const drawInstances = object._multiDrawInstances;
  55929. if ( drawInstances !== null ) {
  55930. // @deprecated, r174
  55931. warnOnce( 'WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  55932. }
  55933. for ( let i = 0; i < drawCount; i ++ ) {
  55934. const count = drawInstances ? drawInstances[ i ] : 1;
  55935. const firstInstance = count > 1 ? 0 : i;
  55936. if ( hasIndex === true ) {
  55937. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  55938. } else {
  55939. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  55940. }
  55941. info.update( object, counts[ i ], count );
  55942. }
  55943. } else if ( hasIndex === true ) {
  55944. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  55945. const indirect = renderObject.getIndirect();
  55946. if ( indirect !== null ) {
  55947. const buffer = this.get( indirect ).buffer;
  55948. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  55949. } else {
  55950. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  55951. }
  55952. info.update( object, indexCount, instanceCount );
  55953. } else {
  55954. const { vertexCount, instanceCount, firstVertex } = drawParams;
  55955. const indirect = renderObject.getIndirect();
  55956. if ( indirect !== null ) {
  55957. const buffer = this.get( indirect ).buffer;
  55958. passEncoderGPU.drawIndirect( buffer, 0 );
  55959. } else {
  55960. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  55961. }
  55962. info.update( object, vertexCount, instanceCount );
  55963. }
  55964. };
  55965. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  55966. const cameraData = this.get( renderObject.camera );
  55967. const cameras = renderObject.camera.cameras;
  55968. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  55969. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  55970. const bindingsData = this.get( cameraIndex );
  55971. const indexesGPU = [];
  55972. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  55973. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  55974. data[ 0 ] = i;
  55975. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  55976. indexesGPU.push( bindGroupIndex );
  55977. }
  55978. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  55979. }
  55980. const pixelRatio = this.renderer.getPixelRatio();
  55981. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  55982. const subCamera = cameras[ i ];
  55983. if ( object.layers.test( subCamera.layers ) ) {
  55984. const vp = subCamera.viewport;
  55985. let pass = renderContextData.currentPass;
  55986. let sets = renderContextData.currentSets;
  55987. if ( renderContextData.bundleEncoders ) {
  55988. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  55989. const bundleSets = renderContextData.bundleSets[ i ];
  55990. pass = bundleEncoder;
  55991. sets = bundleSets;
  55992. }
  55993. if ( vp ) {
  55994. pass.setViewport(
  55995. Math.floor( vp.x * pixelRatio ),
  55996. Math.floor( vp.y * pixelRatio ),
  55997. Math.floor( vp.width * pixelRatio ),
  55998. Math.floor( vp.height * pixelRatio ),
  55999. context.viewportValue.minDepth,
  56000. context.viewportValue.maxDepth
  56001. );
  56002. }
  56003. // Set camera index binding for this layer
  56004. if ( cameraIndex && cameraData.indexesGPU ) {
  56005. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  56006. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  56007. }
  56008. draw( pass, sets );
  56009. }
  56010. }
  56011. } else {
  56012. // Regular single camera rendering
  56013. if ( renderContextData.currentPass ) {
  56014. // Handle occlusion queries
  56015. if ( renderContextData.occlusionQuerySet !== undefined ) {
  56016. const lastObject = renderContextData.lastOcclusionObject;
  56017. if ( lastObject !== object ) {
  56018. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  56019. renderContextData.currentPass.endOcclusionQuery();
  56020. renderContextData.occlusionQueryIndex ++;
  56021. }
  56022. if ( object.occlusionTest === true ) {
  56023. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  56024. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  56025. }
  56026. renderContextData.lastOcclusionObject = object;
  56027. }
  56028. }
  56029. draw( renderContextData.currentPass, renderContextData.currentSets );
  56030. }
  56031. }
  56032. }
  56033. // cache key
  56034. /**
  56035. * Returns `true` if the render pipeline requires an update.
  56036. *
  56037. * @param {RenderObject} renderObject - The render object.
  56038. * @return {boolean} Whether the render pipeline requires an update or not.
  56039. */
  56040. needsRenderUpdate( renderObject ) {
  56041. const data = this.get( renderObject );
  56042. const { object, material } = renderObject;
  56043. const utils = this.utils;
  56044. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  56045. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  56046. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  56047. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  56048. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  56049. let needsUpdate = false;
  56050. if ( data.material !== material || data.materialVersion !== material.version ||
  56051. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  56052. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  56053. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  56054. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  56055. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  56056. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  56057. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  56058. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  56059. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  56060. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  56061. data.primitiveTopology !== primitiveTopology ||
  56062. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  56063. ) {
  56064. data.material = material; data.materialVersion = material.version;
  56065. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  56066. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  56067. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  56068. data.colorWrite = material.colorWrite;
  56069. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  56070. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  56071. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  56072. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  56073. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  56074. data.sampleCount = sampleCount;
  56075. data.colorSpace = colorSpace;
  56076. data.colorFormat = colorFormat;
  56077. data.depthStencilFormat = depthStencilFormat;
  56078. data.primitiveTopology = primitiveTopology;
  56079. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  56080. needsUpdate = true;
  56081. }
  56082. return needsUpdate;
  56083. }
  56084. /**
  56085. * Returns a cache key that is used to identify render pipelines.
  56086. *
  56087. * @param {RenderObject} renderObject - The render object.
  56088. * @return {string} The cache key.
  56089. */
  56090. getRenderCacheKey( renderObject ) {
  56091. const { object, material } = renderObject;
  56092. const utils = this.utils;
  56093. const renderContext = renderObject.context;
  56094. // meshes with negative scale have a different frontFace render pipeline
  56095. // descriptor value so the following must be honored in the cache key
  56096. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  56097. return [
  56098. material.transparent, material.blending, material.premultipliedAlpha,
  56099. material.blendSrc, material.blendDst, material.blendEquation,
  56100. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  56101. material.colorWrite,
  56102. material.depthWrite, material.depthTest, material.depthFunc,
  56103. material.stencilWrite, material.stencilFunc,
  56104. material.stencilFail, material.stencilZFail, material.stencilZPass,
  56105. material.stencilFuncMask, material.stencilWriteMask,
  56106. material.side,
  56107. frontFaceCW,
  56108. utils.getSampleCountRenderContext( renderContext ),
  56109. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  56110. utils.getPrimitiveTopology( object, material ),
  56111. renderObject.getGeometryCacheKey(),
  56112. renderObject.clippingContextCacheKey
  56113. ].join();
  56114. }
  56115. // textures
  56116. /**
  56117. * Updates a GPU sampler for the given texture.
  56118. *
  56119. * @param {Texture} texture - The texture to update the sampler for.
  56120. * @return {string} The current sampler key.
  56121. */
  56122. updateSampler( texture ) {
  56123. return this.textureUtils.updateSampler( texture );
  56124. }
  56125. /**
  56126. * Creates a default texture for the given texture that can be used
  56127. * as a placeholder until the actual texture is ready for usage.
  56128. *
  56129. * @param {Texture} texture - The texture to create a default texture for.
  56130. * @return {boolean} Whether the sampler has been updated or not.
  56131. */
  56132. createDefaultTexture( texture ) {
  56133. return this.textureUtils.createDefaultTexture( texture );
  56134. }
  56135. /**
  56136. * Defines a texture on the GPU for the given texture object.
  56137. *
  56138. * @param {Texture} texture - The texture.
  56139. * @param {Object} [options={}] - Optional configuration parameter.
  56140. */
  56141. createTexture( texture, options ) {
  56142. this.textureUtils.createTexture( texture, options );
  56143. }
  56144. /**
  56145. * Uploads the updated texture data to the GPU.
  56146. *
  56147. * @param {Texture} texture - The texture.
  56148. * @param {Object} [options={}] - Optional configuration parameter.
  56149. */
  56150. updateTexture( texture, options ) {
  56151. this.textureUtils.updateTexture( texture, options );
  56152. }
  56153. /**
  56154. * Generates mipmaps for the given texture.
  56155. *
  56156. * @param {Texture} texture - The texture.
  56157. */
  56158. generateMipmaps( texture ) {
  56159. this.textureUtils.generateMipmaps( texture );
  56160. }
  56161. /**
  56162. * Destroys the GPU data for the given texture object.
  56163. *
  56164. * @param {Texture} texture - The texture.
  56165. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  56166. */
  56167. destroyTexture( texture, isDefaultTexture = false ) {
  56168. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  56169. }
  56170. /**
  56171. * Returns texture data as a typed array.
  56172. *
  56173. * @async
  56174. * @param {Texture} texture - The texture to copy.
  56175. * @param {number} x - The x coordinate of the copy origin.
  56176. * @param {number} y - The y coordinate of the copy origin.
  56177. * @param {number} width - The width of the copy.
  56178. * @param {number} height - The height of the copy.
  56179. * @param {number} faceIndex - The face index.
  56180. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  56181. */
  56182. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  56183. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  56184. }
  56185. /**
  56186. * Inits a time stamp query for the given render context.
  56187. *
  56188. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  56189. * @param {number} uid - Unique id for the context (e.g. render context id).
  56190. * @param {Object} descriptor - The query descriptor.
  56191. */
  56192. initTimestampQuery( type, uid, descriptor ) {
  56193. if ( ! this.trackTimestamp ) return;
  56194. if ( ! this.timestampQueryPool[ type ] ) {
  56195. // TODO: Variable maxQueries?
  56196. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  56197. }
  56198. const timestampQueryPool = this.timestampQueryPool[ type ];
  56199. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  56200. descriptor.timestampWrites = {
  56201. querySet: timestampQueryPool.querySet,
  56202. beginningOfPassWriteIndex: baseOffset,
  56203. endOfPassWriteIndex: baseOffset + 1,
  56204. };
  56205. }
  56206. // node builder
  56207. /**
  56208. * Returns a node builder for the given render object.
  56209. *
  56210. * @param {RenderObject} object - The render object.
  56211. * @param {Renderer} renderer - The renderer.
  56212. * @return {WGSLNodeBuilder} The node builder.
  56213. */
  56214. createNodeBuilder( object, renderer ) {
  56215. return new WGSLNodeBuilder( object, renderer );
  56216. }
  56217. // program
  56218. /**
  56219. * Creates a shader program from the given programmable stage.
  56220. *
  56221. * @param {ProgrammableStage} program - The programmable stage.
  56222. */
  56223. createProgram( program ) {
  56224. const programGPU = this.get( program );
  56225. programGPU.module = {
  56226. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  56227. entryPoint: 'main'
  56228. };
  56229. }
  56230. /**
  56231. * Destroys the shader program of the given programmable stage.
  56232. *
  56233. * @param {ProgrammableStage} program - The programmable stage.
  56234. */
  56235. destroyProgram( program ) {
  56236. this.delete( program );
  56237. }
  56238. // pipelines
  56239. /**
  56240. * Creates a render pipeline for the given render object.
  56241. *
  56242. * @param {RenderObject} renderObject - The render object.
  56243. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  56244. */
  56245. createRenderPipeline( renderObject, promises ) {
  56246. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  56247. }
  56248. /**
  56249. * Creates a compute pipeline for the given compute node.
  56250. *
  56251. * @param {ComputePipeline} computePipeline - The compute pipeline.
  56252. * @param {Array<BindGroup>} bindings - The bindings.
  56253. */
  56254. createComputePipeline( computePipeline, bindings ) {
  56255. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  56256. }
  56257. /**
  56258. * Prepares the state for encoding render bundles.
  56259. *
  56260. * @param {RenderContext} renderContext - The render context.
  56261. */
  56262. beginBundle( renderContext ) {
  56263. const renderContextData = this.get( renderContext );
  56264. renderContextData._currentPass = renderContextData.currentPass;
  56265. renderContextData._currentSets = renderContextData.currentSets;
  56266. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  56267. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  56268. }
  56269. /**
  56270. * After processing render bundles this method finalizes related work.
  56271. *
  56272. * @param {RenderContext} renderContext - The render context.
  56273. * @param {RenderBundle} bundle - The render bundle.
  56274. */
  56275. finishBundle( renderContext, bundle ) {
  56276. const renderContextData = this.get( renderContext );
  56277. const bundleEncoder = renderContextData.currentPass;
  56278. const bundleGPU = bundleEncoder.finish();
  56279. this.get( bundle ).bundleGPU = bundleGPU;
  56280. // restore render pass state
  56281. renderContextData.currentSets = renderContextData._currentSets;
  56282. renderContextData.currentPass = renderContextData._currentPass;
  56283. }
  56284. /**
  56285. * Adds a render bundle to the render context data.
  56286. *
  56287. * @param {RenderContext} renderContext - The render context.
  56288. * @param {RenderBundle} bundle - The render bundle to add.
  56289. */
  56290. addBundle( renderContext, bundle ) {
  56291. const renderContextData = this.get( renderContext );
  56292. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  56293. }
  56294. // bindings
  56295. /**
  56296. * Creates bindings from the given bind group definition.
  56297. *
  56298. * @param {BindGroup} bindGroup - The bind group.
  56299. * @param {Array<BindGroup>} bindings - Array of bind groups.
  56300. * @param {number} cacheIndex - The cache index.
  56301. * @param {number} version - The version.
  56302. */
  56303. createBindings( bindGroup, bindings, cacheIndex, version ) {
  56304. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  56305. }
  56306. /**
  56307. * Updates the given bind group definition.
  56308. *
  56309. * @param {BindGroup} bindGroup - The bind group.
  56310. * @param {Array<BindGroup>} bindings - Array of bind groups.
  56311. * @param {number} cacheIndex - The cache index.
  56312. * @param {number} version - The version.
  56313. */
  56314. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  56315. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  56316. }
  56317. /**
  56318. * Updates a buffer binding.
  56319. *
  56320. * @param {Buffer} binding - The buffer binding to update.
  56321. */
  56322. updateBinding( binding ) {
  56323. this.bindingUtils.updateBinding( binding );
  56324. }
  56325. // attributes
  56326. /**
  56327. * Creates the buffer of an indexed shader attribute.
  56328. *
  56329. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  56330. */
  56331. createIndexAttribute( attribute ) {
  56332. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  56333. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  56334. usage |= GPUBufferUsage.STORAGE;
  56335. }
  56336. this.attributeUtils.createAttribute( attribute, usage );
  56337. }
  56338. /**
  56339. * Creates the GPU buffer of a shader attribute.
  56340. *
  56341. * @param {BufferAttribute} attribute - The buffer attribute.
  56342. */
  56343. createAttribute( attribute ) {
  56344. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56345. }
  56346. /**
  56347. * Creates the GPU buffer of a storage attribute.
  56348. *
  56349. * @param {BufferAttribute} attribute - The buffer attribute.
  56350. */
  56351. createStorageAttribute( attribute ) {
  56352. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56353. }
  56354. /**
  56355. * Creates the GPU buffer of an indirect storage attribute.
  56356. *
  56357. * @param {BufferAttribute} attribute - The buffer attribute.
  56358. */
  56359. createIndirectStorageAttribute( attribute ) {
  56360. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56361. }
  56362. /**
  56363. * Updates the GPU buffer of a shader attribute.
  56364. *
  56365. * @param {BufferAttribute} attribute - The buffer attribute to update.
  56366. */
  56367. updateAttribute( attribute ) {
  56368. this.attributeUtils.updateAttribute( attribute );
  56369. }
  56370. /**
  56371. * Destroys the GPU buffer of a shader attribute.
  56372. *
  56373. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  56374. */
  56375. destroyAttribute( attribute ) {
  56376. this.attributeUtils.destroyAttribute( attribute );
  56377. }
  56378. // canvas
  56379. /**
  56380. * Triggers an update of the default render pass descriptor.
  56381. */
  56382. updateSize() {
  56383. this.delete( this.renderer.getCanvasTarget() );
  56384. }
  56385. // utils public
  56386. /**
  56387. * Returns the maximum anisotropy texture filtering value.
  56388. *
  56389. * @return {number} The maximum anisotropy texture filtering value.
  56390. */
  56391. getMaxAnisotropy() {
  56392. return 16;
  56393. }
  56394. /**
  56395. * Checks if the given feature is supported by the backend.
  56396. *
  56397. * @param {string} name - The feature's name.
  56398. * @return {boolean} Whether the feature is supported or not.
  56399. */
  56400. hasFeature( name ) {
  56401. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  56402. return this.device.features.has( name );
  56403. }
  56404. /**
  56405. * Copies data of the given source texture to the given destination texture.
  56406. *
  56407. * @param {Texture} srcTexture - The source texture.
  56408. * @param {Texture} dstTexture - The destination texture.
  56409. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  56410. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  56411. * @param {number} [srcLevel=0] - The mipmap level to copy.
  56412. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  56413. */
  56414. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  56415. let dstX = 0;
  56416. let dstY = 0;
  56417. let dstZ = 0;
  56418. let srcX = 0;
  56419. let srcY = 0;
  56420. let srcZ = 0;
  56421. let srcWidth = srcTexture.image.width;
  56422. let srcHeight = srcTexture.image.height;
  56423. let srcDepth = 1;
  56424. if ( srcRegion !== null ) {
  56425. if ( srcRegion.isBox3 === true ) {
  56426. srcX = srcRegion.min.x;
  56427. srcY = srcRegion.min.y;
  56428. srcZ = srcRegion.min.z;
  56429. srcWidth = srcRegion.max.x - srcRegion.min.x;
  56430. srcHeight = srcRegion.max.y - srcRegion.min.y;
  56431. srcDepth = srcRegion.max.z - srcRegion.min.z;
  56432. } else {
  56433. // Assume it's a Box2
  56434. srcX = srcRegion.min.x;
  56435. srcY = srcRegion.min.y;
  56436. srcWidth = srcRegion.max.x - srcRegion.min.x;
  56437. srcHeight = srcRegion.max.y - srcRegion.min.y;
  56438. srcDepth = 1;
  56439. }
  56440. }
  56441. if ( dstPosition !== null ) {
  56442. dstX = dstPosition.x;
  56443. dstY = dstPosition.y;
  56444. dstZ = dstPosition.z || 0;
  56445. }
  56446. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  56447. const sourceGPU = this.get( srcTexture ).texture;
  56448. const destinationGPU = this.get( dstTexture ).texture;
  56449. encoder.copyTextureToTexture(
  56450. {
  56451. texture: sourceGPU,
  56452. mipLevel: srcLevel,
  56453. origin: { x: srcX, y: srcY, z: srcZ }
  56454. },
  56455. {
  56456. texture: destinationGPU,
  56457. mipLevel: dstLevel,
  56458. origin: { x: dstX, y: dstY, z: dstZ }
  56459. },
  56460. [
  56461. srcWidth,
  56462. srcHeight,
  56463. srcDepth
  56464. ]
  56465. );
  56466. this.device.queue.submit( [ encoder.finish() ] );
  56467. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  56468. this.textureUtils.generateMipmaps( dstTexture );
  56469. }
  56470. }
  56471. /**
  56472. * Copies the current bound framebuffer to the given texture.
  56473. *
  56474. * @param {Texture} texture - The destination texture.
  56475. * @param {RenderContext} renderContext - The render context.
  56476. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  56477. */
  56478. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  56479. const renderContextData = this.get( renderContext );
  56480. let sourceGPU = null;
  56481. if ( renderContext.renderTarget ) {
  56482. if ( texture.isDepthTexture ) {
  56483. sourceGPU = this.get( renderContext.depthTexture ).texture;
  56484. } else {
  56485. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  56486. }
  56487. } else {
  56488. if ( texture.isDepthTexture ) {
  56489. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  56490. } else {
  56491. sourceGPU = this.context.getCurrentTexture();
  56492. }
  56493. }
  56494. const destinationGPU = this.get( texture ).texture;
  56495. if ( sourceGPU.format !== destinationGPU.format ) {
  56496. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  56497. return;
  56498. }
  56499. let encoder;
  56500. if ( renderContextData.currentPass ) {
  56501. renderContextData.currentPass.end();
  56502. encoder = renderContextData.encoder;
  56503. } else {
  56504. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  56505. }
  56506. encoder.copyTextureToTexture(
  56507. {
  56508. texture: sourceGPU,
  56509. origin: [ rectangle.x, rectangle.y, 0 ],
  56510. },
  56511. {
  56512. texture: destinationGPU
  56513. },
  56514. [
  56515. rectangle.z,
  56516. rectangle.w
  56517. ]
  56518. );
  56519. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  56520. // might be out-of-sync, see #31768
  56521. if ( texture.generateMipmaps ) {
  56522. this.textureUtils.generateMipmaps( texture, encoder );
  56523. }
  56524. if ( renderContextData.currentPass ) {
  56525. const { descriptor } = renderContextData;
  56526. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  56527. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  56528. }
  56529. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  56530. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  56531. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  56532. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  56533. if ( renderContext.viewport ) {
  56534. this.updateViewport( renderContext );
  56535. }
  56536. if ( renderContext.scissor ) {
  56537. this.updateScissor( renderContext );
  56538. }
  56539. } else {
  56540. this.device.queue.submit( [ encoder.finish() ] );
  56541. }
  56542. }
  56543. dispose() {
  56544. this.textureUtils.dispose();
  56545. }
  56546. }
  56547. /**
  56548. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  56549. *
  56550. * @augments SpotLight
  56551. */
  56552. class IESSpotLight extends SpotLight {
  56553. /**
  56554. * Constructs a new IES spot light.
  56555. *
  56556. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  56557. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  56558. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  56559. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  56560. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  56561. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  56562. */
  56563. constructor( color, intensity, distance, angle, penumbra, decay ) {
  56564. super( color, intensity, distance, angle, penumbra, decay );
  56565. /**
  56566. * TODO
  56567. *
  56568. * @type {?Texture}
  56569. * @default null
  56570. */
  56571. this.iesMap = null;
  56572. }
  56573. copy( source, recursive ) {
  56574. super.copy( source, recursive );
  56575. this.iesMap = source.iesMap;
  56576. return this;
  56577. }
  56578. }
  56579. /**
  56580. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  56581. *
  56582. * @augments SpotLight
  56583. */
  56584. class ProjectorLight extends SpotLight {
  56585. /**
  56586. * Constructs a new projector light.
  56587. *
  56588. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  56589. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  56590. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  56591. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  56592. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  56593. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  56594. */
  56595. constructor( color, intensity, distance, angle, penumbra, decay ) {
  56596. super( color, intensity, distance, angle, penumbra, decay );
  56597. /**
  56598. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  56599. *
  56600. * @type {?number}
  56601. * @default null
  56602. */
  56603. this.aspect = null;
  56604. }
  56605. copy( source, recursive ) {
  56606. super.copy( source, recursive );
  56607. this.aspect = source.aspect;
  56608. return this;
  56609. }
  56610. }
  56611. /**
  56612. * This version of a node library represents a basic version
  56613. * just focusing on lights and tone mapping techniques.
  56614. *
  56615. * @private
  56616. * @augments NodeLibrary
  56617. */
  56618. class BasicNodeLibrary extends NodeLibrary {
  56619. /**
  56620. * Constructs a new basic node library.
  56621. */
  56622. constructor() {
  56623. super();
  56624. this.addLight( PointLightNode, PointLight );
  56625. this.addLight( DirectionalLightNode, DirectionalLight );
  56626. this.addLight( RectAreaLightNode, RectAreaLight );
  56627. this.addLight( SpotLightNode, SpotLight );
  56628. this.addLight( AmbientLightNode, AmbientLight );
  56629. this.addLight( HemisphereLightNode, HemisphereLight );
  56630. this.addLight( LightProbeNode, LightProbe );
  56631. this.addLight( IESSpotLightNode, IESSpotLight );
  56632. this.addLight( ProjectorLightNode, ProjectorLight );
  56633. this.addToneMapping( linearToneMapping, LinearToneMapping );
  56634. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  56635. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  56636. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  56637. this.addToneMapping( agxToneMapping, AgXToneMapping );
  56638. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  56639. }
  56640. }
  56641. /**
  56642. * This alternative version of {@link WebGPURenderer} only supports node materials.
  56643. * So classes like `MeshBasicMaterial` are not compatible.
  56644. *
  56645. * @private
  56646. * @augments Renderer
  56647. */
  56648. class WebGPURenderer extends Renderer {
  56649. /**
  56650. * Constructs a new WebGPU renderer.
  56651. *
  56652. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  56653. */
  56654. constructor( parameters = {} ) {
  56655. let BackendClass;
  56656. if ( parameters.forceWebGL ) {
  56657. BackendClass = WebGLBackend;
  56658. } else {
  56659. BackendClass = WebGPUBackend;
  56660. parameters.getFallback = () => {
  56661. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  56662. return new WebGLBackend( parameters );
  56663. };
  56664. }
  56665. const backend = new BackendClass( parameters );
  56666. super( backend, parameters );
  56667. /**
  56668. * The generic default value is overwritten with the
  56669. * standard node library for type mapping. Material
  56670. * mapping is not supported with this version.
  56671. *
  56672. * @type {BasicNodeLibrary}
  56673. */
  56674. this.library = new BasicNodeLibrary();
  56675. /**
  56676. * This flag can be used for type testing.
  56677. *
  56678. * @type {boolean}
  56679. * @readonly
  56680. * @default true
  56681. */
  56682. this.isWebGPURenderer = true;
  56683. }
  56684. }
  56685. /**
  56686. * A specialized group which enables applications access to the
  56687. * Render Bundle API of WebGPU. The group with all its descendant nodes
  56688. * are considered as one render bundle and processed as such by
  56689. * the renderer.
  56690. *
  56691. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  56692. * With a WebGL backend, the group can technically be rendered but without
  56693. * any performance improvements.
  56694. *
  56695. * @augments Group
  56696. */
  56697. class BundleGroup extends Group {
  56698. /**
  56699. * Constructs a new bundle group.
  56700. */
  56701. constructor() {
  56702. super();
  56703. /**
  56704. * This flag can be used for type testing.
  56705. *
  56706. * @type {boolean}
  56707. * @readonly
  56708. * @default true
  56709. */
  56710. this.isBundleGroup = true;
  56711. /**
  56712. * This property is only relevant for detecting types
  56713. * during serialization/deserialization. It should always
  56714. * match the class name.
  56715. *
  56716. * @type {string}
  56717. * @readonly
  56718. * @default 'BundleGroup'
  56719. */
  56720. this.type = 'BundleGroup';
  56721. /**
  56722. * Whether the bundle is static or not. When set to `true`, the structure
  56723. * is assumed to be static and does not change. E.g. no new objects are
  56724. * added to the group
  56725. *
  56726. * If a change is required, an update can still be forced by setting the
  56727. * `needsUpdate` flag to `true`.
  56728. *
  56729. * @type {boolean}
  56730. * @default true
  56731. */
  56732. this.static = true;
  56733. /**
  56734. * The bundle group's version.
  56735. *
  56736. * @type {number}
  56737. * @readonly
  56738. * @default 0
  56739. */
  56740. this.version = 0;
  56741. }
  56742. /**
  56743. * Set this property to `true` when the bundle group has changed.
  56744. *
  56745. * @type {boolean}
  56746. * @default false
  56747. * @param {boolean} value
  56748. */
  56749. set needsUpdate( value ) {
  56750. if ( value === true ) this.version ++;
  56751. }
  56752. }
  56753. /**
  56754. * This module is responsible to manage the post processing setups in apps.
  56755. * You usually create a single instance of this class and use it to define
  56756. * the output of your post processing effect chain.
  56757. * ```js
  56758. * const postProcessing = new PostProcessing( renderer );
  56759. *
  56760. * const scenePass = pass( scene, camera );
  56761. *
  56762. * postProcessing.outputNode = scenePass;
  56763. * ```
  56764. *
  56765. * Note: This module can only be used with `WebGPURenderer`.
  56766. */
  56767. class PostProcessing {
  56768. /**
  56769. * Constructs a new post processing management module.
  56770. *
  56771. * @param {Renderer} renderer - A reference to the renderer.
  56772. * @param {Node<vec4>} outputNode - An optional output node.
  56773. */
  56774. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  56775. /**
  56776. * A reference to the renderer.
  56777. *
  56778. * @type {Renderer}
  56779. */
  56780. this.renderer = renderer;
  56781. /**
  56782. * A node which defines the final output of the post
  56783. * processing. This is usually the last node in a chain
  56784. * of effect nodes.
  56785. *
  56786. * @type {Node<vec4>}
  56787. */
  56788. this.outputNode = outputNode;
  56789. /**
  56790. * Whether the default output tone mapping and color
  56791. * space transformation should be enabled or not.
  56792. *
  56793. * It is enabled by default by it must be disabled when
  56794. * effects must be executed after tone mapping and color
  56795. * space conversion. A typical example is FXAA which
  56796. * requires sRGB input.
  56797. *
  56798. * When set to `false`, the app must control the output
  56799. * transformation with `RenderOutputNode`.
  56800. *
  56801. * ```js
  56802. * const outputPass = renderOutput( scenePass );
  56803. * ```
  56804. *
  56805. * @type {boolean}
  56806. */
  56807. this.outputColorTransform = true;
  56808. /**
  56809. * Must be set to `true` when the output node changes.
  56810. *
  56811. * @type {Node<vec4>}
  56812. */
  56813. this.needsUpdate = true;
  56814. const material = new NodeMaterial();
  56815. material.name = 'PostProcessing';
  56816. /**
  56817. * The full screen quad that is used to render
  56818. * the effects.
  56819. *
  56820. * @private
  56821. * @type {QuadMesh}
  56822. */
  56823. this._quadMesh = new QuadMesh( material );
  56824. this._quadMesh.name = 'Post-Processing';
  56825. /**
  56826. * The context of the post processing stack.
  56827. *
  56828. * @private
  56829. * @type {?Object}
  56830. * @default null
  56831. */
  56832. this._context = null;
  56833. }
  56834. /**
  56835. * When `PostProcessing` is used to apply post processing effects,
  56836. * the application must use this version of `render()` inside
  56837. * its animation loop (not the one from the renderer).
  56838. */
  56839. render() {
  56840. const renderer = this.renderer;
  56841. this._update();
  56842. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  56843. const toneMapping = renderer.toneMapping;
  56844. const outputColorSpace = renderer.outputColorSpace;
  56845. renderer.toneMapping = NoToneMapping;
  56846. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  56847. //
  56848. const currentXR = renderer.xr.enabled;
  56849. renderer.xr.enabled = false;
  56850. this._quadMesh.render( renderer );
  56851. renderer.xr.enabled = currentXR;
  56852. //
  56853. renderer.toneMapping = toneMapping;
  56854. renderer.outputColorSpace = outputColorSpace;
  56855. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  56856. }
  56857. /**
  56858. * Returns the current context of the post processing stack.
  56859. *
  56860. * @readonly
  56861. * @type {?Object}
  56862. */
  56863. get context() {
  56864. return this._context;
  56865. }
  56866. /**
  56867. * Frees internal resources.
  56868. */
  56869. dispose() {
  56870. this._quadMesh.material.dispose();
  56871. }
  56872. /**
  56873. * Updates the state of the module.
  56874. *
  56875. * @private
  56876. */
  56877. _update() {
  56878. if ( this.needsUpdate === true ) {
  56879. const renderer = this.renderer;
  56880. const toneMapping = renderer.toneMapping;
  56881. const outputColorSpace = renderer.outputColorSpace;
  56882. const context = {
  56883. postProcessing: this,
  56884. onBeforePostProcessing: null,
  56885. onAfterPostProcessing: null
  56886. };
  56887. let outputNode = this.outputNode;
  56888. if ( this.outputColorTransform === true ) {
  56889. outputNode = outputNode.context( context );
  56890. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  56891. } else {
  56892. context.toneMapping = toneMapping;
  56893. context.outputColorSpace = outputColorSpace;
  56894. outputNode = outputNode.context( context );
  56895. }
  56896. this._context = context;
  56897. this._quadMesh.material.fragmentNode = outputNode;
  56898. this._quadMesh.material.needsUpdate = true;
  56899. this.needsUpdate = false;
  56900. }
  56901. }
  56902. /**
  56903. * When `PostProcessing` is used to apply post processing effects,
  56904. * the application must use this version of `renderAsync()` inside
  56905. * its animation loop (not the one from the renderer).
  56906. *
  56907. * @async
  56908. * @deprecated
  56909. * @return {Promise} A Promise that resolves when the render has been finished.
  56910. */
  56911. async renderAsync() {
  56912. warnOnce( 'PostProcessing: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  56913. await this.renderer.init();
  56914. this.render();
  56915. }
  56916. }
  56917. /**
  56918. * This special type of texture is intended for compute shaders.
  56919. * It can be used to compute the data of a texture with a compute shader.
  56920. *
  56921. * Note: This type of texture can only be used with `WebGPURenderer`
  56922. * and a WebGPU backend.
  56923. *
  56924. * @augments Texture
  56925. */
  56926. class StorageTexture extends Texture {
  56927. /**
  56928. * Constructs a new storage texture.
  56929. *
  56930. * @param {number} [width=1] - The storage texture's width.
  56931. * @param {number} [height=1] - The storage texture's height.
  56932. */
  56933. constructor( width = 1, height = 1 ) {
  56934. super();
  56935. /**
  56936. * The image object which just represents the texture's dimension.
  56937. *
  56938. * @type {{width: number, height: number}}
  56939. */
  56940. this.image = { width, height };
  56941. /**
  56942. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  56943. *
  56944. * @type {number}
  56945. */
  56946. this.magFilter = LinearFilter;
  56947. /**
  56948. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  56949. *
  56950. * @type {number}
  56951. */
  56952. this.minFilter = LinearFilter;
  56953. /**
  56954. * This flag can be used for type testing.
  56955. *
  56956. * @type {boolean}
  56957. * @readonly
  56958. * @default true
  56959. */
  56960. this.isStorageTexture = true;
  56961. /**
  56962. * When `true`, mipmaps will be auto-generated after compute writes.
  56963. * When `false`, mipmaps must be written manually via compute shaders.
  56964. *
  56965. * @type {boolean}
  56966. * @default true
  56967. */
  56968. this.mipmapsAutoUpdate = true;
  56969. }
  56970. /**
  56971. * Sets the size of the storage texture.
  56972. *
  56973. * @param {number} width - The new width of the storage texture.
  56974. * @param {number} height - The new height of the storage texture.
  56975. */
  56976. setSize( width, height ) {
  56977. if ( this.image.width !== width || this.image.height !== height ) {
  56978. this.image.width = width;
  56979. this.image.height = height;
  56980. this.dispose();
  56981. }
  56982. }
  56983. }
  56984. /**
  56985. * This special type of buffer attribute is intended for compute shaders.
  56986. * It can be used to encode draw parameters for indirect draw calls.
  56987. *
  56988. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  56989. * and a WebGPU backend.
  56990. *
  56991. * @augments StorageBufferAttribute
  56992. */
  56993. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  56994. /**
  56995. * Constructs a new storage buffer attribute.
  56996. *
  56997. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  56998. * The subsequent parameter is then obsolete.
  56999. * @param {number} itemSize - The item size.
  57000. */
  57001. constructor( count, itemSize ) {
  57002. super( count, itemSize, Uint32Array );
  57003. /**
  57004. * This flag can be used for type testing.
  57005. *
  57006. * @type {boolean}
  57007. * @readonly
  57008. * @default true
  57009. */
  57010. this.isIndirectStorageBufferAttribute = true;
  57011. }
  57012. }
  57013. /**
  57014. * A loader for loading node objects in the three.js JSON Object/Scene format.
  57015. *
  57016. * @augments Loader
  57017. */
  57018. class NodeLoader extends Loader {
  57019. /**
  57020. * Constructs a new node loader.
  57021. *
  57022. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57023. */
  57024. constructor( manager ) {
  57025. super( manager );
  57026. /**
  57027. * Represents a dictionary of textures.
  57028. *
  57029. * @type {Object<string,Texture>}
  57030. */
  57031. this.textures = {};
  57032. /**
  57033. * Represents a dictionary of node types.
  57034. *
  57035. * @type {Object<string,Node.constructor>}
  57036. */
  57037. this.nodes = {};
  57038. }
  57039. /**
  57040. * Loads the node definitions from the given URL.
  57041. *
  57042. * @param {string} url - The path/URL of the file to be loaded.
  57043. * @param {Function} onLoad - Will be called when load completes.
  57044. * @param {Function} onProgress - Will be called while load progresses.
  57045. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  57046. */
  57047. load( url, onLoad, onProgress, onError ) {
  57048. const loader = new FileLoader( this.manager );
  57049. loader.setPath( this.path );
  57050. loader.setRequestHeader( this.requestHeader );
  57051. loader.setWithCredentials( this.withCredentials );
  57052. loader.load( url, ( text ) => {
  57053. try {
  57054. onLoad( this.parse( JSON.parse( text ) ) );
  57055. } catch ( e ) {
  57056. if ( onError ) {
  57057. onError( e );
  57058. } else {
  57059. error( e );
  57060. }
  57061. this.manager.itemError( url );
  57062. }
  57063. }, onProgress, onError );
  57064. }
  57065. /**
  57066. * Parse the node dependencies for the loaded node.
  57067. *
  57068. * @param {Array<Object>} [json] - The JSON definition
  57069. * @return {Object<string,Node>} A dictionary with node dependencies.
  57070. */
  57071. parseNodes( json ) {
  57072. const nodes = {};
  57073. if ( json !== undefined ) {
  57074. for ( const nodeJSON of json ) {
  57075. const { uuid, type } = nodeJSON;
  57076. nodes[ uuid ] = this.createNodeFromType( type );
  57077. nodes[ uuid ].uuid = uuid;
  57078. }
  57079. const meta = { nodes, textures: this.textures };
  57080. for ( const nodeJSON of json ) {
  57081. nodeJSON.meta = meta;
  57082. const node = nodes[ nodeJSON.uuid ];
  57083. node.deserialize( nodeJSON );
  57084. delete nodeJSON.meta;
  57085. }
  57086. }
  57087. return nodes;
  57088. }
  57089. /**
  57090. * Parses the node from the given JSON.
  57091. *
  57092. * @param {Object} json - The JSON definition
  57093. * @param {string} json.type - The node type.
  57094. * @param {string} json.uuid - The node UUID.
  57095. * @param {Array<Object>} [json.nodes] - The node dependencies.
  57096. * @param {Object} [json.meta] - The meta data.
  57097. * @return {Node} The parsed node.
  57098. */
  57099. parse( json ) {
  57100. const node = this.createNodeFromType( json.type );
  57101. node.uuid = json.uuid;
  57102. const nodes = this.parseNodes( json.nodes );
  57103. const meta = { nodes, textures: this.textures };
  57104. json.meta = meta;
  57105. node.deserialize( json );
  57106. delete json.meta;
  57107. return node;
  57108. }
  57109. /**
  57110. * Defines the dictionary of textures.
  57111. *
  57112. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  57113. * @return {NodeLoader} A reference to this loader.
  57114. */
  57115. setTextures( value ) {
  57116. this.textures = value;
  57117. return this;
  57118. }
  57119. /**
  57120. * Defines the dictionary of node types.
  57121. *
  57122. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57123. * @return {NodeLoader} A reference to this loader.
  57124. */
  57125. setNodes( value ) {
  57126. this.nodes = value;
  57127. return this;
  57128. }
  57129. /**
  57130. * Creates a node object from the given type.
  57131. *
  57132. * @param {string} type - The node type.
  57133. * @return {Node} The created node instance.
  57134. */
  57135. createNodeFromType( type ) {
  57136. if ( this.nodes[ type ] === undefined ) {
  57137. error( 'NodeLoader: Node type not found:', type );
  57138. return float();
  57139. }
  57140. return nodeObject( new this.nodes[ type ]() );
  57141. }
  57142. }
  57143. /**
  57144. * A special type of material loader for loading node materials.
  57145. *
  57146. * @augments MaterialLoader
  57147. */
  57148. class NodeMaterialLoader extends MaterialLoader {
  57149. /**
  57150. * Constructs a new node material loader.
  57151. *
  57152. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57153. */
  57154. constructor( manager ) {
  57155. super( manager );
  57156. /**
  57157. * Represents a dictionary of node types.
  57158. *
  57159. * @type {Object<string,Node.constructor>}
  57160. */
  57161. this.nodes = {};
  57162. /**
  57163. * Represents a dictionary of node material types.
  57164. *
  57165. * @type {Object<string,NodeMaterial.constructor>}
  57166. */
  57167. this.nodeMaterials = {};
  57168. }
  57169. /**
  57170. * Parses the node material from the given JSON.
  57171. *
  57172. * @param {Object} json - The JSON definition
  57173. * @return {NodeMaterial}. The parsed material.
  57174. */
  57175. parse( json ) {
  57176. const material = super.parse( json );
  57177. const nodes = this.nodes;
  57178. const inputNodes = json.inputNodes;
  57179. for ( const property in inputNodes ) {
  57180. const uuid = inputNodes[ property ];
  57181. material[ property ] = nodes[ uuid ];
  57182. }
  57183. return material;
  57184. }
  57185. /**
  57186. * Defines the dictionary of node types.
  57187. *
  57188. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57189. * @return {NodeLoader} A reference to this loader.
  57190. */
  57191. setNodes( value ) {
  57192. this.nodes = value;
  57193. return this;
  57194. }
  57195. /**
  57196. * Defines the dictionary of node material types.
  57197. *
  57198. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  57199. * @return {NodeLoader} A reference to this loader.
  57200. */
  57201. setNodeMaterials( value ) {
  57202. this.nodeMaterials = value;
  57203. return this;
  57204. }
  57205. /**
  57206. * Creates a node material from the given type.
  57207. *
  57208. * @param {string} type - The node material type.
  57209. * @return {Node} The created node material instance.
  57210. */
  57211. createMaterialFromType( type ) {
  57212. const materialClass = this.nodeMaterials[ type ];
  57213. if ( materialClass !== undefined ) {
  57214. return new materialClass();
  57215. }
  57216. return super.createMaterialFromType( type );
  57217. }
  57218. }
  57219. /**
  57220. * A special type of object loader for loading 3D objects using
  57221. * node materials.
  57222. *
  57223. * @augments ObjectLoader
  57224. */
  57225. class NodeObjectLoader extends ObjectLoader {
  57226. /**
  57227. * Constructs a new node object loader.
  57228. *
  57229. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57230. */
  57231. constructor( manager ) {
  57232. super( manager );
  57233. /**
  57234. * Represents a dictionary of node types.
  57235. *
  57236. * @type {Object<string,Node.constructor>}
  57237. */
  57238. this.nodes = {};
  57239. /**
  57240. * Represents a dictionary of node material types.
  57241. *
  57242. * @type {Object<string,NodeMaterial.constructor>}
  57243. */
  57244. this.nodeMaterials = {};
  57245. /**
  57246. * A reference to hold the `nodes` JSON property.
  57247. *
  57248. * @private
  57249. * @type {?Object[]}
  57250. */
  57251. this._nodesJSON = null;
  57252. }
  57253. /**
  57254. * Defines the dictionary of node types.
  57255. *
  57256. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57257. * @return {NodeObjectLoader} A reference to this loader.
  57258. */
  57259. setNodes( value ) {
  57260. this.nodes = value;
  57261. return this;
  57262. }
  57263. /**
  57264. * Defines the dictionary of node material types.
  57265. *
  57266. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  57267. * @return {NodeObjectLoader} A reference to this loader.
  57268. */
  57269. setNodeMaterials( value ) {
  57270. this.nodeMaterials = value;
  57271. return this;
  57272. }
  57273. /**
  57274. * Parses the node objects from the given JSON.
  57275. *
  57276. * @param {Object} json - The JSON definition
  57277. * @param {Function} onLoad - The onLoad callback function.
  57278. * @return {Object3D}. The parsed 3D object.
  57279. */
  57280. parse( json, onLoad ) {
  57281. this._nodesJSON = json.nodes;
  57282. const data = super.parse( json, onLoad );
  57283. this._nodesJSON = null; // dispose
  57284. return data;
  57285. }
  57286. /**
  57287. * Parses the node objects from the given JSON and textures.
  57288. *
  57289. * @param {Object[]} json - The JSON definition
  57290. * @param {Object<string,Texture>} textures - The texture library.
  57291. * @return {Object<string,Node>}. The parsed nodes.
  57292. */
  57293. parseNodes( json, textures ) {
  57294. if ( json !== undefined ) {
  57295. const loader = new NodeLoader();
  57296. loader.setNodes( this.nodes );
  57297. loader.setTextures( textures );
  57298. return loader.parseNodes( json );
  57299. }
  57300. return {};
  57301. }
  57302. /**
  57303. * Parses the node objects from the given JSON and textures.
  57304. *
  57305. * @param {Object} json - The JSON definition
  57306. * @param {Object<string,Texture>} textures - The texture library.
  57307. * @return {Object<string,NodeMaterial>}. The parsed materials.
  57308. */
  57309. parseMaterials( json, textures ) {
  57310. const materials = {};
  57311. if ( json !== undefined ) {
  57312. const nodes = this.parseNodes( this._nodesJSON, textures );
  57313. const loader = new NodeMaterialLoader();
  57314. loader.setTextures( textures );
  57315. loader.setNodes( nodes );
  57316. loader.setNodeMaterials( this.nodeMaterials );
  57317. for ( let i = 0, l = json.length; i < l; i ++ ) {
  57318. const data = json[ i ];
  57319. materials[ data.uuid ] = loader.parse( data );
  57320. }
  57321. }
  57322. return materials;
  57323. }
  57324. }
  57325. /**
  57326. * In earlier three.js versions, clipping was defined globally
  57327. * on the renderer or on material level. This special version of
  57328. * `THREE.Group` allows to encode the clipping state into the scene
  57329. * graph. Meaning if you create an instance of this group, all
  57330. * descendant 3D objects will be affected by the respective clipping
  57331. * planes.
  57332. *
  57333. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  57334. *
  57335. * @augments Group
  57336. */
  57337. class ClippingGroup extends Group {
  57338. /**
  57339. * Constructs a new clipping group.
  57340. */
  57341. constructor() {
  57342. super();
  57343. /**
  57344. * This flag can be used for type testing.
  57345. *
  57346. * @type {boolean}
  57347. * @readonly
  57348. * @default true
  57349. */
  57350. this.isClippingGroup = true;
  57351. /**
  57352. * An array with clipping planes.
  57353. *
  57354. * @type {Array<Plane>}
  57355. */
  57356. this.clippingPlanes = [];
  57357. /**
  57358. * Whether clipping should be enabled or not.
  57359. *
  57360. * @type {boolean}
  57361. * @default true
  57362. */
  57363. this.enabled = true;
  57364. /**
  57365. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  57366. *
  57367. * @type {boolean}
  57368. * @default false
  57369. */
  57370. this.clipIntersection = false;
  57371. /**
  57372. * Whether shadows should be clipped or not.
  57373. *
  57374. * @type {boolean}
  57375. * @default false
  57376. */
  57377. this.clipShadows = false;
  57378. }
  57379. }
  57380. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BitcastNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, Camera, CanvasTarget, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, EventNode, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InspectorBase, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, IsolateNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoopNode, MRTNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, 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号