three.webgpu.js 1.8 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923
  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, InterleavedBuffer, InterleavedBufferAttribute, DynamicDrawUsage, NoColorSpace, log as log$1, warnOnce, Texture, UnsignedIntType, IntType, NearestFilter, Sphere, BackSide, DoubleSide, Euler, CubeTexture, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, OrthographicCamera, PerspectiveCamera, RenderTarget, LinearSRGBColorSpace, RGBAFormat, HalfFloatType, CubeUVReflectionMapping, BufferGeometry, BufferAttribute, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, arrayNeedsUint32, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, Plane, Object3D, LinearMipMapLinearFilter, Float32BufferAttribute, UVMapping, VSMShadowMap, LessCompare, RGFormat, BasicShadowMap, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, AddEquation, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFShadowMap, FrustumArray, Frustum, DataTexture, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, TimestampQuery, createCanvasElement, ReverseSubtractEquation, SubtractEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, UnsignedInt101111Type, AlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessEqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, getByteLength, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExternalTexture, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, Timer, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, getConsoleFunction, setConsoleFunction } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'aoMapIntensity',
  16. 'attenuationColor',
  17. 'attenuationDistance',
  18. 'bumpMap',
  19. 'clearcoat',
  20. 'clearcoatMap',
  21. 'clearcoatNormalMap',
  22. 'clearcoatNormalScale',
  23. 'clearcoatRoughness',
  24. 'color',
  25. 'dispersion',
  26. 'displacementMap',
  27. 'emissive',
  28. 'emissiveIntensity',
  29. 'emissiveMap',
  30. 'envMap',
  31. 'envMapIntensity',
  32. 'gradientMap',
  33. 'ior',
  34. 'iridescence',
  35. 'iridescenceIOR',
  36. 'iridescenceMap',
  37. 'iridescenceThicknessMap',
  38. 'lightMap',
  39. 'lightMapIntensity',
  40. 'map',
  41. 'matcap',
  42. 'metalness',
  43. 'metalnessMap',
  44. 'normalMap',
  45. 'normalScale',
  46. 'opacity',
  47. 'roughness',
  48. 'roughnessMap',
  49. 'sheen',
  50. 'sheenColor',
  51. 'sheenColorMap',
  52. 'sheenRoughnessMap',
  53. 'shininess',
  54. 'specular',
  55. 'specularColor',
  56. 'specularColorMap',
  57. 'specularIntensity',
  58. 'specularIntensityMap',
  59. 'specularMap',
  60. 'thickness',
  61. 'transmission',
  62. 'transmissionMap'
  63. ];
  64. /**
  65. * A WeakMap to cache lights data for node materials.
  66. * Cache lights data by render ID to avoid unnecessary recalculations.
  67. *
  68. * @private
  69. * @type {WeakMap<LightsNode,Object>}
  70. */
  71. const _lightsCache = new WeakMap();
  72. /**
  73. * This class is used by {@link WebGPURenderer} as management component.
  74. * It's primary purpose is to determine whether render objects require a
  75. * refresh right before they are going to be rendered or not.
  76. */
  77. class NodeMaterialObserver {
  78. /**
  79. * Constructs a new node material observer.
  80. *
  81. * @param {NodeBuilder} builder - The node builder.
  82. */
  83. constructor( builder ) {
  84. /**
  85. * A node material can be used by more than one render object so the
  86. * monitor must maintain a list of render objects.
  87. *
  88. * @type {WeakMap<RenderObject,Object>}
  89. */
  90. this.renderObjects = new WeakMap();
  91. /**
  92. * Whether the material uses node objects or not.
  93. *
  94. * @type {boolean}
  95. */
  96. this.hasNode = this.containsNode( builder );
  97. /**
  98. * Whether the node builder's 3D object is animated or not.
  99. *
  100. * @type {boolean}
  101. */
  102. this.hasAnimation = builder.object.isSkinnedMesh === true;
  103. /**
  104. * A list of all possible material uniforms
  105. *
  106. * @type {Array<string>}
  107. */
  108. this.refreshUniforms = refreshUniforms;
  109. /**
  110. * Holds the current render ID from the node frame.
  111. *
  112. * @type {number}
  113. * @default 0
  114. */
  115. this.renderId = 0;
  116. }
  117. /**
  118. * Returns `true` if the given render object is verified for the first time of this observer.
  119. *
  120. * @param {RenderObject} renderObject - The render object.
  121. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  122. */
  123. firstInitialization( renderObject ) {
  124. const hasInitialized = this.renderObjects.has( renderObject );
  125. if ( hasInitialized === false ) {
  126. this.getRenderObjectData( renderObject );
  127. return true;
  128. }
  129. return false;
  130. }
  131. /**
  132. * Returns `true` if the current rendering produces motion vectors.
  133. *
  134. * @param {Renderer} renderer - The renderer.
  135. * @return {boolean} Whether the current rendering produces motion vectors or not.
  136. */
  137. needsVelocity( renderer ) {
  138. const mrt = renderer.getMRT();
  139. return ( mrt !== null && mrt.has( 'velocity' ) );
  140. }
  141. /**
  142. * Returns monitoring data for the given render object.
  143. *
  144. * @param {RenderObject} renderObject - The render object.
  145. * @return {Object} The monitoring data.
  146. */
  147. getRenderObjectData( renderObject ) {
  148. let data = this.renderObjects.get( renderObject );
  149. if ( data === undefined ) {
  150. const { geometry, material, object } = renderObject;
  151. data = {
  152. material: this.getMaterialData( material ),
  153. geometry: {
  154. id: geometry.id,
  155. attributes: this.getAttributesData( geometry.attributes ),
  156. indexVersion: geometry.index ? geometry.index.version : null,
  157. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  158. },
  159. worldMatrix: object.matrixWorld.clone()
  160. };
  161. if ( object.center ) {
  162. data.center = object.center.clone();
  163. }
  164. if ( object.morphTargetInfluences ) {
  165. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  166. }
  167. if ( renderObject.bundle !== null ) {
  168. data.version = renderObject.bundle.version;
  169. }
  170. if ( data.material.transmission > 0 ) {
  171. const { width, height } = renderObject.context;
  172. data.bufferWidth = width;
  173. data.bufferHeight = height;
  174. }
  175. data.lights = this.getLightsData( renderObject.lightsNode.getLights() );
  176. this.renderObjects.set( renderObject, data );
  177. }
  178. return data;
  179. }
  180. /**
  181. * Returns an attribute data structure holding the attributes versions for
  182. * monitoring.
  183. *
  184. * @param {Object} attributes - The geometry attributes.
  185. * @return {Object} An object for monitoring the versions of attributes.
  186. */
  187. getAttributesData( attributes ) {
  188. const attributesData = {};
  189. for ( const name in attributes ) {
  190. const attribute = attributes[ name ];
  191. attributesData[ name ] = {
  192. version: attribute.version
  193. };
  194. }
  195. return attributesData;
  196. }
  197. /**
  198. * Returns `true` if the node builder's material uses
  199. * node properties.
  200. *
  201. * @param {NodeBuilder} builder - The current node builder.
  202. * @return {boolean} Whether the node builder's material uses node properties or not.
  203. */
  204. containsNode( builder ) {
  205. const material = builder.material;
  206. for ( const property in material ) {
  207. if ( material[ property ] && material[ property ].isNode )
  208. return true;
  209. }
  210. if ( builder.renderer.overrideNodes.modelViewMatrix !== null || builder.renderer.overrideNodes.modelNormalViewMatrix !== null )
  211. return true;
  212. return false;
  213. }
  214. /**
  215. * Returns a material data structure holding the material property values for
  216. * monitoring.
  217. *
  218. * @param {Material} material - The material.
  219. * @return {Object} An object for monitoring material properties.
  220. */
  221. getMaterialData( material ) {
  222. const data = {};
  223. for ( const property of this.refreshUniforms ) {
  224. const value = material[ property ];
  225. if ( value === null || value === undefined ) continue;
  226. if ( typeof value === 'object' && value.clone !== undefined ) {
  227. if ( value.isTexture === true ) {
  228. data[ property ] = { id: value.id, version: value.version };
  229. } else {
  230. data[ property ] = value.clone();
  231. }
  232. } else {
  233. data[ property ] = value;
  234. }
  235. }
  236. return data;
  237. }
  238. /**
  239. * Returns `true` if the given render object has not changed its state.
  240. *
  241. * @param {RenderObject} renderObject - The render object.
  242. * @param {Array<Light>} lightsData - The current material lights.
  243. * @return {boolean} Whether the given render object has changed its state or not.
  244. */
  245. equals( renderObject, lightsData ) {
  246. const { object, material, geometry } = renderObject;
  247. const renderObjectData = this.getRenderObjectData( renderObject );
  248. // world matrix
  249. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  250. renderObjectData.worldMatrix.copy( object.matrixWorld );
  251. return false;
  252. }
  253. // material
  254. const materialData = renderObjectData.material;
  255. for ( const property in materialData ) {
  256. const value = materialData[ property ];
  257. const mtlValue = material[ property ];
  258. if ( value.equals !== undefined ) {
  259. if ( value.equals( mtlValue ) === false ) {
  260. value.copy( mtlValue );
  261. return false;
  262. }
  263. } else if ( mtlValue.isTexture === true ) {
  264. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  265. value.id = mtlValue.id;
  266. value.version = mtlValue.version;
  267. return false;
  268. }
  269. } else if ( value !== mtlValue ) {
  270. materialData[ property ] = mtlValue;
  271. return false;
  272. }
  273. }
  274. if ( materialData.transmission > 0 ) {
  275. const { width, height } = renderObject.context;
  276. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  277. renderObjectData.bufferWidth = width;
  278. renderObjectData.bufferHeight = height;
  279. return false;
  280. }
  281. }
  282. // geometry
  283. const storedGeometryData = renderObjectData.geometry;
  284. const attributes = geometry.attributes;
  285. const storedAttributes = storedGeometryData.attributes;
  286. const storedAttributeNames = Object.keys( storedAttributes );
  287. const currentAttributeNames = Object.keys( attributes );
  288. if ( storedGeometryData.id !== geometry.id ) {
  289. storedGeometryData.id = geometry.id;
  290. return false;
  291. }
  292. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  293. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  294. return false;
  295. }
  296. // compare each attribute
  297. for ( const name of storedAttributeNames ) {
  298. const storedAttributeData = storedAttributes[ name ];
  299. const attribute = attributes[ name ];
  300. if ( attribute === undefined ) {
  301. // attribute was removed
  302. delete storedAttributes[ name ];
  303. return false;
  304. }
  305. if ( storedAttributeData.version !== attribute.version ) {
  306. storedAttributeData.version = attribute.version;
  307. return false;
  308. }
  309. }
  310. // check index
  311. const index = geometry.index;
  312. const storedIndexVersion = storedGeometryData.indexVersion;
  313. const currentIndexVersion = index ? index.version : null;
  314. if ( storedIndexVersion !== currentIndexVersion ) {
  315. storedGeometryData.indexVersion = currentIndexVersion;
  316. return false;
  317. }
  318. // check drawRange
  319. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  320. storedGeometryData.drawRange.start = geometry.drawRange.start;
  321. storedGeometryData.drawRange.count = geometry.drawRange.count;
  322. return false;
  323. }
  324. // morph targets
  325. if ( renderObjectData.morphTargetInfluences ) {
  326. let morphChanged = false;
  327. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  328. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  329. renderObjectData.morphTargetInfluences[ i ] = object.morphTargetInfluences[ i ];
  330. morphChanged = true;
  331. }
  332. }
  333. if ( morphChanged ) return false;
  334. }
  335. // lights
  336. if ( renderObjectData.lights ) {
  337. for ( let i = 0; i < lightsData.length; i ++ ) {
  338. if ( renderObjectData.lights[ i ].map !== lightsData[ i ].map ) {
  339. return false;
  340. }
  341. }
  342. }
  343. // center
  344. if ( renderObjectData.center ) {
  345. if ( renderObjectData.center.equals( object.center ) === false ) {
  346. renderObjectData.center.copy( object.center );
  347. return true;
  348. }
  349. }
  350. // bundle
  351. if ( renderObject.bundle !== null ) {
  352. renderObjectData.version = renderObject.bundle.version;
  353. }
  354. return true;
  355. }
  356. /**
  357. * Returns the lights data for the given material lights.
  358. *
  359. * @param {Array<Light>} materialLights - The material lights.
  360. * @return {Array<Object>} The lights data for the given material lights.
  361. */
  362. getLightsData( materialLights ) {
  363. const lights = [];
  364. for ( const light of materialLights ) {
  365. if ( light.isSpotLight === true && light.map !== null ) {
  366. // only add lights that have a map
  367. lights.push( { map: light.map.version } );
  368. }
  369. }
  370. return lights;
  371. }
  372. /**
  373. * Returns the lights for the given lights node and render ID.
  374. *
  375. * @param {LightsNode} lightsNode - The lights node.
  376. * @param {number} renderId - The render ID.
  377. * @return {Array<Object>} The lights for the given lights node and render ID.
  378. */
  379. getLights( lightsNode, renderId ) {
  380. if ( _lightsCache.has( lightsNode ) ) {
  381. const cached = _lightsCache.get( lightsNode );
  382. if ( cached.renderId === renderId ) {
  383. return cached.lightsData;
  384. }
  385. }
  386. const lightsData = this.getLightsData( lightsNode.getLights() );
  387. _lightsCache.set( lightsNode, { renderId, lightsData } );
  388. return lightsData;
  389. }
  390. /**
  391. * Checks if the given render object requires a refresh.
  392. *
  393. * @param {RenderObject} renderObject - The render object.
  394. * @param {NodeFrame} nodeFrame - The current node frame.
  395. * @return {boolean} Whether the given render object requires a refresh or not.
  396. */
  397. needsRefresh( renderObject, nodeFrame ) {
  398. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  399. return true;
  400. const { renderId } = nodeFrame;
  401. if ( this.renderId !== renderId ) {
  402. this.renderId = renderId;
  403. return true;
  404. }
  405. const isStatic = renderObject.object.static === true;
  406. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  407. if ( isStatic || isBundle )
  408. return false;
  409. const lightsData = this.getLights( renderObject.lightsNode, renderId );
  410. const notEqual = this.equals( renderObject, lightsData ) !== true;
  411. return notEqual;
  412. }
  413. }
  414. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  415. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  416. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  417. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  418. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  419. function cyrb53( value, seed = 0 ) {
  420. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  421. if ( value instanceof Array ) {
  422. for ( let i = 0, val; i < value.length; i ++ ) {
  423. val = value[ i ];
  424. h1 = Math.imul( h1 ^ val, 2654435761 );
  425. h2 = Math.imul( h2 ^ val, 1597334677 );
  426. }
  427. } else {
  428. for ( let i = 0, ch; i < value.length; i ++ ) {
  429. ch = value.charCodeAt( i );
  430. h1 = Math.imul( h1 ^ ch, 2654435761 );
  431. h2 = Math.imul( h2 ^ ch, 1597334677 );
  432. }
  433. }
  434. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  435. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  436. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  437. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  438. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  439. }
  440. /**
  441. * Computes a hash for the given string.
  442. *
  443. * @private
  444. * @method
  445. * @param {string} str - The string to be hashed.
  446. * @return {number} The hash.
  447. */
  448. const hashString = ( str ) => cyrb53( str );
  449. /**
  450. * Computes a hash for the given array.
  451. *
  452. * @private
  453. * @method
  454. * @param {Array<number>} array - The array to be hashed.
  455. * @return {number} The hash.
  456. */
  457. const hashArray = ( array ) => cyrb53( array );
  458. /**
  459. * Computes a hash for the given list of parameters.
  460. *
  461. * @private
  462. * @method
  463. * @param {...number} params - A list of parameters.
  464. * @return {number} The hash.
  465. */
  466. const hash$1 = ( ...params ) => cyrb53( params );
  467. /**
  468. * Computes a cache key for the given node.
  469. *
  470. * @private
  471. * @method
  472. * @param {Object|Node} object - The object to be hashed.
  473. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  474. * @return {number} The hash.
  475. */
  476. function getCacheKey$1( object, force = false ) {
  477. const values = [];
  478. if ( object.isNode === true ) {
  479. values.push( object.id );
  480. }
  481. for ( const { property, childNode } of getNodeChildren( object ) ) {
  482. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  483. }
  484. return cyrb53( values );
  485. }
  486. /**
  487. * This generator function can be used to iterate over the node children
  488. * of the given object.
  489. *
  490. * @private
  491. * @generator
  492. * @param {Object} node - The object to be hashed.
  493. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  494. * @yields {Object} A result node holding the property, index (if available) and the child node.
  495. */
  496. function* getNodeChildren( node, toJSON = false ) {
  497. for ( const property of Object.getOwnPropertyNames( node ) ) {
  498. // Ignore private properties.
  499. if ( property.startsWith( '_' ) === true ) continue;
  500. const object = node[ property ];
  501. if ( Array.isArray( object ) === true ) {
  502. for ( let i = 0; i < object.length; i ++ ) {
  503. const child = object[ i ];
  504. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  505. yield { property, index: i, childNode: child };
  506. }
  507. }
  508. } else if ( object && object.isNode === true ) {
  509. yield { property, childNode: object };
  510. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  511. for ( const subProperty in object ) {
  512. // Ignore private properties.
  513. if ( subProperty.startsWith( '_' ) === true ) continue;
  514. const child = object[ subProperty ];
  515. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  516. yield { property, index: subProperty, childNode: child };
  517. }
  518. }
  519. }
  520. }
  521. }
  522. const typeFromLength = /*@__PURE__*/ new Map( [
  523. [ 1, 'float' ],
  524. [ 2, 'vec2' ],
  525. [ 3, 'vec3' ],
  526. [ 4, 'vec4' ],
  527. [ 9, 'mat3' ],
  528. [ 16, 'mat4' ]
  529. ] );
  530. const dataFromObject = /*@__PURE__*/ new WeakMap();
  531. /**
  532. * Returns the data type for the given the length.
  533. *
  534. * @private
  535. * @method
  536. * @param {number} length - The length.
  537. * @return {string} The data type.
  538. */
  539. function getTypeFromLength( length ) {
  540. return typeFromLength.get( length );
  541. }
  542. /**
  543. * Returns the typed array for the given data type.
  544. *
  545. * @private
  546. * @method
  547. * @param {string} type - The data type.
  548. * @return {TypedArray} The typed array.
  549. */
  550. function getTypedArrayFromType( type ) {
  551. // Handle component type for vectors and matrices
  552. if ( /[iu]?vec\d/.test( type ) ) {
  553. // Handle int vectors
  554. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  555. // Handle uint vectors
  556. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  557. // Default to float vectors
  558. return Float32Array;
  559. }
  560. // Handle matrices (always float)
  561. if ( /mat\d/.test( type ) ) return Float32Array;
  562. // Basic types
  563. if ( /float/.test( type ) ) return Float32Array;
  564. if ( /uint/.test( type ) ) return Uint32Array;
  565. if ( /int/.test( type ) ) return Int32Array;
  566. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  567. }
  568. /**
  569. * Returns the length for the given data type.
  570. *
  571. * @private
  572. * @method
  573. * @param {string} type - The data type.
  574. * @return {number} The length.
  575. */
  576. function getLengthFromType( type ) {
  577. if ( /float|int|uint/.test( type ) ) return 1;
  578. if ( /vec2/.test( type ) ) return 2;
  579. if ( /vec3/.test( type ) ) return 3;
  580. if ( /vec4/.test( type ) ) return 4;
  581. if ( /mat2/.test( type ) ) return 4;
  582. if ( /mat3/.test( type ) ) return 9;
  583. if ( /mat4/.test( type ) ) return 16;
  584. error( 'TSL: Unsupported type:', type );
  585. }
  586. /**
  587. * Returns the gpu memory length for the given data type.
  588. *
  589. * @private
  590. * @method
  591. * @param {string} type - The data type.
  592. * @return {number} The length.
  593. */
  594. function getMemoryLengthFromType( type ) {
  595. if ( /float|int|uint/.test( type ) ) return 1;
  596. if ( /vec2/.test( type ) ) return 2;
  597. if ( /vec3/.test( type ) ) return 3;
  598. if ( /vec4/.test( type ) ) return 4;
  599. if ( /mat2/.test( type ) ) return 4;
  600. if ( /mat3/.test( type ) ) return 12;
  601. if ( /mat4/.test( type ) ) return 16;
  602. error( 'TSL: Unsupported type:', type );
  603. }
  604. /**
  605. * Returns the byte boundary for the given data type.
  606. *
  607. * @private
  608. * @method
  609. * @param {string} type - The data type.
  610. * @return {number} The byte boundary.
  611. */
  612. function getByteBoundaryFromType( type ) {
  613. if ( /float|int|uint/.test( type ) ) return 4;
  614. if ( /vec2/.test( type ) ) return 8;
  615. if ( /vec3/.test( type ) ) return 16;
  616. if ( /vec4/.test( type ) ) return 16;
  617. if ( /mat2/.test( type ) ) return 8;
  618. if ( /mat3/.test( type ) ) return 48;
  619. if ( /mat4/.test( type ) ) return 64;
  620. error( 'TSL: Unsupported type:', type );
  621. }
  622. /**
  623. * Returns the data type for the given value.
  624. *
  625. * @private
  626. * @method
  627. * @param {any} value - The value.
  628. * @return {?string} The data type.
  629. */
  630. function getValueType( value ) {
  631. if ( value === undefined || value === null ) return null;
  632. const typeOf = typeof value;
  633. if ( value.isNode === true ) {
  634. return 'node';
  635. } else if ( typeOf === 'number' ) {
  636. return 'float';
  637. } else if ( typeOf === 'boolean' ) {
  638. return 'bool';
  639. } else if ( typeOf === 'string' ) {
  640. return 'string';
  641. } else if ( typeOf === 'function' ) {
  642. return 'shader';
  643. } else if ( value.isVector2 === true ) {
  644. return 'vec2';
  645. } else if ( value.isVector3 === true ) {
  646. return 'vec3';
  647. } else if ( value.isVector4 === true ) {
  648. return 'vec4';
  649. } else if ( value.isMatrix2 === true ) {
  650. return 'mat2';
  651. } else if ( value.isMatrix3 === true ) {
  652. return 'mat3';
  653. } else if ( value.isMatrix4 === true ) {
  654. return 'mat4';
  655. } else if ( value.isColor === true ) {
  656. return 'color';
  657. } else if ( value instanceof ArrayBuffer ) {
  658. return 'ArrayBuffer';
  659. }
  660. return null;
  661. }
  662. /**
  663. * Returns the value/object for the given data type and parameters.
  664. *
  665. * @private
  666. * @method
  667. * @param {string} type - The given type.
  668. * @param {...any} params - A parameter list.
  669. * @return {any} The value/object.
  670. */
  671. function getValueFromType( type, ...params ) {
  672. const last4 = type ? type.slice( -4 ) : undefined;
  673. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  674. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  675. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  676. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  677. }
  678. if ( type === 'color' ) {
  679. return new Color( ...params );
  680. } else if ( last4 === 'vec2' ) {
  681. return new Vector2( ...params );
  682. } else if ( last4 === 'vec3' ) {
  683. return new Vector3( ...params );
  684. } else if ( last4 === 'vec4' ) {
  685. return new Vector4( ...params );
  686. } else if ( last4 === 'mat2' ) {
  687. return new Matrix2( ...params );
  688. } else if ( last4 === 'mat3' ) {
  689. return new Matrix3( ...params );
  690. } else if ( last4 === 'mat4' ) {
  691. return new Matrix4( ...params );
  692. } else if ( type === 'bool' ) {
  693. return params[ 0 ] || false;
  694. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  695. return params[ 0 ] || 0;
  696. } else if ( type === 'string' ) {
  697. return params[ 0 ] || '';
  698. } else if ( type === 'ArrayBuffer' ) {
  699. return base64ToArrayBuffer( params[ 0 ] );
  700. }
  701. return null;
  702. }
  703. /**
  704. * Gets the object data that can be shared between different rendering steps.
  705. *
  706. * @private
  707. * @param {Object} object - The object to get the data for.
  708. * @return {Object} The object data.
  709. */
  710. function getDataFromObject( object ) {
  711. let data = dataFromObject.get( object );
  712. if ( data === undefined ) {
  713. data = {};
  714. dataFromObject.set( object, data );
  715. }
  716. return data;
  717. }
  718. /**
  719. * Converts the given array buffer to a Base64 string.
  720. *
  721. * @private
  722. * @method
  723. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  724. * @return {string} The Base64 string.
  725. */
  726. function arrayBufferToBase64( arrayBuffer ) {
  727. let chars = '';
  728. const array = new Uint8Array( arrayBuffer );
  729. for ( let i = 0; i < array.length; i ++ ) {
  730. chars += String.fromCharCode( array[ i ] );
  731. }
  732. return btoa( chars );
  733. }
  734. /**
  735. * Converts the given Base64 string to an array buffer.
  736. *
  737. * @private
  738. * @method
  739. * @param {string} base64 - The Base64 string.
  740. * @return {ArrayBuffer} The array buffer.
  741. */
  742. function base64ToArrayBuffer( base64 ) {
  743. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  744. }
  745. var NodeUtils = /*#__PURE__*/Object.freeze({
  746. __proto__: null,
  747. arrayBufferToBase64: arrayBufferToBase64,
  748. base64ToArrayBuffer: base64ToArrayBuffer,
  749. getByteBoundaryFromType: getByteBoundaryFromType,
  750. getCacheKey: getCacheKey$1,
  751. getDataFromObject: getDataFromObject,
  752. getLengthFromType: getLengthFromType,
  753. getMemoryLengthFromType: getMemoryLengthFromType,
  754. getNodeChildren: getNodeChildren,
  755. getTypeFromLength: getTypeFromLength,
  756. getTypedArrayFromType: getTypedArrayFromType,
  757. getValueFromType: getValueFromType,
  758. getValueType: getValueType,
  759. hash: hash$1,
  760. hashArray: hashArray,
  761. hashString: hashString
  762. });
  763. /**
  764. * Possible shader stages.
  765. *
  766. * @property {string} VERTEX The vertex shader stage.
  767. * @property {string} FRAGMENT The fragment shader stage.
  768. */
  769. const NodeShaderStage = {
  770. VERTEX: 'vertex',
  771. FRAGMENT: 'fragment'
  772. };
  773. /**
  774. * Update types of a node.
  775. *
  776. * @property {string} NONE The update method is not executed.
  777. * @property {string} FRAME The update method is executed per frame.
  778. * @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.
  779. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  780. */
  781. const NodeUpdateType = {
  782. NONE: 'none',
  783. FRAME: 'frame',
  784. RENDER: 'render',
  785. OBJECT: 'object'
  786. };
  787. /**
  788. * Data types of a node.
  789. *
  790. * @property {string} BOOLEAN Boolean type.
  791. * @property {string} INTEGER Integer type.
  792. * @property {string} FLOAT Float type.
  793. * @property {string} VECTOR2 Two-dimensional vector type.
  794. * @property {string} VECTOR3 Three-dimensional vector type.
  795. * @property {string} VECTOR4 Four-dimensional vector type.
  796. * @property {string} MATRIX2 2x2 matrix type.
  797. * @property {string} MATRIX3 3x3 matrix type.
  798. * @property {string} MATRIX4 4x4 matrix type.
  799. */
  800. const NodeType = {
  801. BOOLEAN: 'bool',
  802. INTEGER: 'int',
  803. FLOAT: 'float',
  804. VECTOR2: 'vec2',
  805. VECTOR3: 'vec3',
  806. VECTOR4: 'vec4',
  807. MATRIX2: 'mat2',
  808. MATRIX3: 'mat3',
  809. MATRIX4: 'mat4'
  810. };
  811. /**
  812. * Access types of a node. These are relevant for compute and storage usage.
  813. *
  814. * @property {string} READ_ONLY Read-only access
  815. * @property {string} WRITE_ONLY Write-only access.
  816. * @property {string} READ_WRITE Read and write access.
  817. */
  818. const NodeAccess = {
  819. READ_ONLY: 'readOnly',
  820. WRITE_ONLY: 'writeOnly',
  821. READ_WRITE: 'readWrite',
  822. };
  823. const defaultShaderStages = [ 'fragment', 'vertex' ];
  824. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  825. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  826. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  827. const _parentBuildStage = {
  828. analyze: 'setup',
  829. generate: 'analyze'
  830. };
  831. let _nodeId = 0;
  832. /**
  833. * Base class for all nodes.
  834. *
  835. * @augments EventDispatcher
  836. */
  837. class Node extends EventDispatcher {
  838. static get type() {
  839. return 'Node';
  840. }
  841. /**
  842. * Constructs a new node.
  843. *
  844. * @param {?string} nodeType - The node type.
  845. */
  846. constructor( nodeType = null ) {
  847. super();
  848. /**
  849. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  850. *
  851. * @type {?string}
  852. * @default null
  853. */
  854. this.nodeType = nodeType;
  855. /**
  856. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  857. *
  858. * @type {string}
  859. * @default 'none'
  860. */
  861. this.updateType = NodeUpdateType.NONE;
  862. /**
  863. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  864. *
  865. * @type {string}
  866. * @default 'none'
  867. */
  868. this.updateBeforeType = NodeUpdateType.NONE;
  869. /**
  870. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  871. *
  872. * @type {string}
  873. * @default 'none'
  874. */
  875. this.updateAfterType = NodeUpdateType.NONE;
  876. /**
  877. * The UUID of the node.
  878. *
  879. * @type {string}
  880. * @readonly
  881. */
  882. this.uuid = MathUtils.generateUUID();
  883. /**
  884. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  885. *
  886. * @type {number}
  887. * @readonly
  888. * @default 0
  889. */
  890. this.version = 0;
  891. /**
  892. * The name of the node.
  893. *
  894. * @type {string}
  895. * @default ''
  896. */
  897. this.name = '';
  898. /**
  899. * Whether this node is global or not. This property is relevant for the internal
  900. * node caching system. All nodes which should be declared just once should
  901. * set this flag to `true` (a typical example is {@link AttributeNode}).
  902. *
  903. * @type {boolean}
  904. * @default false
  905. */
  906. this.global = false;
  907. /**
  908. * Create a list of parents for this node during the build process.
  909. *
  910. * @type {boolean}
  911. * @default false
  912. */
  913. this.parents = false;
  914. /**
  915. * This flag can be used for type testing.
  916. *
  917. * @type {boolean}
  918. * @readonly
  919. * @default true
  920. */
  921. this.isNode = true;
  922. // private
  923. this._beforeNodes = null;
  924. /**
  925. * The cache key of this node.
  926. *
  927. * @private
  928. * @type {?number}
  929. * @default null
  930. */
  931. this._cacheKey = null;
  932. /**
  933. * The cache key 's version.
  934. *
  935. * @private
  936. * @type {number}
  937. * @default 0
  938. */
  939. this._cacheKeyVersion = 0;
  940. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  941. }
  942. /**
  943. * Set this property to `true` when the node should be regenerated.
  944. *
  945. * @type {boolean}
  946. * @default false
  947. * @param {boolean} value
  948. */
  949. set needsUpdate( value ) {
  950. if ( value === true ) {
  951. this.version ++;
  952. }
  953. }
  954. /**
  955. * The type of the class. The value is usually the constructor name.
  956. *
  957. * @type {string}
  958. * @readonly
  959. */
  960. get type() {
  961. return this.constructor.type;
  962. }
  963. /**
  964. * Convenient method for defining {@link Node#update}.
  965. *
  966. * @param {Function} callback - The update method.
  967. * @param {string} updateType - The update type.
  968. * @return {Node} A reference to this node.
  969. */
  970. onUpdate( callback, updateType ) {
  971. this.updateType = updateType;
  972. this.update = callback.bind( this );
  973. return this;
  974. }
  975. /**
  976. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  977. * this method automatically sets the update type to `FRAME`.
  978. *
  979. * @param {Function} callback - The update method.
  980. * @return {Node} A reference to this node.
  981. */
  982. onFrameUpdate( callback ) {
  983. return this.onUpdate( callback, NodeUpdateType.FRAME );
  984. }
  985. /**
  986. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  987. * this method automatically sets the update type to `RENDER`.
  988. *
  989. * @param {Function} callback - The update method.
  990. * @return {Node} A reference to this node.
  991. */
  992. onRenderUpdate( callback ) {
  993. return this.onUpdate( callback, NodeUpdateType.RENDER );
  994. }
  995. /**
  996. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  997. * this method automatically sets the update type to `OBJECT`.
  998. *
  999. * @param {Function} callback - The update method.
  1000. * @return {Node} A reference to this node.
  1001. */
  1002. onObjectUpdate( callback ) {
  1003. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  1004. }
  1005. /**
  1006. * Convenient method for defining {@link Node#updateReference}.
  1007. *
  1008. * @param {Function} callback - The update method.
  1009. * @return {Node} A reference to this node.
  1010. */
  1011. onReference( callback ) {
  1012. this.updateReference = callback.bind( this );
  1013. return this;
  1014. }
  1015. /**
  1016. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  1017. * to such objects based on a given state (e.g. the current node frame or builder).
  1018. *
  1019. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  1020. * @return {any} The updated reference.
  1021. */
  1022. updateReference( /*state*/ ) {
  1023. return this;
  1024. }
  1025. /**
  1026. * By default this method returns the value of the {@link Node#global} flag. This method
  1027. * can be overwritten in derived classes if an analytical way is required to determine the
  1028. * global cache referring to the current shader-stage.
  1029. *
  1030. * @param {NodeBuilder} builder - The current node builder.
  1031. * @return {boolean} Whether this node is global or not.
  1032. */
  1033. isGlobal( /*builder*/ ) {
  1034. return this.global;
  1035. }
  1036. /**
  1037. * Generator function that can be used to iterate over the child nodes.
  1038. *
  1039. * @generator
  1040. * @yields {Node} A child node.
  1041. */
  1042. * getChildren() {
  1043. for ( const { childNode } of getNodeChildren( this ) ) {
  1044. yield childNode;
  1045. }
  1046. }
  1047. /**
  1048. * Calling this method dispatches the `dispose` event. This event can be used
  1049. * to register event listeners for clean up tasks.
  1050. */
  1051. dispose() {
  1052. this.dispatchEvent( { type: 'dispose' } );
  1053. }
  1054. /**
  1055. * Callback for {@link Node#traverse}.
  1056. *
  1057. * @callback traverseCallback
  1058. * @param {Node} node - The current node.
  1059. */
  1060. /**
  1061. * Can be used to traverse through the node's hierarchy.
  1062. *
  1063. * @param {traverseCallback} callback - A callback that is executed per node.
  1064. */
  1065. traverse( callback ) {
  1066. callback( this );
  1067. for ( const childNode of this.getChildren() ) {
  1068. childNode.traverse( callback );
  1069. }
  1070. }
  1071. /**
  1072. * Returns the cache key for this node.
  1073. *
  1074. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1075. * @return {number} The cache key of the node.
  1076. */
  1077. getCacheKey( force = false ) {
  1078. force = force || this.version !== this._cacheKeyVersion;
  1079. if ( force === true || this._cacheKey === null ) {
  1080. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  1081. this._cacheKeyVersion = this.version;
  1082. }
  1083. return this._cacheKey;
  1084. }
  1085. /**
  1086. * Generate a custom cache key for this node.
  1087. *
  1088. * @return {number} The cache key of the node.
  1089. */
  1090. customCacheKey() {
  1091. return 0;
  1092. }
  1093. /**
  1094. * Returns the references to this node which is by default `this`.
  1095. *
  1096. * @return {Node} A reference to this node.
  1097. */
  1098. getScope() {
  1099. return this;
  1100. }
  1101. /**
  1102. * Returns the hash of the node which is used to identify the node. By default it's
  1103. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1104. * depending on their implementation.
  1105. *
  1106. * @param {NodeBuilder} builder - The current node builder.
  1107. * @return {string} The hash.
  1108. */
  1109. getHash( /*builder*/ ) {
  1110. return this.uuid;
  1111. }
  1112. /**
  1113. * Returns the update type of {@link Node#update}.
  1114. *
  1115. * @return {NodeUpdateType} The update type.
  1116. */
  1117. getUpdateType() {
  1118. return this.updateType;
  1119. }
  1120. /**
  1121. * Returns the update type of {@link Node#updateBefore}.
  1122. *
  1123. * @return {NodeUpdateType} The update type.
  1124. */
  1125. getUpdateBeforeType() {
  1126. return this.updateBeforeType;
  1127. }
  1128. /**
  1129. * Returns the update type of {@link Node#updateAfter}.
  1130. *
  1131. * @return {NodeUpdateType} The update type.
  1132. */
  1133. getUpdateAfterType() {
  1134. return this.updateAfterType;
  1135. }
  1136. /**
  1137. * Certain types are composed of multiple elements. For example a `vec3`
  1138. * is composed of three `float` values. This method returns the type of
  1139. * these elements.
  1140. *
  1141. * @param {NodeBuilder} builder - The current node builder.
  1142. * @return {string} The type of the node.
  1143. */
  1144. getElementType( builder ) {
  1145. const type = this.getNodeType( builder );
  1146. const elementType = builder.getElementType( type );
  1147. return elementType;
  1148. }
  1149. /**
  1150. * Returns the node member type for the given name.
  1151. *
  1152. * @param {NodeBuilder} builder - The current node builder.
  1153. * @param {string} name - The name of the member.
  1154. * @return {string} The type of the node.
  1155. */
  1156. getMemberType( /*builder, name*/ ) {
  1157. return 'void';
  1158. }
  1159. /**
  1160. * Returns the node's type.
  1161. *
  1162. * @param {NodeBuilder} builder - The current node builder.
  1163. * @return {string} The type of the node.
  1164. */
  1165. getNodeType( builder ) {
  1166. const nodeProperties = builder.getNodeProperties( this );
  1167. if ( nodeProperties.outputNode ) {
  1168. return nodeProperties.outputNode.getNodeType( builder );
  1169. }
  1170. return this.nodeType;
  1171. }
  1172. /**
  1173. * This method is used during the build process of a node and ensures
  1174. * equal nodes are not built multiple times but just once. For example if
  1175. * `attribute( 'uv' )` is used multiple times by the user, the build
  1176. * process makes sure to process just the first node.
  1177. *
  1178. * @param {NodeBuilder} builder - The current node builder.
  1179. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1180. */
  1181. getShared( builder ) {
  1182. const hash = this.getHash( builder );
  1183. const nodeFromHash = builder.getNodeFromHash( hash );
  1184. return nodeFromHash || this;
  1185. }
  1186. /**
  1187. * Returns the number of elements in the node array.
  1188. *
  1189. * @param {NodeBuilder} builder - The current node builder.
  1190. * @return {?number} The number of elements in the node array.
  1191. */
  1192. getArrayCount( /*builder*/ ) {
  1193. return null;
  1194. }
  1195. /**
  1196. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1197. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1198. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1199. *
  1200. * @param {NodeBuilder} builder - The current node builder.
  1201. * @return {?Node} The output node.
  1202. */
  1203. setup( builder ) {
  1204. const nodeProperties = builder.getNodeProperties( this );
  1205. let index = 0;
  1206. for ( const childNode of this.getChildren() ) {
  1207. nodeProperties[ 'node' + index ++ ] = childNode;
  1208. }
  1209. // return a outputNode if exists or null
  1210. return nodeProperties.outputNode || null;
  1211. }
  1212. /**
  1213. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1214. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1215. *
  1216. * @param {NodeBuilder} builder - The current node builder.
  1217. * @param {?Node} output - The target output node.
  1218. */
  1219. analyze( builder, output = null ) {
  1220. const usageCount = builder.increaseUsage( this );
  1221. if ( this.parents === true ) {
  1222. const nodeData = builder.getDataFromNode( this, 'any' );
  1223. nodeData.stages = nodeData.stages || {};
  1224. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1225. nodeData.stages[ builder.shaderStage ].push( output );
  1226. }
  1227. if ( usageCount === 1 ) {
  1228. // node flow children
  1229. const nodeProperties = builder.getNodeProperties( this );
  1230. for ( const childNode of Object.values( nodeProperties ) ) {
  1231. if ( childNode && childNode.isNode === true ) {
  1232. childNode.build( builder, this );
  1233. }
  1234. }
  1235. }
  1236. }
  1237. /**
  1238. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1239. * This state builds the output node and returns the resulting shader string.
  1240. *
  1241. * @param {NodeBuilder} builder - The current node builder.
  1242. * @param {?string} [output] - Can be used to define the output type.
  1243. * @return {?string} The generated shader string.
  1244. */
  1245. generate( builder, output ) {
  1246. const { outputNode } = builder.getNodeProperties( this );
  1247. if ( outputNode && outputNode.isNode === true ) {
  1248. return outputNode.build( builder, output );
  1249. }
  1250. }
  1251. /**
  1252. * The method can be implemented to update the node's internal state before it is used to render an object.
  1253. * The {@link Node#updateBeforeType} 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. updateBefore( /*frame*/ ) {
  1260. warn( 'Abstract function.' );
  1261. }
  1262. /**
  1263. * The method can be implemented to update the node's internal state after it was used to render an object.
  1264. * The {@link Node#updateAfterType} 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. updateAfter( /*frame*/ ) {
  1271. warn( 'Abstract function.' );
  1272. }
  1273. /**
  1274. * The method can be implemented to update the node's internal state when it is used to render an object.
  1275. * The {@link Node#updateType} property defines how often the update is executed.
  1276. *
  1277. * @abstract
  1278. * @param {NodeFrame} frame - A reference to the current node frame.
  1279. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1280. */
  1281. update( /*frame*/ ) {
  1282. warn( 'Abstract function.' );
  1283. }
  1284. before( node ) {
  1285. if ( this._beforeNodes === null ) this._beforeNodes = [];
  1286. this._beforeNodes.push( node );
  1287. return this;
  1288. }
  1289. /**
  1290. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1291. * - **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.
  1292. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1293. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1294. *
  1295. * @param {NodeBuilder} builder - The current node builder.
  1296. * @param {?(string|Node)} [output=null] - Can be used to define the output type.
  1297. * @return {?(Node|string)} The result of the build process, depending on the build stage.
  1298. */
  1299. build( builder, output = null ) {
  1300. const refNode = this.getShared( builder );
  1301. if ( this !== refNode ) {
  1302. return refNode.build( builder, output );
  1303. }
  1304. //
  1305. if ( this._beforeNodes !== null ) {
  1306. const currentBeforeNodes = this._beforeNodes;
  1307. this._beforeNodes = null;
  1308. for ( const beforeNode of currentBeforeNodes ) {
  1309. beforeNode.build( builder, output );
  1310. }
  1311. this._beforeNodes = currentBeforeNodes;
  1312. }
  1313. //
  1314. const nodeData = builder.getDataFromNode( this );
  1315. nodeData.buildStages = nodeData.buildStages || {};
  1316. nodeData.buildStages[ builder.buildStage ] = true;
  1317. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1318. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1319. // force parent build stage (setup or analyze)
  1320. const previousBuildStage = builder.getBuildStage();
  1321. builder.setBuildStage( parentBuildStage );
  1322. this.build( builder );
  1323. builder.setBuildStage( previousBuildStage );
  1324. }
  1325. //
  1326. builder.addNode( this );
  1327. builder.addChain( this );
  1328. /* Build stages expected results:
  1329. - "setup" -> Node
  1330. - "analyze" -> null
  1331. - "generate" -> String
  1332. */
  1333. let result = null;
  1334. const buildStage = builder.getBuildStage();
  1335. if ( buildStage === 'setup' ) {
  1336. this.updateReference( builder );
  1337. const properties = builder.getNodeProperties( this );
  1338. if ( properties.initialized !== true ) {
  1339. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1340. properties.initialized = true;
  1341. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1342. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1343. // !! no outputNode !!
  1344. //outputNode = builder.stack;
  1345. }*/
  1346. for ( const childNode of Object.values( properties ) ) {
  1347. if ( childNode && childNode.isNode === true ) {
  1348. if ( childNode.parents === true ) {
  1349. const childProperties = builder.getNodeProperties( childNode );
  1350. childProperties.parents = childProperties.parents || [];
  1351. childProperties.parents.push( this );
  1352. }
  1353. childNode.build( builder );
  1354. }
  1355. }
  1356. }
  1357. result = properties.outputNode;
  1358. } else if ( buildStage === 'analyze' ) {
  1359. this.analyze( builder, output );
  1360. } else if ( buildStage === 'generate' ) {
  1361. // If generate has just one argument, it means the output type is not required.
  1362. // This means that the node does not handle output conversions internally,
  1363. // so the value is stored in a cache and the builder handles the conversion
  1364. // for all requested output types.
  1365. const isGenerateOnce = this.generate.length < 2;
  1366. if ( isGenerateOnce ) {
  1367. const type = this.getNodeType( builder );
  1368. const nodeData = builder.getDataFromNode( this );
  1369. result = nodeData.snippet;
  1370. if ( result === undefined ) {
  1371. if ( nodeData.generated === undefined ) {
  1372. nodeData.generated = true;
  1373. result = this.generate( builder ) || '';
  1374. nodeData.snippet = result;
  1375. } else {
  1376. warn( 'Node: Recursion detected.', this );
  1377. result = '/* Recursion detected. */';
  1378. }
  1379. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1380. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1381. }
  1382. result = builder.format( result, type, output );
  1383. } else {
  1384. result = this.generate( builder, output ) || '';
  1385. }
  1386. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1387. // if no snippet is generated, return a default value
  1388. error( `TSL: Invalid generated code, expected a "${ output }".` );
  1389. result = builder.generateConst( output );
  1390. }
  1391. }
  1392. builder.removeChain( this );
  1393. builder.addSequentialNode( this );
  1394. return result;
  1395. }
  1396. /**
  1397. * Returns the child nodes as a JSON object.
  1398. *
  1399. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1400. */
  1401. getSerializeChildren() {
  1402. return getNodeChildren( this );
  1403. }
  1404. /**
  1405. * Serializes the node to JSON.
  1406. *
  1407. * @param {Object} json - The output JSON object.
  1408. */
  1409. serialize( json ) {
  1410. const nodeChildren = this.getSerializeChildren();
  1411. const inputNodes = {};
  1412. for ( const { property, index, childNode } of nodeChildren ) {
  1413. if ( index !== undefined ) {
  1414. if ( inputNodes[ property ] === undefined ) {
  1415. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1416. }
  1417. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1418. } else {
  1419. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1420. }
  1421. }
  1422. if ( Object.keys( inputNodes ).length > 0 ) {
  1423. json.inputNodes = inputNodes;
  1424. }
  1425. }
  1426. /**
  1427. * Deserializes the node from the given JSON.
  1428. *
  1429. * @param {Object} json - The JSON object.
  1430. */
  1431. deserialize( json ) {
  1432. if ( json.inputNodes !== undefined ) {
  1433. const nodes = json.meta.nodes;
  1434. for ( const property in json.inputNodes ) {
  1435. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1436. const inputArray = [];
  1437. for ( const uuid of json.inputNodes[ property ] ) {
  1438. inputArray.push( nodes[ uuid ] );
  1439. }
  1440. this[ property ] = inputArray;
  1441. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1442. const inputObject = {};
  1443. for ( const subProperty in json.inputNodes[ property ] ) {
  1444. const uuid = json.inputNodes[ property ][ subProperty ];
  1445. inputObject[ subProperty ] = nodes[ uuid ];
  1446. }
  1447. this[ property ] = inputObject;
  1448. } else {
  1449. const uuid = json.inputNodes[ property ];
  1450. this[ property ] = nodes[ uuid ];
  1451. }
  1452. }
  1453. }
  1454. }
  1455. /**
  1456. * Serializes the node into the three.js JSON Object/Scene format.
  1457. *
  1458. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1459. * @return {Object} The serialized node.
  1460. */
  1461. toJSON( meta ) {
  1462. const { uuid, type } = this;
  1463. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1464. if ( isRoot ) {
  1465. meta = {
  1466. textures: {},
  1467. images: {},
  1468. nodes: {}
  1469. };
  1470. }
  1471. // serialize
  1472. let data = meta.nodes[ uuid ];
  1473. if ( data === undefined ) {
  1474. data = {
  1475. uuid,
  1476. type,
  1477. meta,
  1478. metadata: {
  1479. version: 4.7,
  1480. type: 'Node',
  1481. generator: 'Node.toJSON'
  1482. }
  1483. };
  1484. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1485. this.serialize( data );
  1486. delete data.meta;
  1487. }
  1488. // TODO: Copied from Object3D.toJSON
  1489. function extractFromCache( cache ) {
  1490. const values = [];
  1491. for ( const key in cache ) {
  1492. const data = cache[ key ];
  1493. delete data.metadata;
  1494. values.push( data );
  1495. }
  1496. return values;
  1497. }
  1498. if ( isRoot ) {
  1499. const textures = extractFromCache( meta.textures );
  1500. const images = extractFromCache( meta.images );
  1501. const nodes = extractFromCache( meta.nodes );
  1502. if ( textures.length > 0 ) data.textures = textures;
  1503. if ( images.length > 0 ) data.images = images;
  1504. if ( nodes.length > 0 ) data.nodes = nodes;
  1505. }
  1506. return data;
  1507. }
  1508. }
  1509. /**
  1510. * Base class for representing element access on an array-like
  1511. * node data structures.
  1512. *
  1513. * @augments Node
  1514. */
  1515. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1516. static get type() {
  1517. return 'ArrayElementNode';
  1518. }
  1519. /**
  1520. * Constructs an array element node.
  1521. *
  1522. * @param {Node} node - The array-like node.
  1523. * @param {Node} indexNode - The index node that defines the element access.
  1524. */
  1525. constructor( node, indexNode ) {
  1526. super();
  1527. /**
  1528. * The array-like node.
  1529. *
  1530. * @type {Node}
  1531. */
  1532. this.node = node;
  1533. /**
  1534. * The index node that defines the element access.
  1535. *
  1536. * @type {Node}
  1537. */
  1538. this.indexNode = indexNode;
  1539. /**
  1540. * This flag can be used for type testing.
  1541. *
  1542. * @type {boolean}
  1543. * @readonly
  1544. * @default true
  1545. */
  1546. this.isArrayElementNode = true;
  1547. }
  1548. /**
  1549. * This method is overwritten since the node type is inferred from the array-like node.
  1550. *
  1551. * @param {NodeBuilder} builder - The current node builder.
  1552. * @return {string} The node type.
  1553. */
  1554. getNodeType( builder ) {
  1555. return this.node.getElementType( builder );
  1556. }
  1557. generate( builder ) {
  1558. const indexType = this.indexNode.getNodeType( builder );
  1559. const nodeSnippet = this.node.build( builder );
  1560. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1561. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1562. }
  1563. }
  1564. /**
  1565. * This module is part of the TSL core and usually not used in app level code.
  1566. * It represents a convert operation during the shader generation process
  1567. * meaning it converts the data type of a node to a target data type.
  1568. *
  1569. * @augments Node
  1570. */
  1571. class ConvertNode extends Node {
  1572. static get type() {
  1573. return 'ConvertNode';
  1574. }
  1575. /**
  1576. * Constructs a new convert node.
  1577. *
  1578. * @param {Node} node - The node which type should be converted.
  1579. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1580. */
  1581. constructor( node, convertTo ) {
  1582. super();
  1583. /**
  1584. * The node which type should be converted.
  1585. *
  1586. * @type {Node}
  1587. */
  1588. this.node = node;
  1589. /**
  1590. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1591. *
  1592. * @type {string}
  1593. */
  1594. this.convertTo = convertTo;
  1595. }
  1596. /**
  1597. * This method is overwritten since the implementation tries to infer the best
  1598. * matching type from the {@link ConvertNode#convertTo} property.
  1599. *
  1600. * @param {NodeBuilder} builder - The current node builder.
  1601. * @return {string} The node type.
  1602. */
  1603. getNodeType( builder ) {
  1604. const requestType = this.node.getNodeType( builder );
  1605. let convertTo = null;
  1606. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1607. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1608. convertTo = overloadingType;
  1609. }
  1610. }
  1611. return convertTo;
  1612. }
  1613. serialize( data ) {
  1614. super.serialize( data );
  1615. data.convertTo = this.convertTo;
  1616. }
  1617. deserialize( data ) {
  1618. super.deserialize( data );
  1619. this.convertTo = data.convertTo;
  1620. }
  1621. generate( builder, output ) {
  1622. const node = this.node;
  1623. const type = this.getNodeType( builder );
  1624. const snippet = node.build( builder, type );
  1625. return builder.format( snippet, type, output );
  1626. }
  1627. }
  1628. /**
  1629. * This module uses cache management to create temporary variables
  1630. * if the node is used more than once to prevent duplicate calculations.
  1631. *
  1632. * The class acts as a base class for many other nodes types.
  1633. *
  1634. * @augments Node
  1635. */
  1636. class TempNode extends Node {
  1637. static get type() {
  1638. return 'TempNode';
  1639. }
  1640. /**
  1641. * Constructs a temp node.
  1642. *
  1643. * @param {?string} nodeType - The node type.
  1644. */
  1645. constructor( nodeType = null ) {
  1646. super( nodeType );
  1647. /**
  1648. * This flag can be used for type testing.
  1649. *
  1650. * @type {boolean}
  1651. * @readonly
  1652. * @default true
  1653. */
  1654. this.isTempNode = true;
  1655. }
  1656. /**
  1657. * Whether this node is used more than once in context of other nodes.
  1658. *
  1659. * @param {NodeBuilder} builder - The node builder.
  1660. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1661. */
  1662. hasDependencies( builder ) {
  1663. return builder.getDataFromNode( this ).usageCount > 1;
  1664. }
  1665. build( builder, output ) {
  1666. const buildStage = builder.getBuildStage();
  1667. if ( buildStage === 'generate' ) {
  1668. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1669. const nodeData = builder.getDataFromNode( this );
  1670. if ( nodeData.propertyName !== undefined ) {
  1671. return builder.format( nodeData.propertyName, type, output );
  1672. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1673. const snippet = super.build( builder, type );
  1674. const nodeVar = builder.getVarFromNode( this, null, type );
  1675. const propertyName = builder.getPropertyName( nodeVar );
  1676. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1677. nodeData.snippet = snippet;
  1678. nodeData.propertyName = propertyName;
  1679. return builder.format( nodeData.propertyName, type, output );
  1680. }
  1681. }
  1682. return super.build( builder, output );
  1683. }
  1684. }
  1685. /**
  1686. * This module is part of the TSL core and usually not used in app level code.
  1687. * It represents a join operation during the shader generation process.
  1688. * For example in can compose/join two single floats into a `vec2` type.
  1689. *
  1690. * @augments TempNode
  1691. */
  1692. class JoinNode extends TempNode {
  1693. static get type() {
  1694. return 'JoinNode';
  1695. }
  1696. /**
  1697. * Constructs a new join node.
  1698. *
  1699. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1700. * @param {?string} [nodeType=null] - The node type.
  1701. */
  1702. constructor( nodes = [], nodeType = null ) {
  1703. super( nodeType );
  1704. /**
  1705. * An array of nodes that should be joined.
  1706. *
  1707. * @type {Array<Node>}
  1708. */
  1709. this.nodes = nodes;
  1710. }
  1711. /**
  1712. * This method is overwritten since the node type must be inferred from the
  1713. * joined data length if not explicitly defined.
  1714. *
  1715. * @param {NodeBuilder} builder - The current node builder.
  1716. * @return {string} The node type.
  1717. */
  1718. getNodeType( builder ) {
  1719. if ( this.nodeType !== null ) {
  1720. return builder.getVectorType( this.nodeType );
  1721. }
  1722. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1723. }
  1724. generate( builder, output ) {
  1725. const type = this.getNodeType( builder );
  1726. const maxLength = builder.getTypeLength( type );
  1727. const nodes = this.nodes;
  1728. const primitiveType = builder.getComponentType( type );
  1729. const snippetValues = [];
  1730. let length = 0;
  1731. for ( const input of nodes ) {
  1732. if ( length >= maxLength ) {
  1733. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1734. break;
  1735. }
  1736. let inputType = input.getNodeType( builder );
  1737. let inputTypeLength = builder.getTypeLength( inputType );
  1738. let inputSnippet;
  1739. if ( length + inputTypeLength > maxLength ) {
  1740. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1741. inputTypeLength = maxLength - length;
  1742. inputType = builder.getTypeFromLength( inputTypeLength );
  1743. }
  1744. length += inputTypeLength;
  1745. inputSnippet = input.build( builder, inputType );
  1746. const inputPrimitiveType = builder.getComponentType( inputType );
  1747. if ( inputPrimitiveType !== primitiveType ) {
  1748. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  1749. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  1750. }
  1751. snippetValues.push( inputSnippet );
  1752. }
  1753. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1754. return builder.format( snippet, type, output );
  1755. }
  1756. }
  1757. const _stringVectorComponents = vectorComponents.join( '' );
  1758. /**
  1759. * This module is part of the TSL core and usually not used in app level code.
  1760. * `SplitNode` represents a property access operation which means it is
  1761. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1762. * For example:
  1763. * ```js
  1764. * const redValue = color.r;
  1765. * ```
  1766. *
  1767. * @augments Node
  1768. */
  1769. class SplitNode extends Node {
  1770. static get type() {
  1771. return 'SplitNode';
  1772. }
  1773. /**
  1774. * Constructs a new split node.
  1775. *
  1776. * @param {Node} node - The node that should be accessed.
  1777. * @param {string} [components='x'] - The components that should be accessed.
  1778. */
  1779. constructor( node, components = 'x' ) {
  1780. super();
  1781. /**
  1782. * The node that should be accessed.
  1783. *
  1784. * @type {Node}
  1785. */
  1786. this.node = node;
  1787. /**
  1788. * The components that should be accessed.
  1789. *
  1790. * @type {string}
  1791. */
  1792. this.components = components;
  1793. /**
  1794. * This flag can be used for type testing.
  1795. *
  1796. * @type {boolean}
  1797. * @readonly
  1798. * @default true
  1799. */
  1800. this.isSplitNode = true;
  1801. }
  1802. /**
  1803. * Returns the vector length which is computed based on the requested components.
  1804. *
  1805. * @return {number} The vector length.
  1806. */
  1807. getVectorLength() {
  1808. let vectorLength = this.components.length;
  1809. for ( const c of this.components ) {
  1810. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1811. }
  1812. return vectorLength;
  1813. }
  1814. /**
  1815. * Returns the component type of the node's type.
  1816. *
  1817. * @param {NodeBuilder} builder - The current node builder.
  1818. * @return {string} The component type.
  1819. */
  1820. getComponentType( builder ) {
  1821. return builder.getComponentType( this.node.getNodeType( builder ) );
  1822. }
  1823. /**
  1824. * This method is overwritten since the node type is inferred from requested components.
  1825. *
  1826. * @param {NodeBuilder} builder - The current node builder.
  1827. * @return {string} The node type.
  1828. */
  1829. getNodeType( builder ) {
  1830. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1831. }
  1832. /**
  1833. * Returns the scope of the node.
  1834. *
  1835. * @return {Node} The scope of the node.
  1836. */
  1837. getScope() {
  1838. return this.node.getScope();
  1839. }
  1840. generate( builder, output ) {
  1841. const node = this.node;
  1842. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1843. let snippet = null;
  1844. if ( nodeTypeLength > 1 ) {
  1845. let type = null;
  1846. const componentsLength = this.getVectorLength();
  1847. if ( componentsLength >= nodeTypeLength ) {
  1848. // needed expand the input node
  1849. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1850. }
  1851. const nodeSnippet = node.build( builder, type );
  1852. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1853. // unnecessary swizzle
  1854. snippet = builder.format( nodeSnippet, type, output );
  1855. } else {
  1856. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1857. }
  1858. } else {
  1859. // ignore .components if .node returns float/integer
  1860. snippet = node.build( builder, output );
  1861. }
  1862. return snippet;
  1863. }
  1864. serialize( data ) {
  1865. super.serialize( data );
  1866. data.components = this.components;
  1867. }
  1868. deserialize( data ) {
  1869. super.deserialize( data );
  1870. this.components = data.components;
  1871. }
  1872. }
  1873. /**
  1874. * This module is part of the TSL core and usually not used in app level code.
  1875. * `SetNode` represents a set operation which means it is used to implement any
  1876. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1877. * For example:
  1878. * ```js
  1879. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1880. * ```
  1881. *
  1882. * @augments TempNode
  1883. */
  1884. class SetNode extends TempNode {
  1885. static get type() {
  1886. return 'SetNode';
  1887. }
  1888. /**
  1889. * Constructs a new set node.
  1890. *
  1891. * @param {Node} sourceNode - The node that should be updated.
  1892. * @param {string} components - The components that should be updated.
  1893. * @param {Node} targetNode - The value node.
  1894. */
  1895. constructor( sourceNode, components, targetNode ) {
  1896. super();
  1897. /**
  1898. * The node that should be updated.
  1899. *
  1900. * @type {Node}
  1901. */
  1902. this.sourceNode = sourceNode;
  1903. /**
  1904. * The components that should be updated.
  1905. *
  1906. * @type {string}
  1907. */
  1908. this.components = components;
  1909. /**
  1910. * The value node.
  1911. *
  1912. * @type {Node}
  1913. */
  1914. this.targetNode = targetNode;
  1915. }
  1916. /**
  1917. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1918. *
  1919. * @param {NodeBuilder} builder - The current node builder.
  1920. * @return {string} The node type.
  1921. */
  1922. getNodeType( builder ) {
  1923. return this.sourceNode.getNodeType( builder );
  1924. }
  1925. generate( builder ) {
  1926. const { sourceNode, components, targetNode } = this;
  1927. const sourceType = this.getNodeType( builder );
  1928. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1929. const targetType = builder.getTypeFromLength( components.length, componentType );
  1930. const targetSnippet = targetNode.build( builder, targetType );
  1931. const sourceSnippet = sourceNode.build( builder, sourceType );
  1932. const length = builder.getTypeLength( sourceType );
  1933. const snippetValues = [];
  1934. for ( let i = 0; i < length; i ++ ) {
  1935. const component = vectorComponents[ i ];
  1936. if ( component === components[ 0 ] ) {
  1937. snippetValues.push( targetSnippet );
  1938. i += components.length - 1;
  1939. } else {
  1940. snippetValues.push( sourceSnippet + '.' + component );
  1941. }
  1942. }
  1943. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1944. }
  1945. }
  1946. /**
  1947. * This module is part of the TSL core and usually not used in app level code.
  1948. * It represents a flip operation during the shader generation process
  1949. * meaning it flips normalized values with the following formula:
  1950. * ```
  1951. * x = 1 - x;
  1952. * ```
  1953. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1954. * `flipSTPQ()` method invocations on node objects. For example:
  1955. * ```js
  1956. * uvNode = uvNode.flipY();
  1957. * ```
  1958. *
  1959. * @augments TempNode
  1960. */
  1961. class FlipNode extends TempNode {
  1962. static get type() {
  1963. return 'FlipNode';
  1964. }
  1965. /**
  1966. * Constructs a new flip node.
  1967. *
  1968. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1969. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1970. */
  1971. constructor( sourceNode, components ) {
  1972. super();
  1973. /**
  1974. * The node which component(s) should be flipped.
  1975. *
  1976. * @type {Node}
  1977. */
  1978. this.sourceNode = sourceNode;
  1979. /**
  1980. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1981. *
  1982. * @type {string}
  1983. */
  1984. this.components = components;
  1985. }
  1986. /**
  1987. * This method is overwritten since the node type is inferred from the source node.
  1988. *
  1989. * @param {NodeBuilder} builder - The current node builder.
  1990. * @return {string} The node type.
  1991. */
  1992. getNodeType( builder ) {
  1993. return this.sourceNode.getNodeType( builder );
  1994. }
  1995. generate( builder ) {
  1996. const { components, sourceNode } = this;
  1997. const sourceType = this.getNodeType( builder );
  1998. const sourceSnippet = sourceNode.build( builder );
  1999. const sourceCache = builder.getVarFromNode( this );
  2000. const sourceProperty = builder.getPropertyName( sourceCache );
  2001. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  2002. const length = builder.getTypeLength( sourceType );
  2003. const snippetValues = [];
  2004. let componentIndex = 0;
  2005. for ( let i = 0; i < length; i ++ ) {
  2006. const component = vectorComponents[ i ];
  2007. if ( component === components[ componentIndex ] ) {
  2008. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  2009. componentIndex ++;
  2010. } else {
  2011. snippetValues.push( sourceProperty + '.' + component );
  2012. }
  2013. }
  2014. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2015. }
  2016. }
  2017. /**
  2018. * Base class for representing data input nodes.
  2019. *
  2020. * @augments Node
  2021. */
  2022. class InputNode extends Node {
  2023. static get type() {
  2024. return 'InputNode';
  2025. }
  2026. /**
  2027. * Constructs a new input node.
  2028. *
  2029. * @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).
  2030. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2031. */
  2032. constructor( value, nodeType = null ) {
  2033. super( nodeType );
  2034. /**
  2035. * This flag can be used for type testing.
  2036. *
  2037. * @type {boolean}
  2038. * @readonly
  2039. * @default true
  2040. */
  2041. this.isInputNode = true;
  2042. /**
  2043. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2044. *
  2045. * @type {any}
  2046. */
  2047. this.value = value;
  2048. /**
  2049. * The precision of the value in the shader.
  2050. *
  2051. * @type {?('low'|'medium'|'high')}
  2052. * @default null
  2053. */
  2054. this.precision = null;
  2055. }
  2056. getNodeType( /*builder*/ ) {
  2057. if ( this.nodeType === null ) {
  2058. return getValueType( this.value );
  2059. }
  2060. return this.nodeType;
  2061. }
  2062. /**
  2063. * Returns the input type of the node which is by default the node type. Derived modules
  2064. * might overwrite this method and use a fixed type or compute one analytically.
  2065. *
  2066. * A typical example for different input and node types are textures. The input type of a
  2067. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2068. *
  2069. * @param {NodeBuilder} builder - The current node builder.
  2070. * @return {string} The input type.
  2071. */
  2072. getInputType( builder ) {
  2073. return this.getNodeType( builder );
  2074. }
  2075. /**
  2076. * Sets the precision to the given value. The method can be
  2077. * overwritten in derived classes if the final precision must be computed
  2078. * analytically.
  2079. *
  2080. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2081. * @return {InputNode} A reference to this node.
  2082. */
  2083. setPrecision( precision ) {
  2084. this.precision = precision;
  2085. return this;
  2086. }
  2087. serialize( data ) {
  2088. super.serialize( data );
  2089. data.value = this.value;
  2090. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2091. data.valueType = getValueType( this.value );
  2092. data.nodeType = this.nodeType;
  2093. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2094. data.precision = this.precision;
  2095. }
  2096. deserialize( data ) {
  2097. super.deserialize( data );
  2098. this.nodeType = data.nodeType;
  2099. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2100. this.precision = data.precision || null;
  2101. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2102. }
  2103. generate( /*builder, output*/ ) {
  2104. warn( 'Abstract function.' );
  2105. }
  2106. }
  2107. const _regNum = /float|u?int/;
  2108. /**
  2109. * Class for representing a constant value in the shader.
  2110. *
  2111. * @augments InputNode
  2112. */
  2113. class ConstNode extends InputNode {
  2114. static get type() {
  2115. return 'ConstNode';
  2116. }
  2117. /**
  2118. * Constructs a new input node.
  2119. *
  2120. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2121. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2122. */
  2123. constructor( value, nodeType = null ) {
  2124. super( value, nodeType );
  2125. /**
  2126. * This flag can be used for type testing.
  2127. *
  2128. * @type {boolean}
  2129. * @readonly
  2130. * @default true
  2131. */
  2132. this.isConstNode = true;
  2133. }
  2134. /**
  2135. * Generates the shader string of the value with the current node builder.
  2136. *
  2137. * @param {NodeBuilder} builder - The current node builder.
  2138. * @return {string} The generated value as a shader string.
  2139. */
  2140. generateConst( builder ) {
  2141. return builder.generateConst( this.getNodeType( builder ), this.value );
  2142. }
  2143. generate( builder, output ) {
  2144. const type = this.getNodeType( builder );
  2145. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2146. return builder.generateConst( output, this.value );
  2147. }
  2148. return builder.format( this.generateConst( builder ), type, output );
  2149. }
  2150. }
  2151. /**
  2152. * Base class for representing member access on an object-like
  2153. * node data structures.
  2154. *
  2155. * @augments Node
  2156. */
  2157. class MemberNode extends Node {
  2158. static get type() {
  2159. return 'MemberNode';
  2160. }
  2161. /**
  2162. * Constructs a member node.
  2163. *
  2164. * @param {Node} structNode - The struct node.
  2165. * @param {string} property - The property name.
  2166. */
  2167. constructor( structNode, property ) {
  2168. super();
  2169. /**
  2170. * The struct node.
  2171. *
  2172. * @type {Node}
  2173. */
  2174. this.structNode = structNode;
  2175. /**
  2176. * The property name.
  2177. *
  2178. * @type {Node}
  2179. */
  2180. this.property = property;
  2181. /**
  2182. * This flag can be used for type testing.
  2183. *
  2184. * @type {boolean}
  2185. * @readonly
  2186. * @default true
  2187. */
  2188. this.isMemberNode = true;
  2189. }
  2190. hasMember( builder ) {
  2191. if ( this.structNode.isMemberNode ) {
  2192. if ( this.structNode.hasMember( builder ) === false ) {
  2193. return false;
  2194. }
  2195. }
  2196. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2197. }
  2198. getNodeType( builder ) {
  2199. if ( this.hasMember( builder ) === false ) {
  2200. // default type if member does not exist
  2201. return 'float';
  2202. }
  2203. return this.structNode.getMemberType( builder, this.property );
  2204. }
  2205. getMemberType( builder, name ) {
  2206. if ( this.hasMember( builder ) === false ) {
  2207. // default type if member does not exist
  2208. return 'float';
  2209. }
  2210. const type = this.getNodeType( builder );
  2211. const struct = builder.getStructTypeNode( type );
  2212. return struct.getMemberType( builder, name );
  2213. }
  2214. generate( builder ) {
  2215. if ( this.hasMember( builder ) === false ) {
  2216. warn( `TSL: Member "${ this.property }" does not exist in struct.` );
  2217. const type = this.getNodeType( builder );
  2218. return builder.generateConst( type );
  2219. }
  2220. const propertyName = this.structNode.build( builder );
  2221. return propertyName + '.' + this.property;
  2222. }
  2223. }
  2224. let currentStack = null;
  2225. const NodeElements = new Map();
  2226. // Extend Node Class for TSL using prototype
  2227. function addMethodChaining( name, nodeElement ) {
  2228. if ( NodeElements.has( name ) ) {
  2229. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2230. return;
  2231. }
  2232. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2233. NodeElements.set( name, nodeElement );
  2234. if ( name !== 'assign' ) {
  2235. // Changing Node prototype to add method chaining
  2236. Node.prototype[ name ] = function ( ...params ) {
  2237. //if ( name === 'toVarIntent' ) return this;
  2238. return this.isStackNode ? this.add( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2239. };
  2240. // Adding assign method chaining
  2241. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2242. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2243. };
  2244. }
  2245. }
  2246. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2247. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2248. Node.prototype.assign = function ( ...params ) {
  2249. if ( this.isStackNode !== true ) {
  2250. if ( currentStack !== null ) {
  2251. currentStack.assign( this, ...params );
  2252. } else {
  2253. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().' );
  2254. }
  2255. return this;
  2256. } else {
  2257. const nodeElement = NodeElements.get( 'assign' );
  2258. return this.add( nodeElement( ...params ) );
  2259. }
  2260. };
  2261. Node.prototype.toVarIntent = function () {
  2262. return this;
  2263. };
  2264. Node.prototype.get = function ( value ) {
  2265. return new MemberNode( this, value );
  2266. };
  2267. // Cache prototype for TSL
  2268. const proto = {};
  2269. // Set swizzle properties for xyzw, rgba, and stpq.
  2270. function setProtoSwizzle( property, altA, altB ) {
  2271. // swizzle properties
  2272. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2273. get() {
  2274. this._cache = this._cache || {};
  2275. //
  2276. let split = this._cache[ property ];
  2277. if ( split === undefined ) {
  2278. split = new SplitNode( this, property );
  2279. this._cache[ property ] = split;
  2280. }
  2281. return split;
  2282. },
  2283. set( value ) {
  2284. this[ property ].assign( nodeObject( value ) );
  2285. }
  2286. };
  2287. // set properties ( swizzle ) and sort to xyzw sequence
  2288. const propUpper = property.toUpperCase();
  2289. const altAUpper = altA.toUpperCase();
  2290. const altBUpper = altB.toUpperCase();
  2291. // Set methods for swizzle properties
  2292. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2293. const swizzle = parseSwizzleAndSort( property );
  2294. return new SetNode( this, swizzle, nodeObject( value ) );
  2295. };
  2296. // Set methods for flip properties
  2297. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2298. const swizzle = parseSwizzleAndSort( property );
  2299. return new FlipNode( this, swizzle );
  2300. };
  2301. }
  2302. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2303. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2304. const swizzleC = [ 's', 't', 'p', 'q' ];
  2305. for ( let a = 0; a < 4; a ++ ) {
  2306. let prop = swizzleA[ a ];
  2307. let altA = swizzleB[ a ];
  2308. let altB = swizzleC[ a ];
  2309. setProtoSwizzle( prop, altA, altB );
  2310. for ( let b = 0; b < 4; b ++ ) {
  2311. prop = swizzleA[ a ] + swizzleA[ b ];
  2312. altA = swizzleB[ a ] + swizzleB[ b ];
  2313. altB = swizzleC[ a ] + swizzleC[ b ];
  2314. setProtoSwizzle( prop, altA, altB );
  2315. for ( let c = 0; c < 4; c ++ ) {
  2316. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2317. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2318. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2319. setProtoSwizzle( prop, altA, altB );
  2320. for ( let d = 0; d < 4; d ++ ) {
  2321. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2322. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2323. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2324. setProtoSwizzle( prop, altA, altB );
  2325. }
  2326. }
  2327. }
  2328. }
  2329. // Set/get static properties for array elements (0-31).
  2330. for ( let i = 0; i < 32; i ++ ) {
  2331. proto[ i ] = {
  2332. get() {
  2333. this._cache = this._cache || {};
  2334. //
  2335. let element = this._cache[ i ];
  2336. if ( element === undefined ) {
  2337. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2338. this._cache[ i ] = element;
  2339. }
  2340. return element;
  2341. },
  2342. set( value ) {
  2343. this[ i ].assign( nodeObject( value ) );
  2344. }
  2345. };
  2346. }
  2347. /*
  2348. // Set properties for width, height, and depth.
  2349. function setProtoProperty( property, target ) {
  2350. proto[ property ] = {
  2351. get() {
  2352. this._cache = this._cache || {};
  2353. //
  2354. let split = this._cache[ target ];
  2355. if ( split === undefined ) {
  2356. split = new SplitNode( this, target );
  2357. this._cache[ target ] = split;
  2358. }
  2359. return split;
  2360. },
  2361. set( value ) {
  2362. this[ target ].assign( nodeObject( value ) );
  2363. }
  2364. };
  2365. }
  2366. setProtoProperty( 'width', 'x' );
  2367. setProtoProperty( 'height', 'y' );
  2368. setProtoProperty( 'depth', 'z' );
  2369. */
  2370. Object.defineProperties( Node.prototype, proto );
  2371. // --- FINISH ---
  2372. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2373. const ShaderNodeObject = function ( obj, altType = null ) {
  2374. const type = getValueType( obj );
  2375. if ( type === 'node' ) {
  2376. return obj;
  2377. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2378. return nodeObject( getConstNode( obj, altType ) );
  2379. } else if ( type === 'shader' ) {
  2380. return obj.isFn ? obj : Fn( obj );
  2381. }
  2382. return obj;
  2383. };
  2384. const ShaderNodeObjects = function ( objects, altType = null ) {
  2385. for ( const name in objects ) {
  2386. objects[ name ] = nodeObject( objects[ name ], altType );
  2387. }
  2388. return objects;
  2389. };
  2390. const ShaderNodeArray = function ( array, altType = null ) {
  2391. const len = array.length;
  2392. for ( let i = 0; i < len; i ++ ) {
  2393. array[ i ] = nodeObject( array[ i ], altType );
  2394. }
  2395. return array;
  2396. };
  2397. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2398. function assignNode( node ) {
  2399. if ( settings !== null ) {
  2400. node = nodeObject( Object.assign( node, settings ) );
  2401. if ( settings.intent === true ) {
  2402. node = node.toVarIntent();
  2403. }
  2404. } else {
  2405. node = nodeObject( node );
  2406. }
  2407. return node;
  2408. }
  2409. let fn, name = scope, minParams, maxParams;
  2410. function verifyParamsLimit( params ) {
  2411. let tslName;
  2412. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2413. else tslName = NodeClass.type;
  2414. if ( minParams !== undefined && params.length < minParams ) {
  2415. error( `TSL: "${ tslName }" parameter length is less than minimum required.` );
  2416. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2417. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2418. error( `TSL: "${ tslName }" parameter length exceeds limit.` );
  2419. return params.slice( 0, maxParams );
  2420. }
  2421. return params;
  2422. }
  2423. if ( scope === null ) {
  2424. fn = ( ...params ) => {
  2425. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2426. };
  2427. } else if ( factor !== null ) {
  2428. factor = nodeObject( factor );
  2429. fn = ( ...params ) => {
  2430. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2431. };
  2432. } else {
  2433. fn = ( ...params ) => {
  2434. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2435. };
  2436. }
  2437. fn.setParameterLength = ( ...params ) => {
  2438. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2439. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2440. return fn;
  2441. };
  2442. fn.setName = ( value ) => {
  2443. name = value;
  2444. return fn;
  2445. };
  2446. return fn;
  2447. };
  2448. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2449. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2450. };
  2451. class ShaderCallNodeInternal extends Node {
  2452. constructor( shaderNode, rawInputs ) {
  2453. super();
  2454. this.shaderNode = shaderNode;
  2455. this.rawInputs = rawInputs;
  2456. this.isShaderCallNodeInternal = true;
  2457. }
  2458. getNodeType( builder ) {
  2459. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2460. }
  2461. getMemberType( builder, name ) {
  2462. return this.getOutputNode( builder ).getMemberType( builder, name );
  2463. }
  2464. call( builder ) {
  2465. const { shaderNode, rawInputs } = this;
  2466. const properties = builder.getNodeProperties( shaderNode );
  2467. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2468. const subBuildProperty = subBuild || 'default';
  2469. if ( properties[ subBuildProperty ] ) {
  2470. return properties[ subBuildProperty ];
  2471. }
  2472. //
  2473. const previousSubBuildFn = builder.subBuildFn;
  2474. const previousFnCall = builder.fnCall;
  2475. builder.subBuildFn = subBuild;
  2476. builder.fnCall = this;
  2477. let result = null;
  2478. if ( shaderNode.layout ) {
  2479. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2480. if ( functionNodesCacheMap === undefined ) {
  2481. functionNodesCacheMap = new WeakMap();
  2482. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2483. }
  2484. let functionNode = functionNodesCacheMap.get( shaderNode );
  2485. if ( functionNode === undefined ) {
  2486. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2487. functionNodesCacheMap.set( shaderNode, functionNode );
  2488. }
  2489. builder.addInclude( functionNode );
  2490. //
  2491. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2492. result = nodeObject( functionNode.call( inputs ) );
  2493. } else {
  2494. const secureNodeBuilder = new Proxy( builder, {
  2495. get: ( target, property, receiver ) => {
  2496. let value;
  2497. if ( Symbol.iterator === property ) {
  2498. value = function* () {
  2499. yield undefined;
  2500. };
  2501. } else {
  2502. value = Reflect.get( target, property, receiver );
  2503. }
  2504. return value;
  2505. }
  2506. } );
  2507. //
  2508. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2509. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2510. const jsFunc = shaderNode.jsFunc;
  2511. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2512. result = nodeObject( outputNode );
  2513. }
  2514. builder.subBuildFn = previousSubBuildFn;
  2515. builder.fnCall = previousFnCall;
  2516. if ( shaderNode.once ) {
  2517. properties[ subBuildProperty ] = result;
  2518. }
  2519. return result;
  2520. }
  2521. setupOutput( builder ) {
  2522. builder.addStack();
  2523. builder.stack.outputNode = this.call( builder );
  2524. return builder.removeStack();
  2525. }
  2526. getOutputNode( builder ) {
  2527. const properties = builder.getNodeProperties( this );
  2528. const subBuildOutput = builder.getSubBuildOutput( this );
  2529. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2530. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2531. return properties[ subBuildOutput ];
  2532. }
  2533. build( builder, output = null ) {
  2534. let result = null;
  2535. const buildStage = builder.getBuildStage();
  2536. const properties = builder.getNodeProperties( this );
  2537. const subBuildOutput = builder.getSubBuildOutput( this );
  2538. const outputNode = this.getOutputNode( builder );
  2539. const previousFnCall = builder.fnCall;
  2540. builder.fnCall = this;
  2541. if ( buildStage === 'setup' ) {
  2542. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2543. if ( properties[ subBuildInitialized ] !== true ) {
  2544. properties[ subBuildInitialized ] = true;
  2545. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2546. properties[ subBuildOutput ].build( builder );
  2547. // If the shaderNode has subBuilds, add them to the chaining nodes
  2548. // so they can be built later in the build process.
  2549. if ( this.shaderNode.subBuilds ) {
  2550. for ( const node of builder.chaining ) {
  2551. const nodeData = builder.getDataFromNode( node, 'any' );
  2552. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2553. for ( const subBuild of this.shaderNode.subBuilds ) {
  2554. nodeData.subBuilds.add( subBuild );
  2555. }
  2556. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2557. }
  2558. }
  2559. }
  2560. result = properties[ subBuildOutput ];
  2561. } else if ( buildStage === 'analyze' ) {
  2562. outputNode.build( builder, output );
  2563. } else if ( buildStage === 'generate' ) {
  2564. result = outputNode.build( builder, output ) || '';
  2565. }
  2566. builder.fnCall = previousFnCall;
  2567. return result;
  2568. }
  2569. }
  2570. function getLayoutParameters( params ) {
  2571. let output;
  2572. nodeObjects( params );
  2573. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2574. if ( isArrayAsParameter ) {
  2575. output = [ ...params ];
  2576. } else {
  2577. output = params[ 0 ];
  2578. }
  2579. return output;
  2580. }
  2581. function getProxyParameters( params ) {
  2582. let index = 0;
  2583. nodeObjects( params );
  2584. return new Proxy( params, {
  2585. get: ( target, property, receiver ) => {
  2586. let value;
  2587. if ( property === 'length' ) {
  2588. value = params.length;
  2589. return value;
  2590. }
  2591. if ( Symbol.iterator === property ) {
  2592. value = function* () {
  2593. for ( const inputNode of params ) {
  2594. yield nodeObject( inputNode );
  2595. }
  2596. };
  2597. } else {
  2598. if ( params.length > 0 ) {
  2599. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2600. const objectTarget = params[ 0 ];
  2601. if ( objectTarget[ property ] === undefined ) {
  2602. value = objectTarget[ index ++ ];
  2603. } else {
  2604. value = Reflect.get( objectTarget, property, receiver );
  2605. }
  2606. } else if ( params[ 0 ] instanceof Node ) {
  2607. if ( params[ property ] === undefined ) {
  2608. value = params[ index ++ ];
  2609. } else {
  2610. value = Reflect.get( params, property, receiver );
  2611. }
  2612. }
  2613. } else {
  2614. value = Reflect.get( target, property, receiver );
  2615. }
  2616. value = nodeObject( value );
  2617. }
  2618. return value;
  2619. }
  2620. } );
  2621. }
  2622. class ShaderNodeInternal extends Node {
  2623. constructor( jsFunc, nodeType ) {
  2624. super( nodeType );
  2625. this.jsFunc = jsFunc;
  2626. this.layout = null;
  2627. this.global = true;
  2628. this.once = false;
  2629. }
  2630. setLayout( layout ) {
  2631. this.layout = layout;
  2632. return this;
  2633. }
  2634. getLayout() {
  2635. return this.layout;
  2636. }
  2637. call( rawInputs = null ) {
  2638. return new ShaderCallNodeInternal( this, rawInputs );
  2639. }
  2640. setup() {
  2641. return this.call();
  2642. }
  2643. }
  2644. const bools = [ false, true ];
  2645. const uints = [ 0, 1, 2, 3 ];
  2646. const ints = [ -1, -2 ];
  2647. 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 ];
  2648. const boolsCacheMap = new Map();
  2649. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2650. const uintsCacheMap = new Map();
  2651. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2652. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2653. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2654. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2655. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2656. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2657. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2658. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2659. const getConstNode = ( value, type ) => {
  2660. if ( constNodesCacheMap.has( value ) ) {
  2661. return constNodesCacheMap.get( value );
  2662. } else if ( value.isNode === true ) {
  2663. return value;
  2664. } else {
  2665. return new ConstNode( value, type );
  2666. }
  2667. };
  2668. const ConvertType = function ( type, cacheMap = null ) {
  2669. return ( ...params ) => {
  2670. for ( const param of params ) {
  2671. if ( param === undefined ) {
  2672. error( `TSL: Invalid parameter for the type "${ type }".` );
  2673. return nodeObject( new ConstNode( 0, type ) );
  2674. }
  2675. }
  2676. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2677. const paramType = typeof param;
  2678. return paramType !== 'object' && paramType !== 'function';
  2679. } ) ) ) {
  2680. params = [ getValueFromType( type, ...params ) ];
  2681. }
  2682. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2683. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2684. }
  2685. if ( params.length === 1 ) {
  2686. const node = getConstNode( params[ 0 ], type );
  2687. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2688. return nodeObjectIntent( new ConvertNode( node, type ) );
  2689. }
  2690. const nodes = params.map( param => getConstNode( param ) );
  2691. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2692. };
  2693. };
  2694. // exports
  2695. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2696. // utils
  2697. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2698. // shader node base
  2699. function ShaderNode( jsFunc, nodeType ) {
  2700. return new ShaderNodeInternal( jsFunc, nodeType );
  2701. }
  2702. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2703. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2704. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2705. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2706. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2707. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2708. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { intent: true, ...settings } );
  2709. let fnId = 0;
  2710. class FnNode extends Node {
  2711. constructor( jsFunc, layout = null ) {
  2712. super();
  2713. let nodeType = null;
  2714. if ( layout !== null ) {
  2715. if ( typeof layout === 'object' ) {
  2716. nodeType = layout.return;
  2717. } else {
  2718. if ( typeof layout === 'string' ) {
  2719. nodeType = layout;
  2720. } else {
  2721. error( 'TSL: Invalid layout type.' );
  2722. }
  2723. layout = null;
  2724. }
  2725. }
  2726. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2727. if ( layout !== null ) {
  2728. this.setLayout( layout );
  2729. }
  2730. this.isFn = true;
  2731. }
  2732. setLayout( layout ) {
  2733. const nodeType = this.shaderNode.nodeType;
  2734. if ( typeof layout.inputs !== 'object' ) {
  2735. const fullLayout = {
  2736. name: 'fn' + fnId ++,
  2737. type: nodeType,
  2738. inputs: []
  2739. };
  2740. for ( const name in layout ) {
  2741. if ( name === 'return' ) continue;
  2742. fullLayout.inputs.push( {
  2743. name: name,
  2744. type: layout[ name ]
  2745. } );
  2746. }
  2747. layout = fullLayout;
  2748. }
  2749. this.shaderNode.setLayout( layout );
  2750. return this;
  2751. }
  2752. getNodeType( builder ) {
  2753. return this.shaderNode.getNodeType( builder ) || 'float';
  2754. }
  2755. call( ...params ) {
  2756. const fnCall = this.shaderNode.call( params );
  2757. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2758. return fnCall.toVarIntent();
  2759. }
  2760. once( subBuilds = null ) {
  2761. this.shaderNode.once = true;
  2762. this.shaderNode.subBuilds = subBuilds;
  2763. return this;
  2764. }
  2765. generate( builder ) {
  2766. const type = this.getNodeType( builder );
  2767. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2768. return builder.generateConst( type );
  2769. }
  2770. }
  2771. function Fn( jsFunc, layout = null ) {
  2772. const instance = new FnNode( jsFunc, layout );
  2773. return new Proxy( () => {}, {
  2774. apply( target, thisArg, params ) {
  2775. return instance.call( ...params );
  2776. },
  2777. get( target, prop, receiver ) {
  2778. return Reflect.get( instance, prop, receiver );
  2779. },
  2780. set( target, prop, value, receiver ) {
  2781. return Reflect.set( instance, prop, value, receiver );
  2782. }
  2783. } );
  2784. }
  2785. //
  2786. const setCurrentStack = ( stack ) => {
  2787. currentStack = stack;
  2788. };
  2789. const getCurrentStack = () => currentStack;
  2790. /**
  2791. * Represent a conditional node using if/else statements.
  2792. *
  2793. * ```js
  2794. * If( condition, function )
  2795. * .ElseIf( condition, function )
  2796. * .Else( function )
  2797. * ```
  2798. * @tsl
  2799. * @function
  2800. * @param {...any} params - The parameters for the conditional node.
  2801. * @returns {StackNode} The conditional node.
  2802. */
  2803. const If = ( ...params ) => currentStack.If( ...params );
  2804. /**
  2805. * Represent a conditional node using switch/case statements.
  2806. *
  2807. * ```js
  2808. * Switch( value )
  2809. * .Case( 1, function )
  2810. * .Case( 2, 3, 4, function )
  2811. * .Default( function )
  2812. * ```
  2813. * @tsl
  2814. * @function
  2815. * @param {...any} params - The parameters for the conditional node.
  2816. * @returns {StackNode} The conditional node.
  2817. */
  2818. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2819. /**
  2820. * Add the given node to the current stack.
  2821. *
  2822. * @param {Node} node - The node to add.
  2823. * @returns {Node} The node that was added to the stack.
  2824. */
  2825. function Stack( node ) {
  2826. if ( currentStack ) currentStack.add( node );
  2827. return node;
  2828. }
  2829. addMethodChaining( 'toStack', Stack );
  2830. // types
  2831. const color = new ConvertType( 'color' );
  2832. const float = new ConvertType( 'float', cacheMaps.float );
  2833. const int = new ConvertType( 'int', cacheMaps.ints );
  2834. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2835. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2836. const vec2 = new ConvertType( 'vec2' );
  2837. const ivec2 = new ConvertType( 'ivec2' );
  2838. const uvec2 = new ConvertType( 'uvec2' );
  2839. const bvec2 = new ConvertType( 'bvec2' );
  2840. const vec3 = new ConvertType( 'vec3' );
  2841. const ivec3 = new ConvertType( 'ivec3' );
  2842. const uvec3 = new ConvertType( 'uvec3' );
  2843. const bvec3 = new ConvertType( 'bvec3' );
  2844. const vec4 = new ConvertType( 'vec4' );
  2845. const ivec4 = new ConvertType( 'ivec4' );
  2846. const uvec4 = new ConvertType( 'uvec4' );
  2847. const bvec4 = new ConvertType( 'bvec4' );
  2848. const mat2 = new ConvertType( 'mat2' );
  2849. const mat3 = new ConvertType( 'mat3' );
  2850. const mat4 = new ConvertType( 'mat4' );
  2851. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2852. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2853. addMethodChaining( 'toColor', color );
  2854. addMethodChaining( 'toFloat', float );
  2855. addMethodChaining( 'toInt', int );
  2856. addMethodChaining( 'toUint', uint );
  2857. addMethodChaining( 'toBool', bool );
  2858. addMethodChaining( 'toVec2', vec2 );
  2859. addMethodChaining( 'toIVec2', ivec2 );
  2860. addMethodChaining( 'toUVec2', uvec2 );
  2861. addMethodChaining( 'toBVec2', bvec2 );
  2862. addMethodChaining( 'toVec3', vec3 );
  2863. addMethodChaining( 'toIVec3', ivec3 );
  2864. addMethodChaining( 'toUVec3', uvec3 );
  2865. addMethodChaining( 'toBVec3', bvec3 );
  2866. addMethodChaining( 'toVec4', vec4 );
  2867. addMethodChaining( 'toIVec4', ivec4 );
  2868. addMethodChaining( 'toUVec4', uvec4 );
  2869. addMethodChaining( 'toBVec4', bvec4 );
  2870. addMethodChaining( 'toMat2', mat2 );
  2871. addMethodChaining( 'toMat3', mat3 );
  2872. addMethodChaining( 'toMat4', mat4 );
  2873. // basic nodes
  2874. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2875. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2876. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2877. addMethodChaining( 'element', element );
  2878. addMethodChaining( 'convert', convert );
  2879. // deprecated
  2880. /**
  2881. * @tsl
  2882. * @function
  2883. * @deprecated since r176. Use {@link Stack} instead.
  2884. *
  2885. * @param {Node} node - The node to add.
  2886. * @returns {Function}
  2887. */
  2888. const append = ( node ) => { // @deprecated, r176
  2889. warn( 'TSL: append() has been renamed to Stack().' );
  2890. return Stack( node );
  2891. };
  2892. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2893. warn( 'TSL: .append() has been renamed to .toStack().' );
  2894. return Stack( node );
  2895. } );
  2896. /**
  2897. * This class represents a shader property. It can be used
  2898. * to explicitly define a property and assign a value to it.
  2899. *
  2900. * ```js
  2901. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2902. *```
  2903. * `PropertyNode` is used by the engine to predefined common material properties
  2904. * for TSL code.
  2905. *
  2906. * @augments Node
  2907. */
  2908. class PropertyNode extends Node {
  2909. static get type() {
  2910. return 'PropertyNode';
  2911. }
  2912. /**
  2913. * Constructs a new property node.
  2914. *
  2915. * @param {string} nodeType - The type of the node.
  2916. * @param {?string} [name=null] - The name of the property in the shader.
  2917. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2918. */
  2919. constructor( nodeType, name = null, varying = false ) {
  2920. super( nodeType );
  2921. /**
  2922. * The name of the property in the shader. If no name is defined,
  2923. * the node system auto-generates one.
  2924. *
  2925. * @type {?string}
  2926. * @default null
  2927. */
  2928. this.name = name;
  2929. /**
  2930. * Whether this property is a varying or not.
  2931. *
  2932. * @type {boolean}
  2933. * @default false
  2934. */
  2935. this.varying = varying;
  2936. /**
  2937. * This flag can be used for type testing.
  2938. *
  2939. * @type {boolean}
  2940. * @readonly
  2941. * @default true
  2942. */
  2943. this.isPropertyNode = true;
  2944. /**
  2945. * This flag is used for global cache.
  2946. *
  2947. * @type {boolean}
  2948. * @default true
  2949. */
  2950. this.global = true;
  2951. }
  2952. getHash( builder ) {
  2953. return this.name || super.getHash( builder );
  2954. }
  2955. generate( builder ) {
  2956. let nodeVar;
  2957. if ( this.varying === true ) {
  2958. nodeVar = builder.getVaryingFromNode( this, this.name );
  2959. nodeVar.needsInterpolation = true;
  2960. } else {
  2961. nodeVar = builder.getVarFromNode( this, this.name );
  2962. }
  2963. return builder.getPropertyName( nodeVar );
  2964. }
  2965. }
  2966. /**
  2967. * TSL function for creating a property node.
  2968. *
  2969. * @tsl
  2970. * @function
  2971. * @param {string} type - The type of the node.
  2972. * @param {?string} [name=null] - The name of the property in the shader.
  2973. * @returns {PropertyNode}
  2974. */
  2975. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2976. /**
  2977. * TSL function for creating a varying property node.
  2978. *
  2979. * @tsl
  2980. * @function
  2981. * @param {string} type - The type of the node.
  2982. * @param {?string} [name=null] - The name of the varying in the shader.
  2983. * @returns {PropertyNode}
  2984. */
  2985. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2986. /**
  2987. * TSL object that represents the shader variable `DiffuseColor`.
  2988. *
  2989. * @tsl
  2990. * @type {PropertyNode<vec4>}
  2991. */
  2992. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2993. /**
  2994. * TSL object that represents the shader variable `EmissiveColor`.
  2995. *
  2996. * @tsl
  2997. * @type {PropertyNode<vec3>}
  2998. */
  2999. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  3000. /**
  3001. * TSL object that represents the shader variable `Roughness`.
  3002. *
  3003. * @tsl
  3004. * @type {PropertyNode<float>}
  3005. */
  3006. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  3007. /**
  3008. * TSL object that represents the shader variable `Metalness`.
  3009. *
  3010. * @tsl
  3011. * @type {PropertyNode<float>}
  3012. */
  3013. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  3014. /**
  3015. * TSL object that represents the shader variable `Clearcoat`.
  3016. *
  3017. * @tsl
  3018. * @type {PropertyNode<float>}
  3019. */
  3020. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  3021. /**
  3022. * TSL object that represents the shader variable `ClearcoatRoughness`.
  3023. *
  3024. * @tsl
  3025. * @type {PropertyNode<float>}
  3026. */
  3027. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3028. /**
  3029. * TSL object that represents the shader variable `Sheen`.
  3030. *
  3031. * @tsl
  3032. * @type {PropertyNode<vec3>}
  3033. */
  3034. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3035. /**
  3036. * TSL object that represents the shader variable `SheenRoughness`.
  3037. *
  3038. * @tsl
  3039. * @type {PropertyNode<float>}
  3040. */
  3041. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3042. /**
  3043. * TSL object that represents the shader variable `Iridescence`.
  3044. *
  3045. * @tsl
  3046. * @type {PropertyNode<float>}
  3047. */
  3048. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3049. /**
  3050. * TSL object that represents the shader variable `IridescenceIOR`.
  3051. *
  3052. * @tsl
  3053. * @type {PropertyNode<float>}
  3054. */
  3055. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3056. /**
  3057. * TSL object that represents the shader variable `IridescenceThickness`.
  3058. *
  3059. * @tsl
  3060. * @type {PropertyNode<float>}
  3061. */
  3062. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3063. /**
  3064. * TSL object that represents the shader variable `AlphaT`.
  3065. *
  3066. * @tsl
  3067. * @type {PropertyNode<float>}
  3068. */
  3069. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3070. /**
  3071. * TSL object that represents the shader variable `Anisotropy`.
  3072. *
  3073. * @tsl
  3074. * @type {PropertyNode<float>}
  3075. */
  3076. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3077. /**
  3078. * TSL object that represents the shader variable `AnisotropyT`.
  3079. *
  3080. * @tsl
  3081. * @type {PropertyNode<vec3>}
  3082. */
  3083. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3084. /**
  3085. * TSL object that represents the shader variable `AnisotropyB`.
  3086. *
  3087. * @tsl
  3088. * @type {PropertyNode<vec3>}
  3089. */
  3090. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3091. /**
  3092. * TSL object that represents the shader variable `SpecularColor`.
  3093. *
  3094. * @tsl
  3095. * @type {PropertyNode<color>}
  3096. */
  3097. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3098. /**
  3099. * TSL object that represents the shader variable `SpecularF90`.
  3100. *
  3101. * @tsl
  3102. * @type {PropertyNode<float>}
  3103. */
  3104. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3105. /**
  3106. * TSL object that represents the shader variable `Shininess`.
  3107. *
  3108. * @tsl
  3109. * @type {PropertyNode<float>}
  3110. */
  3111. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3112. /**
  3113. * TSL object that represents the shader variable `Output`.
  3114. *
  3115. * @tsl
  3116. * @type {PropertyNode<vec4>}
  3117. */
  3118. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3119. /**
  3120. * TSL object that represents the shader variable `dashSize`.
  3121. *
  3122. * @tsl
  3123. * @type {PropertyNode<float>}
  3124. */
  3125. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3126. /**
  3127. * TSL object that represents the shader variable `gapSize`.
  3128. *
  3129. * @tsl
  3130. * @type {PropertyNode<float>}
  3131. */
  3132. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3133. /**
  3134. * TSL object that represents the shader variable `pointWidth`.
  3135. *
  3136. * @tsl
  3137. * @type {PropertyNode<float>}
  3138. */
  3139. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3140. /**
  3141. * TSL object that represents the shader variable `IOR`.
  3142. *
  3143. * @tsl
  3144. * @type {PropertyNode<float>}
  3145. */
  3146. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3147. /**
  3148. * TSL object that represents the shader variable `Transmission`.
  3149. *
  3150. * @tsl
  3151. * @type {PropertyNode<float>}
  3152. */
  3153. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3154. /**
  3155. * TSL object that represents the shader variable `Thickness`.
  3156. *
  3157. * @tsl
  3158. * @type {PropertyNode<float>}
  3159. */
  3160. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3161. /**
  3162. * TSL object that represents the shader variable `AttenuationDistance`.
  3163. *
  3164. * @tsl
  3165. * @type {PropertyNode<float>}
  3166. */
  3167. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3168. /**
  3169. * TSL object that represents the shader variable `AttenuationColor`.
  3170. *
  3171. * @tsl
  3172. * @type {PropertyNode<color>}
  3173. */
  3174. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3175. /**
  3176. * TSL object that represents the shader variable `Dispersion`.
  3177. *
  3178. * @tsl
  3179. * @type {PropertyNode<float>}
  3180. */
  3181. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3182. /**
  3183. * This node can be used to group single instances of {@link UniformNode}
  3184. * and manage them as a uniform buffer.
  3185. *
  3186. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3187. * will be used when defining the {@link UniformNode#groupNode} property.
  3188. *
  3189. * - `objectGroup`: Uniform buffer per object.
  3190. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3191. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3192. *
  3193. * @augments Node
  3194. */
  3195. class UniformGroupNode extends Node {
  3196. static get type() {
  3197. return 'UniformGroupNode';
  3198. }
  3199. /**
  3200. * Constructs a new uniform group node.
  3201. *
  3202. * @param {string} name - The name of the uniform group node.
  3203. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3204. * @param {number} [order=1] - Influences the internal sorting.
  3205. */
  3206. constructor( name, shared = false, order = 1 ) {
  3207. super( 'string' );
  3208. /**
  3209. * The name of the uniform group node.
  3210. *
  3211. * @type {string}
  3212. */
  3213. this.name = name;
  3214. /**
  3215. * Whether this uniform group node is shared or not.
  3216. *
  3217. * @type {boolean}
  3218. * @default false
  3219. */
  3220. this.shared = shared;
  3221. /**
  3222. * Influences the internal sorting.
  3223. * TODO: Add details when this property should be changed.
  3224. *
  3225. * @type {number}
  3226. * @default 1
  3227. */
  3228. this.order = order;
  3229. /**
  3230. * This flag can be used for type testing.
  3231. *
  3232. * @type {boolean}
  3233. * @readonly
  3234. * @default true
  3235. */
  3236. this.isUniformGroup = true;
  3237. }
  3238. serialize( data ) {
  3239. super.serialize( data );
  3240. data.name = this.name;
  3241. data.version = this.version;
  3242. data.shared = this.shared;
  3243. }
  3244. deserialize( data ) {
  3245. super.deserialize( data );
  3246. this.name = data.name;
  3247. this.version = data.version;
  3248. this.shared = data.shared;
  3249. }
  3250. }
  3251. /**
  3252. * TSL function for creating a uniform group node with the given name.
  3253. *
  3254. * @tsl
  3255. * @function
  3256. * @param {string} name - The name of the uniform group node.
  3257. * @returns {UniformGroupNode}
  3258. */
  3259. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3260. /**
  3261. * TSL function for creating a shared uniform group node with the given name and order.
  3262. *
  3263. * @tsl
  3264. * @function
  3265. * @param {string} name - The name of the uniform group node.
  3266. * @param {number} [order=0] - Influences the internal sorting.
  3267. * @returns {UniformGroupNode}
  3268. */
  3269. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3270. /**
  3271. * TSL object that represents a shared uniform group node which is updated once per frame.
  3272. *
  3273. * @tsl
  3274. * @type {UniformGroupNode}
  3275. */
  3276. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3277. /**
  3278. * TSL object that represents a shared uniform group node which is updated once per render.
  3279. *
  3280. * @tsl
  3281. * @type {UniformGroupNode}
  3282. */
  3283. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3284. /**
  3285. * TSL object that represents a uniform group node which is updated once per object.
  3286. *
  3287. * @tsl
  3288. * @type {UniformGroupNode}
  3289. */
  3290. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3291. /**
  3292. * Class for representing a uniform.
  3293. *
  3294. * @augments InputNode
  3295. */
  3296. class UniformNode extends InputNode {
  3297. static get type() {
  3298. return 'UniformNode';
  3299. }
  3300. /**
  3301. * Constructs a new uniform node.
  3302. *
  3303. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3304. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3305. */
  3306. constructor( value, nodeType = null ) {
  3307. super( value, nodeType );
  3308. /**
  3309. * This flag can be used for type testing.
  3310. *
  3311. * @type {boolean}
  3312. * @readonly
  3313. * @default true
  3314. */
  3315. this.isUniformNode = true;
  3316. /**
  3317. * The name or label of the uniform.
  3318. *
  3319. * @type {string}
  3320. * @default ''
  3321. */
  3322. this.name = '';
  3323. /**
  3324. * The uniform group of this uniform. By default, uniforms are
  3325. * managed per object but they might belong to a shared group
  3326. * which is updated per frame or render call.
  3327. *
  3328. * @type {UniformGroupNode}
  3329. */
  3330. this.groupNode = objectGroup;
  3331. }
  3332. /**
  3333. * Sets the {@link UniformNode#name} property.
  3334. *
  3335. * @param {string} name - The name of the uniform.
  3336. * @return {UniformNode} A reference to this node.
  3337. */
  3338. setName( name ) {
  3339. this.name = name;
  3340. return this;
  3341. }
  3342. /**
  3343. * Sets the {@link UniformNode#name} property.
  3344. *
  3345. * @deprecated
  3346. * @param {string} name - The name of the uniform.
  3347. * @return {UniformNode} A reference to this node.
  3348. */
  3349. label( name ) {
  3350. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3351. return this.setName( name );
  3352. }
  3353. /**
  3354. * Sets the {@link UniformNode#groupNode} property.
  3355. *
  3356. * @param {UniformGroupNode} group - The uniform group.
  3357. * @return {UniformNode} A reference to this node.
  3358. */
  3359. setGroup( group ) {
  3360. this.groupNode = group;
  3361. return this;
  3362. }
  3363. /**
  3364. * Returns the {@link UniformNode#groupNode}.
  3365. *
  3366. * @return {UniformGroupNode} The uniform group.
  3367. */
  3368. getGroup() {
  3369. return this.groupNode;
  3370. }
  3371. /**
  3372. * By default, this method returns the result of {@link Node#getHash} but derived
  3373. * classes might overwrite this method with a different implementation.
  3374. *
  3375. * @param {NodeBuilder} builder - The current node builder.
  3376. * @return {string} The uniform hash.
  3377. */
  3378. getUniformHash( builder ) {
  3379. return this.getHash( builder );
  3380. }
  3381. onUpdate( callback, updateType ) {
  3382. callback = callback.bind( this );
  3383. return super.onUpdate( ( frame ) => {
  3384. const value = callback( frame, this );
  3385. if ( value !== undefined ) {
  3386. this.value = value;
  3387. }
  3388. }, updateType );
  3389. }
  3390. getInputType( builder ) {
  3391. let type = super.getInputType( builder );
  3392. if ( type === 'bool' ) {
  3393. type = 'uint';
  3394. }
  3395. return type;
  3396. }
  3397. generate( builder, output ) {
  3398. const type = this.getNodeType( builder );
  3399. const hash = this.getUniformHash( builder );
  3400. let sharedNode = builder.getNodeFromHash( hash );
  3401. if ( sharedNode === undefined ) {
  3402. builder.setHashNode( this, hash );
  3403. sharedNode = this;
  3404. }
  3405. const sharedNodeType = sharedNode.getInputType( builder );
  3406. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3407. const uniformName = builder.getPropertyName( nodeUniform );
  3408. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3409. //
  3410. let snippet = uniformName;
  3411. if ( type === 'bool' ) {
  3412. // cache to variable
  3413. const nodeData = builder.getDataFromNode( this );
  3414. let propertyName = nodeData.propertyName;
  3415. if ( propertyName === undefined ) {
  3416. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3417. propertyName = builder.getPropertyName( nodeVar );
  3418. nodeData.propertyName = propertyName;
  3419. snippet = builder.format( uniformName, sharedNodeType, type );
  3420. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3421. }
  3422. snippet = propertyName;
  3423. }
  3424. return builder.format( snippet, type, output );
  3425. }
  3426. }
  3427. /**
  3428. * TSL function for creating a uniform node.
  3429. *
  3430. * @tsl
  3431. * @function
  3432. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3433. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3434. * @returns {UniformNode}
  3435. */
  3436. const uniform = ( value, type ) => {
  3437. const nodeType = getConstNodeType( type || value );
  3438. if ( nodeType === value ) {
  3439. // if the value is a type but no having a value
  3440. value = getValueFromType( nodeType );
  3441. }
  3442. // @TODO: get ConstNode from .traverse() in the future
  3443. value = ( value && value.isNode === true ) ? ( value.node && value.node.value ) || value.value : value;
  3444. return nodeObject( new UniformNode( value, nodeType ) );
  3445. };
  3446. /**
  3447. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3448. * ```js
  3449. * const colors = array( [
  3450. * vec3( 1, 0, 0 ),
  3451. * vec3( 0, 1, 0 ),
  3452. * vec3( 0, 0, 1 )
  3453. * ] );
  3454. *
  3455. * const redColor = tintColors.element( 0 );
  3456. * ```
  3457. *
  3458. * @augments TempNode
  3459. */
  3460. class ArrayNode extends TempNode {
  3461. static get type() {
  3462. return 'ArrayNode';
  3463. }
  3464. /**
  3465. * Constructs a new array node.
  3466. *
  3467. * @param {?string} nodeType - The data type of the elements.
  3468. * @param {number} count - Size of the array.
  3469. * @param {?Array<Node>} [values=null] - Array default values.
  3470. */
  3471. constructor( nodeType, count, values = null ) {
  3472. super( nodeType );
  3473. /**
  3474. * Array size.
  3475. *
  3476. * @type {number}
  3477. */
  3478. this.count = count;
  3479. /**
  3480. * Array default values.
  3481. *
  3482. * @type {?Array<Node>}
  3483. */
  3484. this.values = values;
  3485. /**
  3486. * This flag can be used for type testing.
  3487. *
  3488. * @type {boolean}
  3489. * @readonly
  3490. * @default true
  3491. */
  3492. this.isArrayNode = true;
  3493. }
  3494. /**
  3495. * Returns the number of elements in the node array.
  3496. *
  3497. * @param {NodeBuilder} builder - The current node builder.
  3498. * @return {number} The number of elements in the node array.
  3499. */
  3500. getArrayCount( /*builder*/ ) {
  3501. return this.count;
  3502. }
  3503. /**
  3504. * Returns the node's type.
  3505. *
  3506. * @param {NodeBuilder} builder - The current node builder.
  3507. * @return {string} The type of the node.
  3508. */
  3509. getNodeType( builder ) {
  3510. if ( this.nodeType === null ) {
  3511. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3512. }
  3513. return this.nodeType;
  3514. }
  3515. /**
  3516. * Returns the node's type.
  3517. *
  3518. * @param {NodeBuilder} builder - The current node builder.
  3519. * @return {string} The type of the node.
  3520. */
  3521. getElementType( builder ) {
  3522. return this.getNodeType( builder );
  3523. }
  3524. /**
  3525. * This method builds the output node and returns the resulting array as a shader string.
  3526. *
  3527. * @param {NodeBuilder} builder - The current node builder.
  3528. * @return {string} The generated shader string.
  3529. */
  3530. generate( builder ) {
  3531. const type = this.getNodeType( builder );
  3532. return builder.generateArray( type, this.count, this.values );
  3533. }
  3534. }
  3535. /**
  3536. * TSL function for creating an array node.
  3537. *
  3538. * @tsl
  3539. * @function
  3540. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3541. * or an array containing the default values (e.g., [ vec3() ]).
  3542. * @param {?number} [count] - Size of the array.
  3543. * @returns {ArrayNode}
  3544. */
  3545. const array = ( ...params ) => {
  3546. let node;
  3547. if ( params.length === 1 ) {
  3548. const values = params[ 0 ];
  3549. node = new ArrayNode( null, values.length, values );
  3550. } else {
  3551. const nodeType = params[ 0 ];
  3552. const count = params[ 1 ];
  3553. node = new ArrayNode( nodeType, count );
  3554. }
  3555. return nodeObject( node );
  3556. };
  3557. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3558. /**
  3559. * These node represents an assign operation. Meaning a node is assigned
  3560. * to another node.
  3561. *
  3562. * @augments TempNode
  3563. */
  3564. class AssignNode extends TempNode {
  3565. static get type() {
  3566. return 'AssignNode';
  3567. }
  3568. /**
  3569. * Constructs a new assign node.
  3570. *
  3571. * @param {Node} targetNode - The target node.
  3572. * @param {Node} sourceNode - The source type.
  3573. */
  3574. constructor( targetNode, sourceNode ) {
  3575. super();
  3576. /**
  3577. * The target node.
  3578. *
  3579. * @type {Node}
  3580. */
  3581. this.targetNode = targetNode;
  3582. /**
  3583. * The source node.
  3584. *
  3585. * @type {Node}
  3586. */
  3587. this.sourceNode = sourceNode;
  3588. /**
  3589. * This flag can be used for type testing.
  3590. *
  3591. * @type {boolean}
  3592. * @readonly
  3593. * @default true
  3594. */
  3595. this.isAssignNode = true;
  3596. }
  3597. /**
  3598. * Whether this node is used more than once in context of other nodes. This method
  3599. * is overwritten since it always returns `false` (assigns are unique).
  3600. *
  3601. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3602. */
  3603. hasDependencies() {
  3604. return false;
  3605. }
  3606. getNodeType( builder, output ) {
  3607. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3608. }
  3609. /**
  3610. * Whether a split is required when assigning source to target. This can happen when the component length of
  3611. * target and source data type does not match.
  3612. *
  3613. * @param {NodeBuilder} builder - The current node builder.
  3614. * @return {boolean} Whether a split is required when assigning source to target.
  3615. */
  3616. needsSplitAssign( builder ) {
  3617. const { targetNode } = this;
  3618. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3619. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3620. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3621. return assignDifferentVector;
  3622. }
  3623. return false;
  3624. }
  3625. setup( builder ) {
  3626. const { targetNode, sourceNode } = this;
  3627. const scope = targetNode.getScope();
  3628. const targetProperties = builder.getNodeProperties( scope );
  3629. targetProperties.assign = true;
  3630. const properties = builder.getNodeProperties( this );
  3631. properties.sourceNode = sourceNode;
  3632. properties.targetNode = targetNode.context( { assign: true } );
  3633. }
  3634. generate( builder, output ) {
  3635. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3636. const needsSplitAssign = this.needsSplitAssign( builder );
  3637. const target = targetNode.build( builder );
  3638. const targetType = targetNode.getNodeType( builder );
  3639. const source = sourceNode.build( builder, targetType );
  3640. const sourceType = sourceNode.getNodeType( builder );
  3641. const nodeData = builder.getDataFromNode( this );
  3642. //
  3643. let snippet;
  3644. if ( nodeData.initialized === true ) {
  3645. if ( output !== 'void' ) {
  3646. snippet = target;
  3647. }
  3648. } else if ( needsSplitAssign ) {
  3649. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3650. const sourceProperty = builder.getPropertyName( sourceVar );
  3651. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3652. const splitNode = targetNode.node;
  3653. const splitTargetNode = splitNode.node.context( { assign: true } );
  3654. const targetRoot = splitTargetNode.build( builder );
  3655. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3656. const component = splitNode.components[ i ];
  3657. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3658. }
  3659. if ( output !== 'void' ) {
  3660. snippet = target;
  3661. }
  3662. } else {
  3663. snippet = `${ target } = ${ source }`;
  3664. if ( output === 'void' || sourceType === 'void' ) {
  3665. builder.addLineFlowCode( snippet, this );
  3666. if ( output !== 'void' ) {
  3667. snippet = target;
  3668. }
  3669. }
  3670. }
  3671. nodeData.initialized = true;
  3672. return builder.format( snippet, targetType, output );
  3673. }
  3674. }
  3675. /**
  3676. * TSL function for creating an assign node.
  3677. *
  3678. * @tsl
  3679. * @function
  3680. * @param {Node} targetNode - The target node.
  3681. * @param {Node} sourceNode - The source type.
  3682. * @returns {AssignNode}
  3683. */
  3684. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3685. addMethodChaining( 'assign', assign );
  3686. /**
  3687. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3688. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3689. * this logic.
  3690. *
  3691. * @augments TempNode
  3692. */
  3693. class FunctionCallNode extends TempNode {
  3694. static get type() {
  3695. return 'FunctionCallNode';
  3696. }
  3697. /**
  3698. * Constructs a new function call node.
  3699. *
  3700. * @param {?FunctionNode} functionNode - The function node.
  3701. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3702. */
  3703. constructor( functionNode = null, parameters = {} ) {
  3704. super();
  3705. /**
  3706. * The function node.
  3707. *
  3708. * @type {?FunctionNode}
  3709. * @default null
  3710. */
  3711. this.functionNode = functionNode;
  3712. /**
  3713. * The parameters of the function call.
  3714. *
  3715. * @type {Object<string, Node>}
  3716. * @default {}
  3717. */
  3718. this.parameters = parameters;
  3719. }
  3720. /**
  3721. * Sets the parameters of the function call node.
  3722. *
  3723. * @param {Object<string, Node>} parameters - The parameters to set.
  3724. * @return {FunctionCallNode} A reference to this node.
  3725. */
  3726. setParameters( parameters ) {
  3727. this.parameters = parameters;
  3728. return this;
  3729. }
  3730. /**
  3731. * Returns the parameters of the function call node.
  3732. *
  3733. * @return {Object<string, Node>} The parameters of this node.
  3734. */
  3735. getParameters() {
  3736. return this.parameters;
  3737. }
  3738. /**
  3739. * Returns the type of this function call node.
  3740. *
  3741. * @param {NodeBuilder} builder - The current node builder.
  3742. * @returns {string} The type of this node.
  3743. */
  3744. getNodeType( builder ) {
  3745. return this.functionNode.getNodeType( builder );
  3746. }
  3747. /**
  3748. * Returns the function node of this function call node.
  3749. *
  3750. * @param {NodeBuilder} builder - The current node builder.
  3751. * @param {string} [name] - The name of the member.
  3752. * @returns {string} The type of the member.
  3753. */
  3754. getMemberType( builder, name ) {
  3755. return this.functionNode.getMemberType( builder, name );
  3756. }
  3757. generate( builder ) {
  3758. const params = [];
  3759. const functionNode = this.functionNode;
  3760. const inputs = functionNode.getInputs( builder );
  3761. const parameters = this.parameters;
  3762. const generateInput = ( node, inputNode ) => {
  3763. const type = inputNode.type;
  3764. const pointer = type === 'pointer';
  3765. let output;
  3766. if ( pointer ) output = '&' + node.build( builder );
  3767. else output = node.build( builder, type );
  3768. return output;
  3769. };
  3770. if ( Array.isArray( parameters ) ) {
  3771. if ( parameters.length > inputs.length ) {
  3772. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3773. parameters.length = inputs.length;
  3774. } else if ( parameters.length < inputs.length ) {
  3775. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3776. while ( parameters.length < inputs.length ) {
  3777. parameters.push( float( 0 ) );
  3778. }
  3779. }
  3780. for ( let i = 0; i < parameters.length; i ++ ) {
  3781. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3782. }
  3783. } else {
  3784. for ( const inputNode of inputs ) {
  3785. const node = parameters[ inputNode.name ];
  3786. if ( node !== undefined ) {
  3787. params.push( generateInput( node, inputNode ) );
  3788. } else {
  3789. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3790. params.push( generateInput( float( 0 ), inputNode ) );
  3791. }
  3792. }
  3793. }
  3794. const functionName = functionNode.build( builder, 'property' );
  3795. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3796. }
  3797. }
  3798. const call = ( func, ...params ) => {
  3799. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3800. return new FunctionCallNode( nodeObject( func ), params );
  3801. };
  3802. addMethodChaining( 'call', call );
  3803. const _vectorOperators = {
  3804. '==': 'equal',
  3805. '!=': 'notEqual',
  3806. '<': 'lessThan',
  3807. '>': 'greaterThan',
  3808. '<=': 'lessThanEqual',
  3809. '>=': 'greaterThanEqual',
  3810. '%': 'mod'
  3811. };
  3812. /**
  3813. * This node represents basic mathematical and logical operations like addition,
  3814. * subtraction or comparisons (e.g. `equal()`).
  3815. *
  3816. * @augments TempNode
  3817. */
  3818. class OperatorNode extends TempNode {
  3819. static get type() {
  3820. return 'OperatorNode';
  3821. }
  3822. /**
  3823. * Constructs a new operator node.
  3824. *
  3825. * @param {string} op - The operator.
  3826. * @param {Node} aNode - The first input.
  3827. * @param {Node} bNode - The second input.
  3828. * @param {...Node} params - Additional input parameters.
  3829. */
  3830. constructor( op, aNode, bNode, ...params ) {
  3831. super();
  3832. if ( params.length > 0 ) {
  3833. let finalOp = new OperatorNode( op, aNode, bNode );
  3834. for ( let i = 0; i < params.length - 1; i ++ ) {
  3835. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3836. }
  3837. aNode = finalOp;
  3838. bNode = params[ params.length - 1 ];
  3839. }
  3840. /**
  3841. * The operator.
  3842. *
  3843. * @type {string}
  3844. */
  3845. this.op = op;
  3846. /**
  3847. * The first input.
  3848. *
  3849. * @type {Node}
  3850. */
  3851. this.aNode = aNode;
  3852. /**
  3853. * The second input.
  3854. *
  3855. * @type {Node}
  3856. */
  3857. this.bNode = bNode;
  3858. /**
  3859. * This flag can be used for type testing.
  3860. *
  3861. * @type {boolean}
  3862. * @readonly
  3863. * @default true
  3864. */
  3865. this.isOperatorNode = true;
  3866. }
  3867. /**
  3868. * Returns the operator method name.
  3869. *
  3870. * @param {NodeBuilder} builder - The current node builder.
  3871. * @param {string} output - The output type.
  3872. * @returns {string} The operator method name.
  3873. */
  3874. getOperatorMethod( builder, output ) {
  3875. return builder.getMethod( _vectorOperators[ this.op ], output );
  3876. }
  3877. /**
  3878. * This method is overwritten since the node type is inferred from the operator
  3879. * and the input node types.
  3880. *
  3881. * @param {NodeBuilder} builder - The current node builder.
  3882. * @param {?string} [output=null] - The output type.
  3883. * @return {string} The node type.
  3884. */
  3885. getNodeType( builder, output = null ) {
  3886. const op = this.op;
  3887. const aNode = this.aNode;
  3888. const bNode = this.bNode;
  3889. const typeA = aNode.getNodeType( builder );
  3890. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3891. if ( typeA === 'void' || typeB === 'void' ) {
  3892. return output || 'void';
  3893. } else if ( op === '%' ) {
  3894. return typeA;
  3895. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3896. return builder.getIntegerType( typeA );
  3897. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3898. return 'bool';
  3899. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3900. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3901. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3902. } else {
  3903. // Handle matrix operations
  3904. if ( builder.isMatrix( typeA ) ) {
  3905. if ( typeB === 'float' ) {
  3906. return typeA; // matrix * scalar = matrix
  3907. } else if ( builder.isVector( typeB ) ) {
  3908. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3909. } else if ( builder.isMatrix( typeB ) ) {
  3910. return typeA; // matrix * matrix
  3911. }
  3912. } else if ( builder.isMatrix( typeB ) ) {
  3913. if ( typeA === 'float' ) {
  3914. return typeB; // scalar * matrix = matrix
  3915. } else if ( builder.isVector( typeA ) ) {
  3916. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3917. }
  3918. }
  3919. // Handle non-matrix cases
  3920. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3921. // anytype x anytype: use the greater length vector
  3922. return typeB;
  3923. }
  3924. return typeA;
  3925. }
  3926. }
  3927. generate( builder, output ) {
  3928. const op = this.op;
  3929. const { aNode, bNode } = this;
  3930. const type = this.getNodeType( builder, output );
  3931. let typeA = null;
  3932. let typeB = null;
  3933. if ( type !== 'void' ) {
  3934. typeA = aNode.getNodeType( builder );
  3935. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3936. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3937. if ( builder.isVector( typeA ) ) {
  3938. typeB = typeA;
  3939. } else if ( builder.isVector( typeB ) ) {
  3940. typeA = typeB;
  3941. } else if ( typeA !== typeB ) {
  3942. typeA = typeB = 'float';
  3943. }
  3944. } else if ( op === '>>' || op === '<<' ) {
  3945. typeA = type;
  3946. typeB = builder.changeComponentType( typeB, 'uint' );
  3947. } else if ( op === '%' ) {
  3948. typeA = type;
  3949. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3950. } else if ( builder.isMatrix( typeA ) ) {
  3951. if ( typeB === 'float' ) {
  3952. // Keep matrix type for typeA, but ensure typeB stays float
  3953. typeB = 'float';
  3954. } else if ( builder.isVector( typeB ) ) {
  3955. // matrix x vector
  3956. typeB = builder.getVectorFromMatrix( typeA );
  3957. } else if ( builder.isMatrix( typeB ) ) ; else {
  3958. typeA = typeB = type;
  3959. }
  3960. } else if ( builder.isMatrix( typeB ) ) {
  3961. if ( typeA === 'float' ) {
  3962. // Keep matrix type for typeB, but ensure typeA stays float
  3963. typeA = 'float';
  3964. } else if ( builder.isVector( typeA ) ) {
  3965. // vector x matrix
  3966. typeA = builder.getVectorFromMatrix( typeB );
  3967. } else {
  3968. typeA = typeB = type;
  3969. }
  3970. } else {
  3971. // anytype x anytype
  3972. typeA = typeB = type;
  3973. }
  3974. } else {
  3975. typeA = typeB = type;
  3976. }
  3977. const a = aNode.build( builder, typeA );
  3978. const b = bNode ? bNode.build( builder, typeB ) : null;
  3979. const fnOpSnippet = builder.getFunctionOperator( op );
  3980. if ( output !== 'void' ) {
  3981. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3982. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3983. if ( isGLSL ) {
  3984. if ( builder.isVector( typeA ) ) {
  3985. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3986. } else {
  3987. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3988. }
  3989. } else {
  3990. // WGSL
  3991. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3992. }
  3993. } else if ( op === '%' ) {
  3994. if ( builder.isInteger( typeB ) ) {
  3995. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3996. } else {
  3997. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3998. }
  3999. } else if ( op === '!' || op === '~' ) {
  4000. return builder.format( `(${op}${a})`, typeA, output );
  4001. } else if ( fnOpSnippet ) {
  4002. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4003. } else {
  4004. // Handle matrix operations
  4005. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4006. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  4007. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  4008. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4009. } else {
  4010. let snippet = `( ${ a } ${ op } ${ b } )`;
  4011. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  4012. snippet = `all${ snippet }`;
  4013. }
  4014. return builder.format( snippet, type, output );
  4015. }
  4016. }
  4017. } else if ( typeA !== 'void' ) {
  4018. if ( fnOpSnippet ) {
  4019. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4020. } else {
  4021. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4022. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  4023. } else {
  4024. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4025. }
  4026. }
  4027. }
  4028. }
  4029. serialize( data ) {
  4030. super.serialize( data );
  4031. data.op = this.op;
  4032. }
  4033. deserialize( data ) {
  4034. super.deserialize( data );
  4035. this.op = data.op;
  4036. }
  4037. }
  4038. /**
  4039. * Returns the addition of two or more value.
  4040. *
  4041. * @tsl
  4042. * @function
  4043. * @param {Node} a - The first input.
  4044. * @param {Node} b - The second input.
  4045. * @param {...Node} params - Additional input parameters.
  4046. * @returns {OperatorNode}
  4047. */
  4048. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4049. /**
  4050. * Returns the subtraction of two or more value.
  4051. *
  4052. * @tsl
  4053. * @function
  4054. * @param {Node} a - The first input.
  4055. * @param {Node} b - The second input.
  4056. * @param {...Node} params - Additional input parameters.
  4057. * @returns {OperatorNode}
  4058. */
  4059. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4060. /**
  4061. * Returns the multiplication of two or more value.
  4062. *
  4063. * @tsl
  4064. * @function
  4065. * @param {Node} a - The first input.
  4066. * @param {Node} b - The second input.
  4067. * @param {...Node} params - Additional input parameters.
  4068. * @returns {OperatorNode}
  4069. */
  4070. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4071. /**
  4072. * Returns the division of two or more value.
  4073. *
  4074. * @tsl
  4075. * @function
  4076. * @param {Node} a - The first input.
  4077. * @param {Node} b - The second input.
  4078. * @param {...Node} params - Additional input parameters.
  4079. * @returns {OperatorNode}
  4080. */
  4081. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4082. /**
  4083. * Computes the remainder of dividing the first node by the second one.
  4084. *
  4085. * @tsl
  4086. * @function
  4087. * @param {Node} a - The first input.
  4088. * @param {Node} b - The second input.
  4089. * @returns {OperatorNode}
  4090. */
  4091. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4092. /**
  4093. * Checks if two nodes are equal.
  4094. *
  4095. * @tsl
  4096. * @function
  4097. * @param {Node} a - The first input.
  4098. * @param {Node} b - The second input.
  4099. * @returns {OperatorNode}
  4100. */
  4101. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4102. /**
  4103. * Checks if two nodes are not equal.
  4104. *
  4105. * @tsl
  4106. * @function
  4107. * @param {Node} a - The first input.
  4108. * @param {Node} b - The second input.
  4109. * @returns {OperatorNode}
  4110. */
  4111. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4112. /**
  4113. * Checks if the first node is less than the second.
  4114. *
  4115. * @tsl
  4116. * @function
  4117. * @param {Node} a - The first input.
  4118. * @param {Node} b - The second input.
  4119. * @returns {OperatorNode}
  4120. */
  4121. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4122. /**
  4123. * Checks if the first node is greater than the second.
  4124. *
  4125. * @tsl
  4126. * @function
  4127. * @param {Node} a - The first input.
  4128. * @param {Node} b - The second input.
  4129. * @returns {OperatorNode}
  4130. */
  4131. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4132. /**
  4133. * Checks if the first node is less than or equal to the second.
  4134. *
  4135. * @tsl
  4136. * @function
  4137. * @param {Node} a - The first input.
  4138. * @param {Node} b - The second input.
  4139. * @returns {OperatorNode}
  4140. */
  4141. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4142. /**
  4143. * Checks if the first node is greater than or equal to the second.
  4144. *
  4145. * @tsl
  4146. * @function
  4147. * @param {Node} a - The first input.
  4148. * @param {Node} b - The second input.
  4149. * @returns {OperatorNode}
  4150. */
  4151. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4152. /**
  4153. * Performs a logical AND operation on multiple nodes.
  4154. *
  4155. * @tsl
  4156. * @function
  4157. * @param {...Node} nodes - The input nodes to be combined using AND.
  4158. * @returns {OperatorNode}
  4159. */
  4160. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4161. /**
  4162. * Performs a logical OR operation on multiple nodes.
  4163. *
  4164. * @tsl
  4165. * @function
  4166. * @param {...Node} nodes - The input nodes to be combined using OR.
  4167. * @returns {OperatorNode}
  4168. */
  4169. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4170. /**
  4171. * Performs logical NOT on a node.
  4172. *
  4173. * @tsl
  4174. * @function
  4175. * @param {Node} value - The value.
  4176. * @returns {OperatorNode}
  4177. */
  4178. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4179. /**
  4180. * Performs logical XOR on two nodes.
  4181. *
  4182. * @tsl
  4183. * @function
  4184. * @param {Node} a - The first input.
  4185. * @param {Node} b - The second input.
  4186. * @returns {OperatorNode}
  4187. */
  4188. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4189. /**
  4190. * Performs bitwise AND on two nodes.
  4191. *
  4192. * @tsl
  4193. * @function
  4194. * @param {Node} a - The first input.
  4195. * @param {Node} b - The second input.
  4196. * @returns {OperatorNode}
  4197. */
  4198. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4199. /**
  4200. * Performs bitwise NOT on a node.
  4201. *
  4202. * @tsl
  4203. * @function
  4204. * @param {Node} a - The first input.
  4205. * @param {Node} b - The second input.
  4206. * @returns {OperatorNode}
  4207. */
  4208. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4209. /**
  4210. * Performs bitwise OR on two nodes.
  4211. *
  4212. * @tsl
  4213. * @function
  4214. * @param {Node} a - The first input.
  4215. * @param {Node} b - The second input.
  4216. * @returns {OperatorNode}
  4217. */
  4218. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4219. /**
  4220. * Performs bitwise XOR on two nodes.
  4221. *
  4222. * @tsl
  4223. * @function
  4224. * @param {Node} a - The first input.
  4225. * @param {Node} b - The second input.
  4226. * @returns {OperatorNode}
  4227. */
  4228. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4229. /**
  4230. * Shifts a node to the left.
  4231. *
  4232. * @tsl
  4233. * @function
  4234. * @param {Node} a - The node to shift.
  4235. * @param {Node} b - The value to shift.
  4236. * @returns {OperatorNode}
  4237. */
  4238. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4239. /**
  4240. * Shifts a node to the right.
  4241. *
  4242. * @tsl
  4243. * @function
  4244. * @param {Node} a - The node to shift.
  4245. * @param {Node} b - The value to shift.
  4246. * @returns {OperatorNode}
  4247. */
  4248. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4249. /**
  4250. * Increments a node by 1.
  4251. *
  4252. * @tsl
  4253. * @function
  4254. * @param {Node} a - The node to increment.
  4255. * @returns {OperatorNode}
  4256. */
  4257. const incrementBefore = Fn( ( [ a ] ) => {
  4258. a.addAssign( 1 );
  4259. return a;
  4260. } );
  4261. /**
  4262. * Decrements a node by 1.
  4263. *
  4264. * @tsl
  4265. * @function
  4266. * @param {Node} a - The node to decrement.
  4267. * @returns {OperatorNode}
  4268. */
  4269. const decrementBefore = Fn( ( [ a ] ) => {
  4270. a.subAssign( 1 );
  4271. return a;
  4272. } );
  4273. /**
  4274. * Increments a node by 1 and returns the previous value.
  4275. *
  4276. * @tsl
  4277. * @function
  4278. * @param {Node} a - The node to increment.
  4279. * @returns {OperatorNode}
  4280. */
  4281. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4282. const temp = int( a ).toConst();
  4283. a.addAssign( 1 );
  4284. return temp;
  4285. } );
  4286. /**
  4287. * Decrements a node by 1 and returns the previous value.
  4288. *
  4289. * @tsl
  4290. * @function
  4291. * @param {Node} a - The node to decrement.
  4292. * @returns {OperatorNode}
  4293. */
  4294. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4295. const temp = int( a ).toConst();
  4296. a.subAssign( 1 );
  4297. return temp;
  4298. } );
  4299. addMethodChaining( 'add', add );
  4300. addMethodChaining( 'sub', sub );
  4301. addMethodChaining( 'mul', mul );
  4302. addMethodChaining( 'div', div );
  4303. addMethodChaining( 'mod', mod );
  4304. addMethodChaining( 'equal', equal );
  4305. addMethodChaining( 'notEqual', notEqual );
  4306. addMethodChaining( 'lessThan', lessThan );
  4307. addMethodChaining( 'greaterThan', greaterThan );
  4308. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4309. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4310. addMethodChaining( 'and', and );
  4311. addMethodChaining( 'or', or );
  4312. addMethodChaining( 'not', not );
  4313. addMethodChaining( 'xor', xor );
  4314. addMethodChaining( 'bitAnd', bitAnd );
  4315. addMethodChaining( 'bitNot', bitNot );
  4316. addMethodChaining( 'bitOr', bitOr );
  4317. addMethodChaining( 'bitXor', bitXor );
  4318. addMethodChaining( 'shiftLeft', shiftLeft );
  4319. addMethodChaining( 'shiftRight', shiftRight );
  4320. addMethodChaining( 'incrementBefore', incrementBefore );
  4321. addMethodChaining( 'decrementBefore', decrementBefore );
  4322. addMethodChaining( 'increment', increment );
  4323. addMethodChaining( 'decrement', decrement );
  4324. /**
  4325. * @tsl
  4326. * @function
  4327. * @deprecated since r175. Use {@link mod} instead.
  4328. *
  4329. * @param {Node} a - The first input.
  4330. * @param {Node} b - The second input.
  4331. * @returns {OperatorNode}
  4332. */
  4333. const modInt = ( a, b ) => { // @deprecated, r175
  4334. warn( 'TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4335. return mod( int( a ), int( b ) );
  4336. };
  4337. addMethodChaining( 'modInt', modInt );
  4338. /**
  4339. * This node represents a variety of mathematical methods available in shaders.
  4340. * They are divided into three categories:
  4341. *
  4342. * - Methods with one input like `sin`, `cos` or `normalize`.
  4343. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4344. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4345. *
  4346. * @augments TempNode
  4347. */
  4348. class MathNode extends TempNode {
  4349. static get type() {
  4350. return 'MathNode';
  4351. }
  4352. /**
  4353. * Constructs a new math node.
  4354. *
  4355. * @param {string} method - The method name.
  4356. * @param {Node} aNode - The first input.
  4357. * @param {?Node} [bNode=null] - The second input.
  4358. * @param {?Node} [cNode=null] - The third input.
  4359. */
  4360. constructor( method, aNode, bNode = null, cNode = null ) {
  4361. super();
  4362. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4363. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4364. let finalOp = new MathNode( method, aNode, bNode );
  4365. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4366. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4367. }
  4368. aNode = finalOp;
  4369. bNode = arguments[ arguments.length - 1 ];
  4370. cNode = null;
  4371. }
  4372. /**
  4373. * The method name.
  4374. *
  4375. * @type {string}
  4376. */
  4377. this.method = method;
  4378. /**
  4379. * The first input.
  4380. *
  4381. * @type {Node}
  4382. */
  4383. this.aNode = aNode;
  4384. /**
  4385. * The second input.
  4386. *
  4387. * @type {?Node}
  4388. * @default null
  4389. */
  4390. this.bNode = bNode;
  4391. /**
  4392. * The third input.
  4393. *
  4394. * @type {?Node}
  4395. * @default null
  4396. */
  4397. this.cNode = cNode;
  4398. /**
  4399. * This flag can be used for type testing.
  4400. *
  4401. * @type {boolean}
  4402. * @readonly
  4403. * @default true
  4404. */
  4405. this.isMathNode = true;
  4406. }
  4407. /**
  4408. * The input type is inferred from the node types of the input nodes.
  4409. *
  4410. * @param {NodeBuilder} builder - The current node builder.
  4411. * @return {string} The input type.
  4412. */
  4413. getInputType( builder ) {
  4414. const aType = this.aNode.getNodeType( builder );
  4415. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4416. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4417. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4418. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4419. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4420. if ( aLen > bLen && aLen > cLen ) {
  4421. return aType;
  4422. } else if ( bLen > cLen ) {
  4423. return bType;
  4424. } else if ( cLen > aLen ) {
  4425. return cType;
  4426. }
  4427. return aType;
  4428. }
  4429. /**
  4430. * The selected method as well as the input type determine the node type of this node.
  4431. *
  4432. * @param {NodeBuilder} builder - The current node builder.
  4433. * @return {string} The node type.
  4434. */
  4435. getNodeType( builder ) {
  4436. const method = this.method;
  4437. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4438. return 'float';
  4439. } else if ( method === MathNode.CROSS ) {
  4440. return 'vec3';
  4441. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4442. return 'bool';
  4443. } else if ( method === MathNode.EQUALS ) {
  4444. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4445. } else {
  4446. return this.getInputType( builder );
  4447. }
  4448. }
  4449. setup( builder ) {
  4450. const { aNode, bNode, method } = this;
  4451. let outputNode = null;
  4452. if ( method === MathNode.ONE_MINUS ) {
  4453. outputNode = sub( 1.0, aNode );
  4454. } else if ( method === MathNode.RECIPROCAL ) {
  4455. outputNode = div( 1.0, aNode );
  4456. } else if ( method === MathNode.DIFFERENCE ) {
  4457. outputNode = abs( sub( aNode, bNode ) );
  4458. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4459. // dir can be either a direction vector or a normal vector
  4460. // upper-left 3x3 of matrix is assumed to be orthogonal
  4461. let tA = aNode;
  4462. let tB = bNode;
  4463. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4464. tB = vec4( vec3( tB ), 0.0 );
  4465. } else {
  4466. tA = vec4( vec3( tA ), 0.0 );
  4467. }
  4468. const mulNode = mul( tA, tB ).xyz;
  4469. outputNode = normalize( mulNode );
  4470. }
  4471. if ( outputNode !== null ) {
  4472. return outputNode;
  4473. } else {
  4474. return super.setup( builder );
  4475. }
  4476. }
  4477. generate( builder, output ) {
  4478. const properties = builder.getNodeProperties( this );
  4479. if ( properties.outputNode ) {
  4480. return super.generate( builder, output );
  4481. }
  4482. let method = this.method;
  4483. const type = this.getNodeType( builder );
  4484. const inputType = this.getInputType( builder );
  4485. const a = this.aNode;
  4486. const b = this.bNode;
  4487. const c = this.cNode;
  4488. const coordinateSystem = builder.renderer.coordinateSystem;
  4489. if ( method === MathNode.NEGATE ) {
  4490. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4491. } else {
  4492. const params = [];
  4493. if ( method === MathNode.CROSS ) {
  4494. params.push(
  4495. a.build( builder, type ),
  4496. b.build( builder, type )
  4497. );
  4498. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4499. params.push(
  4500. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4501. b.build( builder, inputType )
  4502. );
  4503. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4504. params.push(
  4505. a.build( builder, inputType ),
  4506. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4507. );
  4508. } else if ( method === MathNode.REFRACT ) {
  4509. params.push(
  4510. a.build( builder, inputType ),
  4511. b.build( builder, inputType ),
  4512. c.build( builder, 'float' )
  4513. );
  4514. } else if ( method === MathNode.MIX ) {
  4515. params.push(
  4516. a.build( builder, inputType ),
  4517. b.build( builder, inputType ),
  4518. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4519. );
  4520. } else {
  4521. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4522. method = 'atan2';
  4523. }
  4524. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4525. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4526. method = '/*' + method + '*/';
  4527. }
  4528. params.push( a.build( builder, inputType ) );
  4529. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4530. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4531. }
  4532. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4533. }
  4534. }
  4535. serialize( data ) {
  4536. super.serialize( data );
  4537. data.method = this.method;
  4538. }
  4539. deserialize( data ) {
  4540. super.deserialize( data );
  4541. this.method = data.method;
  4542. }
  4543. }
  4544. // 1 input
  4545. MathNode.ALL = 'all';
  4546. MathNode.ANY = 'any';
  4547. MathNode.RADIANS = 'radians';
  4548. MathNode.DEGREES = 'degrees';
  4549. MathNode.EXP = 'exp';
  4550. MathNode.EXP2 = 'exp2';
  4551. MathNode.LOG = 'log';
  4552. MathNode.LOG2 = 'log2';
  4553. MathNode.SQRT = 'sqrt';
  4554. MathNode.INVERSE_SQRT = 'inversesqrt';
  4555. MathNode.FLOOR = 'floor';
  4556. MathNode.CEIL = 'ceil';
  4557. MathNode.NORMALIZE = 'normalize';
  4558. MathNode.FRACT = 'fract';
  4559. MathNode.SIN = 'sin';
  4560. MathNode.COS = 'cos';
  4561. MathNode.TAN = 'tan';
  4562. MathNode.ASIN = 'asin';
  4563. MathNode.ACOS = 'acos';
  4564. MathNode.ATAN = 'atan';
  4565. MathNode.ABS = 'abs';
  4566. MathNode.SIGN = 'sign';
  4567. MathNode.LENGTH = 'length';
  4568. MathNode.NEGATE = 'negate';
  4569. MathNode.ONE_MINUS = 'oneMinus';
  4570. MathNode.DFDX = 'dFdx';
  4571. MathNode.DFDY = 'dFdy';
  4572. MathNode.ROUND = 'round';
  4573. MathNode.RECIPROCAL = 'reciprocal';
  4574. MathNode.TRUNC = 'trunc';
  4575. MathNode.FWIDTH = 'fwidth';
  4576. MathNode.TRANSPOSE = 'transpose';
  4577. MathNode.DETERMINANT = 'determinant';
  4578. MathNode.INVERSE = 'inverse';
  4579. // 2 inputs
  4580. MathNode.EQUALS = 'equals';
  4581. MathNode.MIN = 'min';
  4582. MathNode.MAX = 'max';
  4583. MathNode.STEP = 'step';
  4584. MathNode.REFLECT = 'reflect';
  4585. MathNode.DISTANCE = 'distance';
  4586. MathNode.DIFFERENCE = 'difference';
  4587. MathNode.DOT = 'dot';
  4588. MathNode.CROSS = 'cross';
  4589. MathNode.POW = 'pow';
  4590. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4591. // 3 inputs
  4592. MathNode.MIX = 'mix';
  4593. MathNode.CLAMP = 'clamp';
  4594. MathNode.REFRACT = 'refract';
  4595. MathNode.SMOOTHSTEP = 'smoothstep';
  4596. MathNode.FACEFORWARD = 'faceforward';
  4597. // 1 inputs
  4598. /**
  4599. * A small value used to handle floating-point precision errors.
  4600. *
  4601. * @tsl
  4602. * @type {Node<float>}
  4603. */
  4604. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4605. /**
  4606. * Represents infinity.
  4607. *
  4608. * @tsl
  4609. * @type {Node<float>}
  4610. */
  4611. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4612. /**
  4613. * Represents PI.
  4614. *
  4615. * @tsl
  4616. * @type {Node<float>}
  4617. */
  4618. const PI = /*@__PURE__*/ float( Math.PI );
  4619. /**
  4620. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  4621. *
  4622. * @tsl
  4623. * @deprecated
  4624. * @type {Node<float>}
  4625. */
  4626. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  4627. /**
  4628. * Represents PI * 2.
  4629. *
  4630. * @tsl
  4631. * @type {Node<float>}
  4632. */
  4633. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  4634. /**
  4635. * Represents PI / 2.
  4636. *
  4637. * @tsl
  4638. * @type {Node<float>}
  4639. */
  4640. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  4641. /**
  4642. * Returns `true` if all components of `x` are `true`.
  4643. *
  4644. * @tsl
  4645. * @function
  4646. * @param {Node | number} x - The parameter.
  4647. * @returns {Node<bool>}
  4648. */
  4649. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4650. /**
  4651. * Returns `true` if any components of `x` are `true`.
  4652. *
  4653. * @tsl
  4654. * @function
  4655. * @param {Node | number} x - The parameter.
  4656. * @returns {Node<bool>}
  4657. */
  4658. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4659. /**
  4660. * Converts a quantity in degrees to radians.
  4661. *
  4662. * @tsl
  4663. * @function
  4664. * @param {Node | number} x - The input in degrees.
  4665. * @returns {Node}
  4666. */
  4667. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4668. /**
  4669. * Convert a quantity in radians to degrees.
  4670. *
  4671. * @tsl
  4672. * @function
  4673. * @param {Node | number} x - The input in radians.
  4674. * @returns {Node}
  4675. */
  4676. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4677. /**
  4678. * Returns the natural exponentiation of the parameter.
  4679. *
  4680. * @tsl
  4681. * @function
  4682. * @param {Node | number} x - The parameter.
  4683. * @returns {Node}
  4684. */
  4685. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4686. /**
  4687. * Returns 2 raised to the power of the parameter.
  4688. *
  4689. * @tsl
  4690. * @function
  4691. * @param {Node | number} x - The parameter.
  4692. * @returns {Node}
  4693. */
  4694. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4695. /**
  4696. * Returns the natural logarithm of the parameter.
  4697. *
  4698. * @tsl
  4699. * @function
  4700. * @param {Node | number} x - The parameter.
  4701. * @returns {Node}
  4702. */
  4703. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4704. /**
  4705. * Returns the base 2 logarithm of the parameter.
  4706. *
  4707. * @tsl
  4708. * @function
  4709. * @param {Node | number} x - The parameter.
  4710. * @returns {Node}
  4711. */
  4712. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4713. /**
  4714. * Returns the square root of the parameter.
  4715. *
  4716. * @tsl
  4717. * @function
  4718. * @param {Node | number} x - The parameter.
  4719. * @returns {Node}
  4720. */
  4721. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4722. /**
  4723. * Returns the inverse of the square root of the parameter.
  4724. *
  4725. * @tsl
  4726. * @function
  4727. * @param {Node | number} x - The parameter.
  4728. * @returns {Node}
  4729. */
  4730. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4731. /**
  4732. * Finds the nearest integer less than or equal to the parameter.
  4733. *
  4734. * @tsl
  4735. * @function
  4736. * @param {Node | number} x - The parameter.
  4737. * @returns {Node}
  4738. */
  4739. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4740. /**
  4741. * Finds the nearest integer that is greater than or equal to the parameter.
  4742. *
  4743. * @tsl
  4744. * @function
  4745. * @param {Node | number} x - The parameter.
  4746. * @returns {Node}
  4747. */
  4748. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4749. /**
  4750. * Calculates the unit vector in the same direction as the original vector.
  4751. *
  4752. * @tsl
  4753. * @function
  4754. * @param {Node} x - The input vector.
  4755. * @returns {Node}
  4756. */
  4757. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4758. /**
  4759. * Computes the fractional part of the parameter.
  4760. *
  4761. * @tsl
  4762. * @function
  4763. * @param {Node | number} x - The parameter.
  4764. * @returns {Node}
  4765. */
  4766. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4767. /**
  4768. * Returns the sine of the parameter.
  4769. *
  4770. * @tsl
  4771. * @function
  4772. * @param {Node | number} x - The parameter.
  4773. * @returns {Node}
  4774. */
  4775. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4776. /**
  4777. * Returns the cosine of the parameter.
  4778. *
  4779. * @tsl
  4780. * @function
  4781. * @param {Node | number} x - The parameter.
  4782. * @returns {Node}
  4783. */
  4784. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4785. /**
  4786. * Returns the tangent of the parameter.
  4787. *
  4788. * @tsl
  4789. * @function
  4790. * @param {Node | number} x - The parameter.
  4791. * @returns {Node}
  4792. */
  4793. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4794. /**
  4795. * Returns the arcsine of the parameter.
  4796. *
  4797. * @tsl
  4798. * @function
  4799. * @param {Node | number} x - The parameter.
  4800. * @returns {Node}
  4801. */
  4802. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4803. /**
  4804. * Returns the arccosine of the parameter.
  4805. *
  4806. * @tsl
  4807. * @function
  4808. * @param {Node | number} x - The parameter.
  4809. * @returns {Node}
  4810. */
  4811. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4812. /**
  4813. * Returns the arc-tangent of the parameter.
  4814. * If two parameters are provided, the result is `atan2(y/x)`.
  4815. *
  4816. * @tsl
  4817. * @function
  4818. * @param {Node | number} y - The y parameter.
  4819. * @param {?(Node | number)} x - The x parameter.
  4820. * @returns {Node}
  4821. */
  4822. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4823. /**
  4824. * Returns the absolute value of the parameter.
  4825. *
  4826. * @tsl
  4827. * @function
  4828. * @param {Node | number} x - The parameter.
  4829. * @returns {Node}
  4830. */
  4831. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4832. /**
  4833. * Extracts the sign of the parameter.
  4834. *
  4835. * @tsl
  4836. * @function
  4837. * @param {Node | number} x - The parameter.
  4838. * @returns {Node}
  4839. */
  4840. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4841. /**
  4842. * Calculates the length of a vector.
  4843. *
  4844. * @tsl
  4845. * @function
  4846. * @param {Node} x - The parameter.
  4847. * @returns {Node<float>}
  4848. */
  4849. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4850. /**
  4851. * Negates the value of the parameter (-x).
  4852. *
  4853. * @tsl
  4854. * @function
  4855. * @param {Node | number} x - The parameter.
  4856. * @returns {Node}
  4857. */
  4858. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4859. /**
  4860. * Return `1` minus the parameter.
  4861. *
  4862. * @tsl
  4863. * @function
  4864. * @param {Node | number} x - The parameter.
  4865. * @returns {Node}
  4866. */
  4867. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4868. /**
  4869. * Returns the partial derivative of the parameter with respect to x.
  4870. *
  4871. * @tsl
  4872. * @function
  4873. * @param {Node | number} x - The parameter.
  4874. * @returns {Node}
  4875. */
  4876. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4877. /**
  4878. * Returns the partial derivative of the parameter with respect to y.
  4879. *
  4880. * @tsl
  4881. * @function
  4882. * @param {Node | number} x - The parameter.
  4883. * @returns {Node}
  4884. */
  4885. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4886. /**
  4887. * Rounds the parameter to the nearest integer.
  4888. *
  4889. * @tsl
  4890. * @function
  4891. * @param {Node | number} x - The parameter.
  4892. * @returns {Node}
  4893. */
  4894. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4895. /**
  4896. * Returns the reciprocal of the parameter `(1/x)`.
  4897. *
  4898. * @tsl
  4899. * @function
  4900. * @param {Node | number} x - The parameter.
  4901. * @returns {Node}
  4902. */
  4903. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4904. /**
  4905. * Truncates the parameter, removing the fractional part.
  4906. *
  4907. * @tsl
  4908. * @function
  4909. * @param {Node | number} x - The parameter.
  4910. * @returns {Node}
  4911. */
  4912. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4913. /**
  4914. * Returns the sum of the absolute derivatives in x and y.
  4915. *
  4916. * @tsl
  4917. * @function
  4918. * @param {Node | number} x - The parameter.
  4919. * @returns {Node}
  4920. */
  4921. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4922. /**
  4923. * Returns the transpose of a matrix.
  4924. *
  4925. * @tsl
  4926. * @function
  4927. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4928. * @returns {Node}
  4929. */
  4930. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4931. /**
  4932. * Returns the determinant of a matrix.
  4933. *
  4934. * @tsl
  4935. * @function
  4936. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4937. * @returns {Node<float>}
  4938. */
  4939. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4940. /**
  4941. * Returns the inverse of a matrix.
  4942. *
  4943. * @tsl
  4944. * @function
  4945. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4946. * @returns {Node<mat2|mat3|mat4>}
  4947. */
  4948. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4949. // 2 inputs
  4950. /**
  4951. * Returns `true` if `x` equals `y`.
  4952. *
  4953. * @tsl
  4954. * @function
  4955. * @param {Node | number} x - The first parameter.
  4956. * @param {Node | number} y - The second parameter.
  4957. * @deprecated since r175. Use {@link equal} instead.
  4958. * @returns {Node<bool>}
  4959. */
  4960. const equals = ( x, y ) => { // @deprecated, r172
  4961. warn( 'TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4962. return equal( x, y );
  4963. };
  4964. /**
  4965. * Returns the least of the given values.
  4966. *
  4967. * @tsl
  4968. * @function
  4969. * @param {...(Node | number)} values - The values to compare.
  4970. * @returns {Node}
  4971. */
  4972. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4973. /**
  4974. * Returns the greatest of the given values.
  4975. *
  4976. * @tsl
  4977. * @function
  4978. * @param {...(Node | number)} values - The values to compare.
  4979. * @returns {Node}
  4980. */
  4981. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4982. /**
  4983. * Generate a step function by comparing two values.
  4984. *
  4985. * @tsl
  4986. * @function
  4987. * @param {Node | number} x - The y parameter.
  4988. * @param {Node | number} y - The x parameter.
  4989. * @returns {Node}
  4990. */
  4991. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4992. /**
  4993. * Calculates the reflection direction for an incident vector.
  4994. *
  4995. * @tsl
  4996. * @function
  4997. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4998. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4999. * @returns {Node<vec2|vec3|vec4>}
  5000. */
  5001. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  5002. /**
  5003. * Calculates the distance between two points.
  5004. *
  5005. * @tsl
  5006. * @function
  5007. * @param {Node<vec2|vec3|vec4>} x - The first point.
  5008. * @param {Node<vec2|vec3|vec4>} y - The second point.
  5009. * @returns {Node<float>}
  5010. */
  5011. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  5012. /**
  5013. * Calculates the absolute difference between two values.
  5014. *
  5015. * @tsl
  5016. * @function
  5017. * @param {Node | number} x - The first parameter.
  5018. * @param {Node | number} y - The second parameter.
  5019. * @returns {Node}
  5020. */
  5021. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  5022. /**
  5023. * Calculates the dot product of two vectors.
  5024. *
  5025. * @tsl
  5026. * @function
  5027. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  5028. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5029. * @returns {Node<float>}
  5030. */
  5031. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5032. /**
  5033. * Calculates the cross product of two vectors.
  5034. *
  5035. * @tsl
  5036. * @function
  5037. * @param {Node<vec2|vec3>} x - The first vector.
  5038. * @param {Node<vec2|vec3>} y - The second vector.
  5039. * @returns {Node<float|vec3>}
  5040. */
  5041. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5042. /**
  5043. * Return the value of the first parameter raised to the power of the second one.
  5044. *
  5045. * @tsl
  5046. * @function
  5047. * @param {Node | number} x - The first parameter.
  5048. * @param {Node | number} y - The second parameter.
  5049. * @returns {Node}
  5050. */
  5051. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5052. /**
  5053. * Returns the square of the parameter.
  5054. *
  5055. * @tsl
  5056. * @function
  5057. * @param {Node | number} x - The first parameter.
  5058. * @returns {Node}
  5059. */
  5060. const pow2 = ( x ) => mul( x, x );
  5061. /**
  5062. * Returns the cube of the parameter.
  5063. *
  5064. * @tsl
  5065. * @function
  5066. * @param {Node | number} x - The first parameter.
  5067. * @returns {Node}
  5068. */
  5069. const pow3 = ( x ) => mul( x, x, x );
  5070. /**
  5071. * Returns the fourth power of the parameter.
  5072. *
  5073. * @tsl
  5074. * @function
  5075. * @param {Node | number} x - The first parameter.
  5076. * @returns {Node}
  5077. */
  5078. const pow4 = ( x ) => mul( x, x, x, x );
  5079. /**
  5080. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5081. *
  5082. * @tsl
  5083. * @function
  5084. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5085. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5086. * @returns {Node}
  5087. */
  5088. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5089. /**
  5090. * Returns the cube root of a number.
  5091. *
  5092. * @tsl
  5093. * @function
  5094. * @param {Node | number} a - The first parameter.
  5095. * @returns {Node}
  5096. */
  5097. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5098. /**
  5099. * Calculate the squared length of a vector.
  5100. *
  5101. * @tsl
  5102. * @function
  5103. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5104. * @returns {Node<float>}
  5105. */
  5106. const lengthSq = ( a ) => dot( a, a );
  5107. /**
  5108. * Linearly interpolates between two values.
  5109. *
  5110. * @tsl
  5111. * @function
  5112. * @param {Node | number} a - The first parameter.
  5113. * @param {Node | number} b - The second parameter.
  5114. * @param {Node | number} t - The interpolation value.
  5115. * @returns {Node}
  5116. */
  5117. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5118. /**
  5119. * Constrains a value to lie between two further values.
  5120. *
  5121. * @tsl
  5122. * @function
  5123. * @param {Node | number} value - The value to constrain.
  5124. * @param {Node | number} [low=0] - The lower bound.
  5125. * @param {Node | number} [high=1] - The upper bound.
  5126. * @returns {Node}
  5127. */
  5128. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  5129. /**
  5130. * Constrains a value between `0` and `1`.
  5131. *
  5132. * @tsl
  5133. * @function
  5134. * @param {Node | number} value - The value to constrain.
  5135. * @returns {Node}
  5136. */
  5137. const saturate = ( value ) => clamp( value );
  5138. /**
  5139. * Calculates the refraction direction for an incident vector.
  5140. *
  5141. * @tsl
  5142. * @function
  5143. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5144. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5145. * @param {Node<float>} eta - The ratio of indices of refraction.
  5146. * @returns {Node<vec2|vec3|vec4>}
  5147. */
  5148. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5149. /**
  5150. * Performs a Hermite interpolation between two values.
  5151. *
  5152. * @tsl
  5153. * @function
  5154. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5155. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5156. * @param {Node | number} x - The source value for interpolation.
  5157. * @returns {Node}
  5158. */
  5159. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5160. /**
  5161. * Returns a vector pointing in the same direction as another.
  5162. *
  5163. * @tsl
  5164. * @function
  5165. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5166. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5167. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5168. * @returns {Node<vec2|vec3|vec4>}
  5169. */
  5170. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5171. /**
  5172. * Returns a random value for the given uv.
  5173. *
  5174. * @tsl
  5175. * @function
  5176. * @param {Node<vec2>} uv - The uv node.
  5177. * @returns {Node<float>}
  5178. */
  5179. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5180. const a = 12.9898, b = 78.233, c = 43758.5453;
  5181. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5182. return fract( sin( sn ).mul( c ) );
  5183. } );
  5184. /**
  5185. * Alias for `mix()` with a different parameter order.
  5186. *
  5187. * @tsl
  5188. * @function
  5189. * @param {Node | number} t - The interpolation value.
  5190. * @param {Node | number} e1 - The first parameter.
  5191. * @param {Node | number} e2 - The second parameter.
  5192. * @returns {Node}
  5193. */
  5194. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5195. /**
  5196. * Alias for `smoothstep()` with a different parameter order.
  5197. *
  5198. * @tsl
  5199. * @function
  5200. * @param {Node | number} x - The source value for interpolation.
  5201. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5202. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5203. * @returns {Node}
  5204. */
  5205. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5206. /**
  5207. * Alias for `step()` with a different parameter order.
  5208. *
  5209. * @tsl
  5210. * @function
  5211. * @param {Node | number} x - The source value for interpolation.
  5212. * @param {Node | number} edge - The edge value.
  5213. * @returns {Node}
  5214. */
  5215. const stepElement = ( x, edge ) => step( edge, x );
  5216. /**
  5217. * Returns the arc-tangent of the quotient of its parameters.
  5218. *
  5219. * @tsl
  5220. * @function
  5221. * @deprecated since r172. Use {@link atan} instead.
  5222. *
  5223. * @param {Node | number} y - The y parameter.
  5224. * @param {Node | number} x - The x parameter.
  5225. * @returns {Node}
  5226. */
  5227. const atan2 = ( y, x ) => { // @deprecated, r172
  5228. warn( 'TSL: "atan2" is overloaded. Use "atan" instead.' );
  5229. return atan( y, x );
  5230. };
  5231. // GLSL alias function
  5232. const faceforward = faceForward;
  5233. const inversesqrt = inverseSqrt;
  5234. // Method chaining
  5235. addMethodChaining( 'all', all );
  5236. addMethodChaining( 'any', any );
  5237. addMethodChaining( 'equals', equals );
  5238. addMethodChaining( 'radians', radians );
  5239. addMethodChaining( 'degrees', degrees );
  5240. addMethodChaining( 'exp', exp );
  5241. addMethodChaining( 'exp2', exp2 );
  5242. addMethodChaining( 'log', log );
  5243. addMethodChaining( 'log2', log2 );
  5244. addMethodChaining( 'sqrt', sqrt );
  5245. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5246. addMethodChaining( 'floor', floor );
  5247. addMethodChaining( 'ceil', ceil );
  5248. addMethodChaining( 'normalize', normalize );
  5249. addMethodChaining( 'fract', fract );
  5250. addMethodChaining( 'sin', sin );
  5251. addMethodChaining( 'cos', cos );
  5252. addMethodChaining( 'tan', tan );
  5253. addMethodChaining( 'asin', asin );
  5254. addMethodChaining( 'acos', acos );
  5255. addMethodChaining( 'atan', atan );
  5256. addMethodChaining( 'abs', abs );
  5257. addMethodChaining( 'sign', sign );
  5258. addMethodChaining( 'length', length );
  5259. addMethodChaining( 'lengthSq', lengthSq );
  5260. addMethodChaining( 'negate', negate );
  5261. addMethodChaining( 'oneMinus', oneMinus );
  5262. addMethodChaining( 'dFdx', dFdx );
  5263. addMethodChaining( 'dFdy', dFdy );
  5264. addMethodChaining( 'round', round );
  5265. addMethodChaining( 'reciprocal', reciprocal );
  5266. addMethodChaining( 'trunc', trunc );
  5267. addMethodChaining( 'fwidth', fwidth );
  5268. addMethodChaining( 'atan2', atan2 );
  5269. addMethodChaining( 'min', min$1 );
  5270. addMethodChaining( 'max', max$1 );
  5271. addMethodChaining( 'step', stepElement );
  5272. addMethodChaining( 'reflect', reflect );
  5273. addMethodChaining( 'distance', distance );
  5274. addMethodChaining( 'dot', dot );
  5275. addMethodChaining( 'cross', cross );
  5276. addMethodChaining( 'pow', pow );
  5277. addMethodChaining( 'pow2', pow2 );
  5278. addMethodChaining( 'pow3', pow3 );
  5279. addMethodChaining( 'pow4', pow4 );
  5280. addMethodChaining( 'transformDirection', transformDirection );
  5281. addMethodChaining( 'mix', mixElement );
  5282. addMethodChaining( 'clamp', clamp );
  5283. addMethodChaining( 'refract', refract );
  5284. addMethodChaining( 'smoothstep', smoothstepElement );
  5285. addMethodChaining( 'faceForward', faceForward );
  5286. addMethodChaining( 'difference', difference );
  5287. addMethodChaining( 'saturate', saturate );
  5288. addMethodChaining( 'cbrt', cbrt );
  5289. addMethodChaining( 'transpose', transpose );
  5290. addMethodChaining( 'determinant', determinant );
  5291. addMethodChaining( 'inverse', inverse );
  5292. addMethodChaining( 'rand', rand );
  5293. /**
  5294. * Represents a logical `if/else` statement. Can be used as an alternative
  5295. * to the `If()`/`Else()` syntax.
  5296. *
  5297. * The corresponding TSL `select()` looks like so:
  5298. * ```js
  5299. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5300. * ```
  5301. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5302. * determine the outcome of the entire statement.
  5303. *
  5304. * @augments Node
  5305. */
  5306. class ConditionalNode extends Node {
  5307. static get type() {
  5308. return 'ConditionalNode';
  5309. }
  5310. /**
  5311. * Constructs a new conditional node.
  5312. *
  5313. * @param {Node} condNode - The node that defines the condition.
  5314. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5315. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5316. */
  5317. constructor( condNode, ifNode, elseNode = null ) {
  5318. super();
  5319. /**
  5320. * The node that defines the condition.
  5321. *
  5322. * @type {Node}
  5323. */
  5324. this.condNode = condNode;
  5325. /**
  5326. * The node that is evaluate when the condition ends up `true`.
  5327. *
  5328. * @type {Node}
  5329. */
  5330. this.ifNode = ifNode;
  5331. /**
  5332. * The node that is evaluate when the condition ends up `false`.
  5333. *
  5334. * @type {?Node}
  5335. * @default null
  5336. */
  5337. this.elseNode = elseNode;
  5338. }
  5339. /**
  5340. * This method is overwritten since the node type is inferred from the if/else
  5341. * nodes.
  5342. *
  5343. * @param {NodeBuilder} builder - The current node builder.
  5344. * @return {string} The node type.
  5345. */
  5346. getNodeType( builder ) {
  5347. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5348. if ( ifNode === undefined ) {
  5349. // fallback setup
  5350. builder.flowBuildStage( this, 'setup' );
  5351. return this.getNodeType( builder );
  5352. }
  5353. const ifType = ifNode.getNodeType( builder );
  5354. if ( elseNode !== null ) {
  5355. const elseType = elseNode.getNodeType( builder );
  5356. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5357. return elseType;
  5358. }
  5359. }
  5360. return ifType;
  5361. }
  5362. setup( builder ) {
  5363. const condNode = this.condNode;
  5364. const ifNode = this.ifNode.isolate();
  5365. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5366. //
  5367. const currentNodeBlock = builder.context.nodeBlock;
  5368. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5369. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5370. //
  5371. const isUniformFlow = builder.context.uniformFlow;
  5372. const properties = builder.getNodeProperties( this );
  5373. properties.condNode = condNode;
  5374. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5375. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5376. }
  5377. generate( builder, output ) {
  5378. const type = this.getNodeType( builder );
  5379. const nodeData = builder.getDataFromNode( this );
  5380. if ( nodeData.nodeProperty !== undefined ) {
  5381. return nodeData.nodeProperty;
  5382. }
  5383. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5384. const functionNode = builder.currentFunctionNode;
  5385. const needsOutput = output !== 'void';
  5386. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5387. nodeData.nodeProperty = nodeProperty;
  5388. const nodeSnippet = condNode.build( builder, 'bool' );
  5389. const isUniformFlow = builder.context.uniformFlow;
  5390. if ( isUniformFlow && elseNode !== null ) {
  5391. const ifSnippet = ifNode.build( builder, type );
  5392. const elseSnippet = elseNode.build( builder, type );
  5393. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5394. // TODO: If node property already exists return something else
  5395. return builder.format( mathSnippet, type, output );
  5396. }
  5397. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5398. let ifSnippet = ifNode.build( builder, type );
  5399. if ( ifSnippet ) {
  5400. if ( needsOutput ) {
  5401. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5402. } else {
  5403. ifSnippet = 'return ' + ifSnippet + ';';
  5404. if ( functionNode === null ) {
  5405. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5406. ifSnippet = '// ' + ifSnippet;
  5407. }
  5408. }
  5409. }
  5410. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5411. if ( elseNode !== null ) {
  5412. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5413. let elseSnippet = elseNode.build( builder, type );
  5414. if ( elseSnippet ) {
  5415. if ( needsOutput ) {
  5416. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5417. } else {
  5418. elseSnippet = 'return ' + elseSnippet + ';';
  5419. if ( functionNode === null ) {
  5420. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5421. elseSnippet = '// ' + elseSnippet;
  5422. }
  5423. }
  5424. }
  5425. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5426. } else {
  5427. builder.addFlowCode( '\n\n' );
  5428. }
  5429. return builder.format( nodeProperty, type, output );
  5430. }
  5431. }
  5432. /**
  5433. * TSL function for creating a conditional node.
  5434. *
  5435. * @tsl
  5436. * @function
  5437. * @param {Node} condNode - The node that defines the condition.
  5438. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5439. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5440. * @returns {ConditionalNode}
  5441. */
  5442. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5443. addMethodChaining( 'select', select );
  5444. /**
  5445. * This node can be used as a context management component for another node.
  5446. * {@link NodeBuilder} performs its node building process in a specific context and
  5447. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5448. *
  5449. * ```js
  5450. *node.context( { getUV: () => customCoord } );
  5451. *```
  5452. * @augments Node
  5453. */
  5454. class ContextNode extends Node {
  5455. static get type() {
  5456. return 'ContextNode';
  5457. }
  5458. /**
  5459. * Constructs a new context node.
  5460. *
  5461. * @param {Node} node - The node whose context should be modified.
  5462. * @param {Object} [value={}] - The modified context data.
  5463. */
  5464. constructor( node, value = {} ) {
  5465. super();
  5466. /**
  5467. * This flag can be used for type testing.
  5468. *
  5469. * @type {boolean}
  5470. * @readonly
  5471. * @default true
  5472. */
  5473. this.isContextNode = true;
  5474. /**
  5475. * The node whose context should be modified.
  5476. *
  5477. * @type {Node}
  5478. */
  5479. this.node = node;
  5480. /**
  5481. * The modified context data.
  5482. *
  5483. * @type {Object}
  5484. * @default {}
  5485. */
  5486. this.value = value;
  5487. }
  5488. /**
  5489. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5490. *
  5491. * @return {Node} A reference to {@link ContextNode#node}.
  5492. */
  5493. getScope() {
  5494. return this.node.getScope();
  5495. }
  5496. /**
  5497. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5498. *
  5499. * @param {NodeBuilder} builder - The current node builder.
  5500. * @return {string} The node type.
  5501. */
  5502. getNodeType( builder ) {
  5503. return this.node.getNodeType( builder );
  5504. }
  5505. /**
  5506. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5507. *
  5508. * @param {NodeBuilder} builder - The current node builder.
  5509. * @param {string} name - The member name.
  5510. * @returns {string} The member type.
  5511. */
  5512. getMemberType( builder, name ) {
  5513. return this.node.getMemberType( builder, name );
  5514. }
  5515. analyze( builder ) {
  5516. const previousContext = builder.addContext( this.value );
  5517. this.node.build( builder );
  5518. builder.setContext( previousContext );
  5519. }
  5520. setup( builder ) {
  5521. const previousContext = builder.addContext( this.value );
  5522. this.node.build( builder );
  5523. builder.setContext( previousContext );
  5524. }
  5525. generate( builder, output ) {
  5526. const previousContext = builder.addContext( this.value );
  5527. const snippet = this.node.build( builder, output );
  5528. builder.setContext( previousContext );
  5529. return snippet;
  5530. }
  5531. }
  5532. /**
  5533. * TSL function for creating a context node.
  5534. *
  5535. * @tsl
  5536. * @function
  5537. * @param {Node} node - The node whose context should be modified.
  5538. * @param {Object} [value={}] - The modified context data.
  5539. * @returns {ContextNode}
  5540. */
  5541. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5542. /**
  5543. * TSL function for defining a uniformFlow context value for a given node.
  5544. *
  5545. * @tsl
  5546. * @function
  5547. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5548. * @returns {ContextNode}
  5549. */
  5550. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5551. /**
  5552. * TSL function for defining a name for the context value for a given node.
  5553. *
  5554. * @tsl
  5555. * @function
  5556. * @param {Node} node - The node whose context should be modified.
  5557. * @param {string} name - The name to set.
  5558. * @returns {ContextNode}
  5559. */
  5560. const setName = ( node, name ) => context( node, { nodeName: name } );
  5561. /**
  5562. * TSL function for defining a label context value for a given node.
  5563. *
  5564. * @tsl
  5565. * @function
  5566. * @deprecated
  5567. * @param {Node} node - The node whose context should be modified.
  5568. * @param {string} name - The name/label to set.
  5569. * @returns {ContextNode}
  5570. */
  5571. function label( node, name ) {
  5572. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5573. return setName( node, name );
  5574. }
  5575. addMethodChaining( 'context', context );
  5576. addMethodChaining( 'label', label );
  5577. addMethodChaining( 'uniformFlow', uniformFlow );
  5578. addMethodChaining( 'setName', setName );
  5579. /**
  5580. * Class for representing shader variables as nodes. Variables are created from
  5581. * existing nodes like the following:
  5582. *
  5583. * ```js
  5584. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5585. * ```
  5586. *
  5587. * @augments Node
  5588. */
  5589. class VarNode extends Node {
  5590. static get type() {
  5591. return 'VarNode';
  5592. }
  5593. /**
  5594. * Constructs a new variable node.
  5595. *
  5596. * @param {Node} node - The node for which a variable should be created.
  5597. * @param {?string} [name=null] - The name of the variable in the shader.
  5598. * @param {boolean} [readOnly=false] - The read-only flag.
  5599. */
  5600. constructor( node, name = null, readOnly = false ) {
  5601. super();
  5602. /**
  5603. * The node for which a variable should be created.
  5604. *
  5605. * @type {Node}
  5606. */
  5607. this.node = node;
  5608. /**
  5609. * The name of the variable in the shader. If no name is defined,
  5610. * the node system auto-generates one.
  5611. *
  5612. * @type {?string}
  5613. * @default null
  5614. */
  5615. this.name = name;
  5616. /**
  5617. * `VarNode` sets this property to `true` by default.
  5618. *
  5619. * @type {boolean}
  5620. * @default true
  5621. */
  5622. this.global = true;
  5623. /**
  5624. * This flag can be used for type testing.
  5625. *
  5626. * @type {boolean}
  5627. * @readonly
  5628. * @default true
  5629. */
  5630. this.isVarNode = true;
  5631. /**
  5632. *
  5633. * The read-only flag.
  5634. *
  5635. * @type {boolean}
  5636. * @default false
  5637. */
  5638. this.readOnly = readOnly;
  5639. /**
  5640. *
  5641. * Add this flag to the node system to indicate that this node require parents.
  5642. *
  5643. * @type {boolean}
  5644. * @default true
  5645. */
  5646. this.parents = true;
  5647. /**
  5648. * This flag is used to indicate that this node is used for intent.
  5649. *
  5650. * @type {boolean}
  5651. * @default false
  5652. */
  5653. this.intent = false;
  5654. }
  5655. /**
  5656. * Sets the intent flag for this node.
  5657. *
  5658. * This flag is used to indicate that this node is used for intent
  5659. * and should not be built directly. Instead, it is used to indicate that
  5660. * the node should be treated as a variable intent.
  5661. *
  5662. * It's useful for assigning variables without needing creating a new variable node.
  5663. *
  5664. * @param {boolean} value - The value to set for the intent flag.
  5665. * @returns {VarNode} This node.
  5666. */
  5667. setIntent( value ) {
  5668. this.intent = value;
  5669. return this;
  5670. }
  5671. /**
  5672. * Returns the intent flag of this node.
  5673. *
  5674. * @return {boolean} The intent flag.
  5675. */
  5676. getIntent() {
  5677. return this.intent;
  5678. }
  5679. getMemberType( builder, name ) {
  5680. return this.node.getMemberType( builder, name );
  5681. }
  5682. getElementType( builder ) {
  5683. return this.node.getElementType( builder );
  5684. }
  5685. getNodeType( builder ) {
  5686. return this.node.getNodeType( builder );
  5687. }
  5688. getArrayCount( builder ) {
  5689. return this.node.getArrayCount( builder );
  5690. }
  5691. isAssign( builder ) {
  5692. const properties = builder.getNodeProperties( this );
  5693. let assign = properties.assign;
  5694. if ( assign !== true ) {
  5695. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  5696. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  5697. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  5698. if ( shaderNodeData.hasLoop ) {
  5699. assign = true;
  5700. }
  5701. }
  5702. }
  5703. }
  5704. return assign;
  5705. }
  5706. build( ...params ) {
  5707. if ( this.intent === true ) {
  5708. const builder = params[ 0 ];
  5709. if ( this.isAssign( builder ) !== true ) {
  5710. return this.node.build( ...params );
  5711. }
  5712. }
  5713. return super.build( ...params );
  5714. }
  5715. generate( builder ) {
  5716. const { node, name, readOnly } = this;
  5717. const { renderer } = builder;
  5718. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5719. let isDeterministic = false;
  5720. let shouldTreatAsReadOnly = false;
  5721. if ( readOnly ) {
  5722. isDeterministic = builder.isDeterministic( node );
  5723. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5724. }
  5725. const nodeType = this.getNodeType( builder );
  5726. if ( nodeType == 'void' ) {
  5727. if ( this.intent !== true ) {
  5728. error( 'TSL: ".toVar()" can not be used with void type.' );
  5729. }
  5730. const snippet = node.build( builder );
  5731. return snippet;
  5732. }
  5733. const vectorType = builder.getVectorType( nodeType );
  5734. const snippet = node.build( builder, vectorType );
  5735. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5736. const propertyName = builder.getPropertyName( nodeVar );
  5737. let declarationPrefix = propertyName;
  5738. if ( shouldTreatAsReadOnly ) {
  5739. if ( isWebGPUBackend ) {
  5740. declarationPrefix = isDeterministic
  5741. ? `const ${ propertyName }`
  5742. : `let ${ propertyName }`;
  5743. } else {
  5744. const count = node.getArrayCount( builder );
  5745. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5746. }
  5747. }
  5748. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5749. return propertyName;
  5750. }
  5751. }
  5752. /**
  5753. * TSL function for creating a var node.
  5754. *
  5755. * @tsl
  5756. * @function
  5757. * @param {Node} node - The node for which a variable should be created.
  5758. * @param {?string} name - The name of the variable in the shader.
  5759. * @returns {VarNode}
  5760. */
  5761. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5762. /**
  5763. * TSL function for creating a var node.
  5764. *
  5765. * @tsl
  5766. * @function
  5767. * @param {Node} node - The node for which a variable should be created.
  5768. * @param {?string} name - The name of the variable in the shader.
  5769. * @returns {VarNode}
  5770. */
  5771. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5772. /**
  5773. * TSL function for creating a const node.
  5774. *
  5775. * @tsl
  5776. * @function
  5777. * @param {Node} node - The node for which a constant should be created.
  5778. * @param {?string} name - The name of the constant in the shader.
  5779. * @returns {VarNode}
  5780. */
  5781. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5782. //
  5783. //
  5784. /**
  5785. * TSL function for creating a var intent node.
  5786. *
  5787. * @tsl
  5788. * @function
  5789. * @param {Node} node - The node for which a variable should be created.
  5790. * @param {?string} name - The name of the variable in the shader.
  5791. * @returns {VarNode}
  5792. */
  5793. const VarIntent = ( node ) => {
  5794. if ( getCurrentStack() === null ) {
  5795. return node;
  5796. }
  5797. return createVar( node ).setIntent( true ).toStack();
  5798. };
  5799. // Method chaining
  5800. addMethodChaining( 'toVar', Var );
  5801. addMethodChaining( 'toConst', Const );
  5802. addMethodChaining( 'toVarIntent', VarIntent );
  5803. /**
  5804. * This node is used to build a sub-build in the node system.
  5805. *
  5806. * @augments Node
  5807. * @param {Node} node - The node to be built in the sub-build.
  5808. * @param {string} name - The name of the sub-build.
  5809. * @param {?string} [nodeType=null] - The type of the node, if known.
  5810. */
  5811. class SubBuildNode extends Node {
  5812. static get type() {
  5813. return 'SubBuild';
  5814. }
  5815. constructor( node, name, nodeType = null ) {
  5816. super( nodeType );
  5817. /**
  5818. * The node to be built in the sub-build.
  5819. *
  5820. * @type {Node}
  5821. */
  5822. this.node = node;
  5823. /**
  5824. * The name of the sub-build.
  5825. *
  5826. * @type {string}
  5827. */
  5828. this.name = name;
  5829. /**
  5830. * This flag can be used for type testing.
  5831. *
  5832. * @type {boolean}
  5833. * @readonly
  5834. * @default true
  5835. */
  5836. this.isSubBuildNode = true;
  5837. }
  5838. getNodeType( builder ) {
  5839. if ( this.nodeType !== null ) return this.nodeType;
  5840. builder.addSubBuild( this.name );
  5841. const nodeType = this.node.getNodeType( builder );
  5842. builder.removeSubBuild();
  5843. return nodeType;
  5844. }
  5845. build( builder, ...params ) {
  5846. builder.addSubBuild( this.name );
  5847. const data = this.node.build( builder, ...params );
  5848. builder.removeSubBuild();
  5849. return data;
  5850. }
  5851. }
  5852. /**
  5853. * Creates a new sub-build node.
  5854. *
  5855. * @tsl
  5856. * @function
  5857. * @param {Node} node - The node to be built in the sub-build.
  5858. * @param {string} name - The name of the sub-build.
  5859. * @param {?string} [type=null] - The type of the node, if known.
  5860. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5861. */
  5862. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5863. /**
  5864. * Class for representing shader varyings as nodes. Varyings are create from
  5865. * existing nodes like the following:
  5866. *
  5867. * ```js
  5868. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5869. * ```
  5870. *
  5871. * @augments Node
  5872. */
  5873. class VaryingNode extends Node {
  5874. static get type() {
  5875. return 'VaryingNode';
  5876. }
  5877. /**
  5878. * Constructs a new varying node.
  5879. *
  5880. * @param {Node} node - The node for which a varying should be created.
  5881. * @param {?string} name - The name of the varying in the shader.
  5882. */
  5883. constructor( node, name = null ) {
  5884. super();
  5885. /**
  5886. * The node for which a varying should be created.
  5887. *
  5888. * @type {Node}
  5889. */
  5890. this.node = node;
  5891. /**
  5892. * The name of the varying in the shader. If no name is defined,
  5893. * the node system auto-generates one.
  5894. *
  5895. * @type {?string}
  5896. * @default null
  5897. */
  5898. this.name = name;
  5899. /**
  5900. * This flag can be used for type testing.
  5901. *
  5902. * @type {boolean}
  5903. * @readonly
  5904. * @default true
  5905. */
  5906. this.isVaryingNode = true;
  5907. /**
  5908. * The interpolation type of the varying data.
  5909. *
  5910. * @type {?string}
  5911. * @default null
  5912. */
  5913. this.interpolationType = null;
  5914. /**
  5915. * The interpolation sampling type of varying data.
  5916. *
  5917. * @type {?string}
  5918. * @default null
  5919. */
  5920. this.interpolationSampling = null;
  5921. /**
  5922. * This flag is used for global cache.
  5923. *
  5924. * @type {boolean}
  5925. * @default true
  5926. */
  5927. this.global = true;
  5928. }
  5929. /**
  5930. * Defines the interpolation type of the varying.
  5931. *
  5932. * @param {string} type - The interpolation type.
  5933. * @param {?string} sampling - The interpolation sampling type
  5934. * @return {VaryingNode} A reference to this node.
  5935. */
  5936. setInterpolation( type, sampling = null ) {
  5937. this.interpolationType = type;
  5938. this.interpolationSampling = sampling;
  5939. return this;
  5940. }
  5941. getHash( builder ) {
  5942. return this.name || super.getHash( builder );
  5943. }
  5944. getNodeType( builder ) {
  5945. // VaryingNode is auto type
  5946. return this.node.getNodeType( builder );
  5947. }
  5948. /**
  5949. * This method performs the setup of a varying node with the current node builder.
  5950. *
  5951. * @param {NodeBuilder} builder - The current node builder.
  5952. * @return {NodeVarying} The node varying from the node builder.
  5953. */
  5954. setupVarying( builder ) {
  5955. const properties = builder.getNodeProperties( this );
  5956. let varying = properties.varying;
  5957. if ( varying === undefined ) {
  5958. const name = this.name;
  5959. const type = this.getNodeType( builder );
  5960. const interpolationType = this.interpolationType;
  5961. const interpolationSampling = this.interpolationSampling;
  5962. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5963. properties.node = subBuild( this.node, 'VERTEX' );
  5964. }
  5965. // this property can be used to check if the varying can be optimized for a variable
  5966. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5967. return varying;
  5968. }
  5969. setup( builder ) {
  5970. this.setupVarying( builder );
  5971. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5972. }
  5973. analyze( builder ) {
  5974. this.setupVarying( builder );
  5975. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5976. }
  5977. generate( builder ) {
  5978. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  5979. const properties = builder.getNodeProperties( this );
  5980. const varying = this.setupVarying( builder );
  5981. if ( properties[ propertyKey ] === undefined ) {
  5982. const type = this.getNodeType( builder );
  5983. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5984. // force node run in vertex stage
  5985. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  5986. properties[ propertyKey ] = propertyName;
  5987. }
  5988. return builder.getPropertyName( varying );
  5989. }
  5990. }
  5991. /**
  5992. * TSL function for creating a varying node.
  5993. *
  5994. * @tsl
  5995. * @function
  5996. * @param {Node} node - The node for which a varying should be created.
  5997. * @param {?string} name - The name of the varying in the shader.
  5998. * @returns {VaryingNode}
  5999. */
  6000. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  6001. /**
  6002. * Computes a node in the vertex stage.
  6003. *
  6004. * @tsl
  6005. * @function
  6006. * @param {Node} node - The node which should be executed in the vertex stage.
  6007. * @returns {VaryingNode}
  6008. */
  6009. const vertexStage = ( node ) => varying( node );
  6010. addMethodChaining( 'toVarying', varying );
  6011. addMethodChaining( 'toVertexStage', vertexStage );
  6012. // Deprecated
  6013. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  6014. warn( 'TSL: .varying() has been renamed to .toVarying().' );
  6015. return varying( ...params );
  6016. } );
  6017. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  6018. warn( 'TSL: .vertexStage() has been renamed to .toVertexStage().' );
  6019. return varying( ...params );
  6020. } );
  6021. /**
  6022. * Converts the given color value from sRGB to linear-sRGB color space.
  6023. *
  6024. * @tsl
  6025. * @function
  6026. * @param {Node<vec3>} color - The sRGB color.
  6027. * @return {Node<vec3>} The linear-sRGB color.
  6028. */
  6029. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6030. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6031. const b = color.mul( 0.0773993808 );
  6032. const factor = color.lessThanEqual( 0.04045 );
  6033. const rgbResult = mix( a, b, factor );
  6034. return rgbResult;
  6035. } ).setLayout( {
  6036. name: 'sRGBTransferEOTF',
  6037. type: 'vec3',
  6038. inputs: [
  6039. { name: 'color', type: 'vec3' }
  6040. ]
  6041. } );
  6042. /**
  6043. * Converts the given color value from linear-sRGB to sRGB color space.
  6044. *
  6045. * @tsl
  6046. * @function
  6047. * @param {Node<vec3>} color - The linear-sRGB color.
  6048. * @return {Node<vec3>} The sRGB color.
  6049. */
  6050. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6051. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6052. const b = color.mul( 12.92 );
  6053. const factor = color.lessThanEqual( 0.0031308 );
  6054. const rgbResult = mix( a, b, factor );
  6055. return rgbResult;
  6056. } ).setLayout( {
  6057. name: 'sRGBTransferOETF',
  6058. type: 'vec3',
  6059. inputs: [
  6060. { name: 'color', type: 'vec3' }
  6061. ]
  6062. } );
  6063. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6064. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6065. /**
  6066. * This node represents a color space conversion. Meaning it converts
  6067. * a color value from a source to a target color space.
  6068. *
  6069. * @augments TempNode
  6070. */
  6071. class ColorSpaceNode extends TempNode {
  6072. static get type() {
  6073. return 'ColorSpaceNode';
  6074. }
  6075. /**
  6076. * Constructs a new color space node.
  6077. *
  6078. * @param {Node} colorNode - Represents the color to convert.
  6079. * @param {string} source - The source color space.
  6080. * @param {string} target - The target color space.
  6081. */
  6082. constructor( colorNode, source, target ) {
  6083. super( 'vec4' );
  6084. /**
  6085. * Represents the color to convert.
  6086. *
  6087. * @type {Node}
  6088. */
  6089. this.colorNode = colorNode;
  6090. /**
  6091. * The source color space.
  6092. *
  6093. * @type {string}
  6094. */
  6095. this.source = source;
  6096. /**
  6097. * The target color space.
  6098. *
  6099. * @type {string}
  6100. */
  6101. this.target = target;
  6102. }
  6103. /**
  6104. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6105. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6106. * color management and renderer.
  6107. *
  6108. * @param {NodeBuilder} builder - The current node builder.
  6109. * @param {string} colorSpace - The color space to resolve.
  6110. * @return {string} The resolved color space.
  6111. */
  6112. resolveColorSpace( builder, colorSpace ) {
  6113. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6114. return ColorManagement.workingColorSpace;
  6115. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6116. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6117. }
  6118. return colorSpace;
  6119. }
  6120. setup( builder ) {
  6121. const { colorNode } = this;
  6122. const source = this.resolveColorSpace( builder, this.source );
  6123. const target = this.resolveColorSpace( builder, this.target );
  6124. let outputNode = colorNode;
  6125. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6126. return outputNode;
  6127. }
  6128. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6129. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6130. }
  6131. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6132. outputNode = vec4(
  6133. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6134. outputNode.a
  6135. );
  6136. }
  6137. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6138. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6139. }
  6140. return outputNode;
  6141. }
  6142. }
  6143. /**
  6144. * TSL function for converting a given color node from the current working color space to the given color space.
  6145. *
  6146. * @tsl
  6147. * @function
  6148. * @param {Node} node - Represents the node to convert.
  6149. * @param {string} targetColorSpace - The target color space.
  6150. * @returns {ColorSpaceNode}
  6151. */
  6152. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6153. /**
  6154. * TSL function for converting a given color node from the given color space to the current working color space.
  6155. *
  6156. * @tsl
  6157. * @function
  6158. * @param {Node} node - Represents the node to convert.
  6159. * @param {string} sourceColorSpace - The source color space.
  6160. * @returns {ColorSpaceNode}
  6161. */
  6162. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6163. /**
  6164. * TSL function for converting a given color node from one color space to another one.
  6165. *
  6166. * @tsl
  6167. * @function
  6168. * @param {Node} node - Represents the node to convert.
  6169. * @param {string} sourceColorSpace - The source color space.
  6170. * @param {string} targetColorSpace - The target color space.
  6171. * @returns {ColorSpaceNode}
  6172. */
  6173. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6174. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6175. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6176. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  6177. /**
  6178. * This class is only relevant if the referenced property is array-like.
  6179. * In this case, `ReferenceElementNode` allows to refer to a specific
  6180. * element inside the data structure via an index.
  6181. *
  6182. * @augments ArrayElementNode
  6183. */
  6184. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6185. static get type() {
  6186. return 'ReferenceElementNode';
  6187. }
  6188. /**
  6189. * Constructs a new reference element node.
  6190. *
  6191. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6192. * @param {Node} indexNode - The index node that defines the element access.
  6193. */
  6194. constructor( referenceNode, indexNode ) {
  6195. super( referenceNode, indexNode );
  6196. /**
  6197. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6198. * property references to the current node.
  6199. *
  6200. * @type {?ReferenceBaseNode}
  6201. * @default null
  6202. */
  6203. this.referenceNode = referenceNode;
  6204. /**
  6205. * This flag can be used for type testing.
  6206. *
  6207. * @type {boolean}
  6208. * @readonly
  6209. * @default true
  6210. */
  6211. this.isReferenceElementNode = true;
  6212. }
  6213. /**
  6214. * This method is overwritten since the node type is inferred from
  6215. * the uniform type of the reference node.
  6216. *
  6217. * @return {string} The node type.
  6218. */
  6219. getNodeType() {
  6220. return this.referenceNode.uniformType;
  6221. }
  6222. generate( builder ) {
  6223. const snippet = super.generate( builder );
  6224. const arrayType = this.referenceNode.getNodeType();
  6225. const elementType = this.getNodeType();
  6226. return builder.format( snippet, arrayType, elementType );
  6227. }
  6228. };
  6229. /**
  6230. * Base class for nodes which establishes a reference to a property of another object.
  6231. * In this way, the value of the node is automatically linked to the value of
  6232. * referenced object. Reference nodes internally represent the linked value
  6233. * as a uniform.
  6234. *
  6235. * @augments Node
  6236. */
  6237. class ReferenceBaseNode extends Node {
  6238. static get type() {
  6239. return 'ReferenceBaseNode';
  6240. }
  6241. /**
  6242. * Constructs a new reference base node.
  6243. *
  6244. * @param {string} property - The name of the property the node refers to.
  6245. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6246. * @param {?Object} [object=null] - The object the property belongs to.
  6247. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6248. */
  6249. constructor( property, uniformType, object = null, count = null ) {
  6250. super();
  6251. /**
  6252. * The name of the property the node refers to.
  6253. *
  6254. * @type {string}
  6255. */
  6256. this.property = property;
  6257. /**
  6258. * The uniform type that should be used to represent the property value.
  6259. *
  6260. * @type {string}
  6261. */
  6262. this.uniformType = uniformType;
  6263. /**
  6264. * The object the property belongs to.
  6265. *
  6266. * @type {?Object}
  6267. * @default null
  6268. */
  6269. this.object = object;
  6270. /**
  6271. * When the linked property is an array, this parameter defines its length.
  6272. *
  6273. * @type {?number}
  6274. * @default null
  6275. */
  6276. this.count = count;
  6277. /**
  6278. * The property name might have dots so nested properties can be referred.
  6279. * The hierarchy of the names is stored inside this array.
  6280. *
  6281. * @type {Array<string>}
  6282. */
  6283. this.properties = property.split( '.' );
  6284. /**
  6285. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6286. * since the final reference might be updated from calling code.
  6287. *
  6288. * @type {?Object}
  6289. * @default null
  6290. */
  6291. this.reference = object;
  6292. /**
  6293. * The uniform node that holds the value of the reference node.
  6294. *
  6295. * @type {UniformNode}
  6296. * @default null
  6297. */
  6298. this.node = null;
  6299. /**
  6300. * The uniform group of the internal uniform.
  6301. *
  6302. * @type {UniformGroupNode}
  6303. * @default null
  6304. */
  6305. this.group = null;
  6306. /**
  6307. * Overwritten since reference nodes are updated per object.
  6308. *
  6309. * @type {string}
  6310. * @default 'object'
  6311. */
  6312. this.updateType = NodeUpdateType.OBJECT;
  6313. }
  6314. /**
  6315. * Sets the uniform group for this reference node.
  6316. *
  6317. * @param {UniformGroupNode} group - The uniform group to set.
  6318. * @return {ReferenceBaseNode} A reference to this node.
  6319. */
  6320. setGroup( group ) {
  6321. this.group = group;
  6322. return this;
  6323. }
  6324. /**
  6325. * When the referred property is array-like, this method can be used
  6326. * to access elements via an index node.
  6327. *
  6328. * @param {IndexNode} indexNode - indexNode.
  6329. * @return {ReferenceElementNode} A reference to an element.
  6330. */
  6331. element( indexNode ) {
  6332. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6333. }
  6334. /**
  6335. * Sets the node type which automatically defines the internal
  6336. * uniform type.
  6337. *
  6338. * @param {string} uniformType - The type to set.
  6339. */
  6340. setNodeType( uniformType ) {
  6341. const node = uniform( null, uniformType );
  6342. if ( this.group !== null ) {
  6343. node.setGroup( this.group );
  6344. }
  6345. this.node = node;
  6346. }
  6347. /**
  6348. * This method is overwritten since the node type is inferred from
  6349. * the type of the reference node.
  6350. *
  6351. * @param {NodeBuilder} builder - The current node builder.
  6352. * @return {string} The node type.
  6353. */
  6354. getNodeType( builder ) {
  6355. if ( this.node === null ) {
  6356. this.updateReference( builder );
  6357. this.updateValue();
  6358. }
  6359. return this.node.getNodeType( builder );
  6360. }
  6361. /**
  6362. * Returns the property value from the given referred object.
  6363. *
  6364. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6365. * @return {any} The value.
  6366. */
  6367. getValueFromReference( object = this.reference ) {
  6368. const { properties } = this;
  6369. let value = object[ properties[ 0 ] ];
  6370. for ( let i = 1; i < properties.length; i ++ ) {
  6371. value = value[ properties[ i ] ];
  6372. }
  6373. return value;
  6374. }
  6375. /**
  6376. * Allows to update the reference based on the given state. The state is only
  6377. * evaluated {@link ReferenceBaseNode#object} is not set.
  6378. *
  6379. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6380. * @return {Object} The updated reference.
  6381. */
  6382. updateReference( state ) {
  6383. this.reference = this.object !== null ? this.object : state.object;
  6384. return this.reference;
  6385. }
  6386. /**
  6387. * The output of the reference node is the internal uniform node.
  6388. *
  6389. * @return {UniformNode} The output node.
  6390. */
  6391. setup() {
  6392. this.updateValue();
  6393. return this.node;
  6394. }
  6395. /**
  6396. * Overwritten to update the internal uniform value.
  6397. *
  6398. * @param {NodeFrame} frame - A reference to the current node frame.
  6399. */
  6400. update( /*frame*/ ) {
  6401. this.updateValue();
  6402. }
  6403. /**
  6404. * Retrieves the value from the referred object property and uses it
  6405. * to updated the internal uniform.
  6406. */
  6407. updateValue() {
  6408. if ( this.node === null ) this.setNodeType( this.uniformType );
  6409. const value = this.getValueFromReference();
  6410. if ( Array.isArray( value ) ) {
  6411. this.node.array = value;
  6412. } else {
  6413. this.node.value = value;
  6414. }
  6415. }
  6416. }
  6417. /**
  6418. * TSL function for creating a reference base node.
  6419. *
  6420. * @tsl
  6421. * @function
  6422. * @param {string} name - The name of the property the node refers to.
  6423. * @param {string} type - The uniform type that should be used to represent the property value.
  6424. * @param {Object} object - The object the property belongs to.
  6425. * @returns {ReferenceBaseNode}
  6426. */
  6427. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6428. /**
  6429. * This node is a special type of reference node which is intended
  6430. * for linking renderer properties with node values.
  6431. * ```js
  6432. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6433. * ```
  6434. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6435. * automatically be updated.
  6436. *
  6437. * @augments ReferenceBaseNode
  6438. */
  6439. class RendererReferenceNode extends ReferenceBaseNode {
  6440. static get type() {
  6441. return 'RendererReferenceNode';
  6442. }
  6443. /**
  6444. * Constructs a new renderer reference node.
  6445. *
  6446. * @param {string} property - The name of the property the node refers to.
  6447. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6448. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6449. * the node refers to the renderer of the current state.
  6450. */
  6451. constructor( property, inputType, renderer = null ) {
  6452. super( property, inputType, renderer );
  6453. /**
  6454. * The renderer the property belongs to. When no renderer is set,
  6455. * the node refers to the renderer of the current state.
  6456. *
  6457. * @type {?Renderer}
  6458. * @default null
  6459. */
  6460. this.renderer = renderer;
  6461. this.setGroup( renderGroup );
  6462. }
  6463. /**
  6464. * Updates the reference based on the given state. The state is only evaluated
  6465. * {@link RendererReferenceNode#renderer} is not set.
  6466. *
  6467. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6468. * @return {Object} The updated reference.
  6469. */
  6470. updateReference( state ) {
  6471. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6472. return this.reference;
  6473. }
  6474. }
  6475. /**
  6476. * TSL function for creating a renderer reference node.
  6477. *
  6478. * @tsl
  6479. * @function
  6480. * @param {string} name - The name of the property the node refers to.
  6481. * @param {string} type - The uniform type that should be used to represent the property value.
  6482. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6483. * the node refers to the renderer of the current state.
  6484. * @returns {RendererReferenceNode}
  6485. */
  6486. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6487. /**
  6488. * This node represents a tone mapping operation.
  6489. *
  6490. * @augments TempNode
  6491. */
  6492. class ToneMappingNode extends TempNode {
  6493. static get type() {
  6494. return 'ToneMappingNode';
  6495. }
  6496. /**
  6497. * Constructs a new tone mapping node.
  6498. *
  6499. * @param {number} toneMapping - The tone mapping type.
  6500. * @param {Node} exposureNode - The tone mapping exposure.
  6501. * @param {Node} [colorNode=null] - The color node to process.
  6502. */
  6503. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6504. super( 'vec3' );
  6505. /**
  6506. * The tone mapping type.
  6507. *
  6508. * @type {number}
  6509. */
  6510. this.toneMapping = toneMapping;
  6511. /**
  6512. * The tone mapping exposure.
  6513. *
  6514. * @type {Node}
  6515. * @default null
  6516. */
  6517. this.exposureNode = exposureNode;
  6518. /**
  6519. * Represents the color to process.
  6520. *
  6521. * @type {?Node}
  6522. * @default null
  6523. */
  6524. this.colorNode = colorNode;
  6525. }
  6526. /**
  6527. * Overwrites the default `customCacheKey()` implementation by including the tone
  6528. * mapping type into the cache key.
  6529. *
  6530. * @return {number} The hash.
  6531. */
  6532. customCacheKey() {
  6533. return hash$1( this.toneMapping );
  6534. }
  6535. setup( builder ) {
  6536. const colorNode = this.colorNode || builder.context.color;
  6537. const toneMapping = this.toneMapping;
  6538. if ( toneMapping === NoToneMapping ) return colorNode;
  6539. let outputNode = null;
  6540. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6541. if ( toneMappingFn !== null ) {
  6542. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6543. } else {
  6544. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6545. outputNode = colorNode;
  6546. }
  6547. return outputNode;
  6548. }
  6549. }
  6550. /**
  6551. * TSL function for creating a tone mapping node.
  6552. *
  6553. * @tsl
  6554. * @function
  6555. * @param {number} mapping - The tone mapping type.
  6556. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6557. * @param {Node<vec3> | Color} color - The color node to process.
  6558. * @returns {ToneMappingNode<vec3>}
  6559. */
  6560. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6561. /**
  6562. * TSL object that represents the global tone mapping exposure of the renderer.
  6563. *
  6564. * @tsl
  6565. * @type {RendererReferenceNode<vec3>}
  6566. */
  6567. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6568. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6569. /**
  6570. * In earlier `three.js` versions it was only possible to define attribute data
  6571. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6572. * on the node level.
  6573. * ```js
  6574. * const geometry = new THREE.PlaneGeometry();
  6575. * const positionAttribute = geometry.getAttribute( 'position' );
  6576. *
  6577. * const colors = [];
  6578. * for ( let i = 0; i < position.count; i ++ ) {
  6579. * colors.push( 1, 0, 0 );
  6580. * }
  6581. *
  6582. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6583. * ```
  6584. * This new approach is especially interesting when geometry data are generated via
  6585. * compute shaders. The below line converts a storage buffer into an attribute node.
  6586. * ```js
  6587. * material.positionNode = positionBuffer.toAttribute();
  6588. * ```
  6589. * @augments InputNode
  6590. */
  6591. class BufferAttributeNode extends InputNode {
  6592. static get type() {
  6593. return 'BufferAttributeNode';
  6594. }
  6595. /**
  6596. * Constructs a new buffer attribute node.
  6597. *
  6598. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6599. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6600. * @param {number} [bufferStride=0] - The buffer stride.
  6601. * @param {number} [bufferOffset=0] - The buffer offset.
  6602. */
  6603. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6604. super( value, bufferType );
  6605. /**
  6606. * This flag can be used for type testing.
  6607. *
  6608. * @type {boolean}
  6609. * @readonly
  6610. * @default true
  6611. */
  6612. this.isBufferNode = true;
  6613. /**
  6614. * The buffer type (e.g. `'vec3'`).
  6615. *
  6616. * @type {?string}
  6617. * @default null
  6618. */
  6619. this.bufferType = bufferType;
  6620. /**
  6621. * The buffer stride.
  6622. *
  6623. * @type {number}
  6624. * @default 0
  6625. */
  6626. this.bufferStride = bufferStride;
  6627. /**
  6628. * The buffer offset.
  6629. *
  6630. * @type {number}
  6631. * @default 0
  6632. */
  6633. this.bufferOffset = bufferOffset;
  6634. /**
  6635. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6636. * if you are planning to update the attribute data per frame.
  6637. *
  6638. * @type {number}
  6639. * @default StaticDrawUsage
  6640. */
  6641. this.usage = StaticDrawUsage;
  6642. /**
  6643. * Whether the attribute is instanced or not.
  6644. *
  6645. * @type {boolean}
  6646. * @default false
  6647. */
  6648. this.instanced = false;
  6649. /**
  6650. * A reference to the buffer attribute.
  6651. *
  6652. * @type {?BufferAttribute}
  6653. * @default null
  6654. */
  6655. this.attribute = null;
  6656. /**
  6657. * `BufferAttributeNode` sets this property to `true` by default.
  6658. *
  6659. * @type {boolean}
  6660. * @default true
  6661. */
  6662. this.global = true;
  6663. if ( value && value.isBufferAttribute === true ) {
  6664. this.attribute = value;
  6665. this.usage = value.usage;
  6666. this.instanced = value.isInstancedBufferAttribute;
  6667. }
  6668. }
  6669. /**
  6670. * This method is overwritten since the attribute data might be shared
  6671. * and thus the hash should be shared as well.
  6672. *
  6673. * @param {NodeBuilder} builder - The current node builder.
  6674. * @return {string} The hash.
  6675. */
  6676. getHash( builder ) {
  6677. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6678. let bufferData = builder.globalCache.getData( this.value );
  6679. if ( bufferData === undefined ) {
  6680. bufferData = {
  6681. node: this
  6682. };
  6683. builder.globalCache.setData( this.value, bufferData );
  6684. }
  6685. return bufferData.node.uuid;
  6686. }
  6687. return this.uuid;
  6688. }
  6689. /**
  6690. * This method is overwritten since the node type is inferred from
  6691. * the buffer attribute.
  6692. *
  6693. * @param {NodeBuilder} builder - The current node builder.
  6694. * @return {string} The node type.
  6695. */
  6696. getNodeType( builder ) {
  6697. if ( this.bufferType === null ) {
  6698. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6699. }
  6700. return this.bufferType;
  6701. }
  6702. /**
  6703. * Depending on which value was passed to the node, `setup()` behaves
  6704. * differently. If no instance of `BufferAttribute` was passed, the method
  6705. * creates an internal attribute and configures it respectively.
  6706. *
  6707. * @param {NodeBuilder} builder - The current node builder.
  6708. */
  6709. setup( builder ) {
  6710. if ( this.attribute !== null ) return;
  6711. const type = this.getNodeType( builder );
  6712. const array = this.value;
  6713. const itemSize = builder.getTypeLength( type );
  6714. const stride = this.bufferStride || itemSize;
  6715. const offset = this.bufferOffset;
  6716. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6717. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6718. buffer.setUsage( this.usage );
  6719. this.attribute = bufferAttribute;
  6720. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6721. }
  6722. /**
  6723. * Generates the code snippet of the buffer attribute node.
  6724. *
  6725. * @param {NodeBuilder} builder - The current node builder.
  6726. * @return {string} The generated code snippet.
  6727. */
  6728. generate( builder ) {
  6729. const nodeType = this.getNodeType( builder );
  6730. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6731. const propertyName = builder.getPropertyName( nodeAttribute );
  6732. let output = null;
  6733. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6734. this.name = propertyName;
  6735. output = propertyName;
  6736. } else {
  6737. const nodeVarying = varying( this );
  6738. output = nodeVarying.build( builder, nodeType );
  6739. }
  6740. return output;
  6741. }
  6742. /**
  6743. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6744. *
  6745. * @param {NodeBuilder} builder - The current node builder.
  6746. * @return {string} The input type.
  6747. */
  6748. getInputType( /*builder*/ ) {
  6749. return 'bufferAttribute';
  6750. }
  6751. /**
  6752. * Sets the `usage` property to the given value.
  6753. *
  6754. * @param {number} value - The usage to set.
  6755. * @return {BufferAttributeNode} A reference to this node.
  6756. */
  6757. setUsage( value ) {
  6758. this.usage = value;
  6759. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6760. this.attribute.usage = value;
  6761. }
  6762. return this;
  6763. }
  6764. /**
  6765. * Sets the `instanced` property to the given value.
  6766. *
  6767. * @param {boolean} value - The value to set.
  6768. * @return {BufferAttributeNode} A reference to this node.
  6769. */
  6770. setInstanced( value ) {
  6771. this.instanced = value;
  6772. return this;
  6773. }
  6774. }
  6775. /**
  6776. * TSL function for creating a buffer attribute node.
  6777. *
  6778. * @tsl
  6779. * @function
  6780. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6781. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6782. * @param {number} [stride=0] - The buffer stride.
  6783. * @param {number} [offset=0] - The buffer offset.
  6784. * @returns {BufferAttributeNode}
  6785. */
  6786. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6787. /**
  6788. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6789. * Use this function if attribute data are updated per frame.
  6790. *
  6791. * @tsl
  6792. * @function
  6793. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6794. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6795. * @param {number} [stride=0] - The buffer stride.
  6796. * @param {number} [offset=0] - The buffer offset.
  6797. * @returns {BufferAttributeNode}
  6798. */
  6799. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6800. /**
  6801. * TSL function for creating a buffer attribute node but with enabled instancing
  6802. *
  6803. * @tsl
  6804. * @function
  6805. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6806. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6807. * @param {number} [stride=0] - The buffer stride.
  6808. * @param {number} [offset=0] - The buffer offset.
  6809. * @returns {BufferAttributeNode}
  6810. */
  6811. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6812. /**
  6813. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6814. *
  6815. * @tsl
  6816. * @function
  6817. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6818. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6819. * @param {number} [stride=0] - The buffer stride.
  6820. * @param {number} [offset=0] - The buffer offset.
  6821. * @returns {BufferAttributeNode}
  6822. */
  6823. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6824. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6825. /**
  6826. * TODO
  6827. *
  6828. * @augments Node
  6829. */
  6830. class ComputeNode extends Node {
  6831. static get type() {
  6832. return 'ComputeNode';
  6833. }
  6834. /**
  6835. * Constructs a new compute node.
  6836. *
  6837. * @param {Node} computeNode - TODO
  6838. * @param {Array<number>} workgroupSize - TODO.
  6839. */
  6840. constructor( computeNode, workgroupSize ) {
  6841. super( 'void' );
  6842. /**
  6843. * This flag can be used for type testing.
  6844. *
  6845. * @type {boolean}
  6846. * @readonly
  6847. * @default true
  6848. */
  6849. this.isComputeNode = true;
  6850. /**
  6851. * TODO
  6852. *
  6853. * @type {Node}
  6854. */
  6855. this.computeNode = computeNode;
  6856. /**
  6857. * TODO
  6858. *
  6859. * @type {Array<number>}
  6860. * @default [ 64 ]
  6861. */
  6862. this.workgroupSize = workgroupSize;
  6863. /**
  6864. * TODO
  6865. *
  6866. * @type {number}
  6867. */
  6868. this.count = null;
  6869. /**
  6870. * TODO
  6871. *
  6872. * @type {number}
  6873. */
  6874. this.version = 1;
  6875. /**
  6876. * The name or label of the uniform.
  6877. *
  6878. * @type {string}
  6879. * @default ''
  6880. */
  6881. this.name = '';
  6882. /**
  6883. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6884. * is executed once per object by default.
  6885. *
  6886. * @type {string}
  6887. * @default 'object'
  6888. */
  6889. this.updateBeforeType = NodeUpdateType.OBJECT;
  6890. /**
  6891. * TODO
  6892. *
  6893. * @type {?Function}
  6894. */
  6895. this.onInitFunction = null;
  6896. }
  6897. setCount( count ) {
  6898. this.count = count;
  6899. return this;
  6900. }
  6901. getCount() {
  6902. return this.count;
  6903. }
  6904. /**
  6905. * Executes the `dispose` event for this node.
  6906. */
  6907. dispose() {
  6908. this.dispatchEvent( { type: 'dispose' } );
  6909. }
  6910. /**
  6911. * Sets the {@link ComputeNode#name} property.
  6912. *
  6913. * @param {string} name - The name of the uniform.
  6914. * @return {ComputeNode} A reference to this node.
  6915. */
  6916. setName( name ) {
  6917. this.name = name;
  6918. return this;
  6919. }
  6920. /**
  6921. * Sets the {@link ComputeNode#name} property.
  6922. *
  6923. * @deprecated
  6924. * @param {string} name - The name of the uniform.
  6925. * @return {ComputeNode} A reference to this node.
  6926. */
  6927. label( name ) {
  6928. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  6929. return this.setName( name );
  6930. }
  6931. /**
  6932. * TODO
  6933. *
  6934. * @param {Function} callback - TODO.
  6935. * @return {ComputeNode} A reference to this node.
  6936. */
  6937. onInit( callback ) {
  6938. this.onInitFunction = callback;
  6939. return this;
  6940. }
  6941. /**
  6942. * The method execute the compute for this node.
  6943. *
  6944. * @param {NodeFrame} frame - A reference to the current node frame.
  6945. */
  6946. updateBefore( { renderer } ) {
  6947. renderer.compute( this );
  6948. }
  6949. setup( builder ) {
  6950. const result = this.computeNode.build( builder );
  6951. if ( result ) {
  6952. const properties = builder.getNodeProperties( this );
  6953. properties.outputComputeNode = result.outputNode;
  6954. result.outputNode = null;
  6955. }
  6956. return result;
  6957. }
  6958. generate( builder, output ) {
  6959. const { shaderStage } = builder;
  6960. if ( shaderStage === 'compute' ) {
  6961. const snippet = this.computeNode.build( builder, 'void' );
  6962. if ( snippet !== '' ) {
  6963. builder.addLineFlowCode( snippet, this );
  6964. }
  6965. } else {
  6966. const properties = builder.getNodeProperties( this );
  6967. const outputComputeNode = properties.outputComputeNode;
  6968. if ( outputComputeNode ) {
  6969. return outputComputeNode.build( builder, output );
  6970. }
  6971. }
  6972. }
  6973. }
  6974. /**
  6975. * TSL function for creating a compute kernel node.
  6976. *
  6977. * @tsl
  6978. * @function
  6979. * @param {Node} node - TODO
  6980. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6981. * @returns {AtomicFunctionNode}
  6982. */
  6983. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  6984. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  6985. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  6986. }
  6987. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  6988. const val = workgroupSize[ i ];
  6989. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  6990. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  6991. }
  6992. }
  6993. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  6994. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  6995. //
  6996. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  6997. };
  6998. /**
  6999. * TSL function for creating a compute node.
  7000. *
  7001. * @tsl
  7002. * @function
  7003. * @param {Node} node - TODO
  7004. * @param {number} count - TODO.
  7005. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7006. * @returns {AtomicFunctionNode}
  7007. */
  7008. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  7009. addMethodChaining( 'compute', compute );
  7010. addMethodChaining( 'computeKernel', computeKernel );
  7011. /**
  7012. * This node can be used as a cache management component for another node.
  7013. * Caching is in general used by default in {@link NodeBuilder} but this node
  7014. * allows the usage of a shared parent cache during the build process.
  7015. *
  7016. * @augments Node
  7017. */
  7018. class IsolateNode extends Node {
  7019. static get type() {
  7020. return 'IsolateNode';
  7021. }
  7022. /**
  7023. * Constructs a new cache node.
  7024. *
  7025. * @param {Node} node - The node that should be cached.
  7026. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7027. */
  7028. constructor( node, parent = true ) {
  7029. super();
  7030. /**
  7031. * The node that should be cached.
  7032. *
  7033. * @type {Node}
  7034. */
  7035. this.node = node;
  7036. /**
  7037. * Whether this node refers to a shared parent cache or not.
  7038. *
  7039. * @type {boolean}
  7040. * @default true
  7041. */
  7042. this.parent = parent;
  7043. /**
  7044. * This flag can be used for type testing.
  7045. *
  7046. * @type {boolean}
  7047. * @readonly
  7048. * @default true
  7049. */
  7050. this.isIsolateNode = true;
  7051. }
  7052. getNodeType( builder ) {
  7053. const previousCache = builder.getCache();
  7054. const cache = builder.getCacheFromNode( this, this.parent );
  7055. builder.setCache( cache );
  7056. const nodeType = this.node.getNodeType( builder );
  7057. builder.setCache( previousCache );
  7058. return nodeType;
  7059. }
  7060. build( builder, ...params ) {
  7061. const previousCache = builder.getCache();
  7062. const cache = builder.getCacheFromNode( this, this.parent );
  7063. builder.setCache( cache );
  7064. const data = this.node.build( builder, ...params );
  7065. builder.setCache( previousCache );
  7066. return data;
  7067. }
  7068. setParent( parent ) {
  7069. this.parent = parent;
  7070. return this;
  7071. }
  7072. getParent() {
  7073. return this.parent;
  7074. }
  7075. }
  7076. /**
  7077. * TSL function for creating a cache node.
  7078. *
  7079. * @tsl
  7080. * @function
  7081. * @param {Node} node - The node that should be cached.
  7082. * @returns {IsolateNode}
  7083. */
  7084. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7085. /**
  7086. * TSL function for creating a cache node.
  7087. *
  7088. * @tsl
  7089. * @function
  7090. * @deprecated
  7091. * @param {Node} node - The node that should be cached.
  7092. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7093. * @returns {IsolateNode}
  7094. */
  7095. function cache( node, parent = true ) {
  7096. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7097. return isolate( node ).setParent( parent );
  7098. }
  7099. addMethodChaining( 'cache', cache );
  7100. addMethodChaining( 'isolate', isolate );
  7101. /**
  7102. * The class generates the code of a given node but returns another node in the output.
  7103. * This can be used to call a method or node that does not return a value, i.e.
  7104. * type `void` on an input where returning a value is required. Example:
  7105. *
  7106. * ```js
  7107. * material.colorNode = myColor.bypass( runVoidFn() )
  7108. *```
  7109. *
  7110. * @augments Node
  7111. */
  7112. class BypassNode extends Node {
  7113. static get type() {
  7114. return 'BypassNode';
  7115. }
  7116. /**
  7117. * Constructs a new bypass node.
  7118. *
  7119. * @param {Node} outputNode - The output node.
  7120. * @param {Node} callNode - The call node.
  7121. */
  7122. constructor( outputNode, callNode ) {
  7123. super();
  7124. /**
  7125. * This flag can be used for type testing.
  7126. *
  7127. * @type {boolean}
  7128. * @readonly
  7129. * @default true
  7130. */
  7131. this.isBypassNode = true;
  7132. /**
  7133. * The output node.
  7134. *
  7135. * @type {Node}
  7136. */
  7137. this.outputNode = outputNode;
  7138. /**
  7139. * The call node.
  7140. *
  7141. * @type {Node}
  7142. */
  7143. this.callNode = callNode;
  7144. }
  7145. getNodeType( builder ) {
  7146. return this.outputNode.getNodeType( builder );
  7147. }
  7148. generate( builder ) {
  7149. const snippet = this.callNode.build( builder, 'void' );
  7150. if ( snippet !== '' ) {
  7151. builder.addLineFlowCode( snippet, this );
  7152. }
  7153. return this.outputNode.build( builder );
  7154. }
  7155. }
  7156. /**
  7157. * TSL function for creating a bypass node.
  7158. *
  7159. * @tsl
  7160. * @function
  7161. * @param {Node} outputNode - The output node.
  7162. * @param {Node} callNode - The call node.
  7163. * @returns {BypassNode}
  7164. */
  7165. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7166. addMethodChaining( 'bypass', bypass );
  7167. /**
  7168. * This node allows to remap a node value from one range into another. E.g a value of
  7169. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7170. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7171. *
  7172. * @augments Node
  7173. */
  7174. class RemapNode extends Node {
  7175. static get type() {
  7176. return 'RemapNode';
  7177. }
  7178. /**
  7179. * Constructs a new remap node.
  7180. *
  7181. * @param {Node} node - The node that should be remapped.
  7182. * @param {Node} inLowNode - The source or current lower bound of the range.
  7183. * @param {Node} inHighNode - The source or current upper bound of the range.
  7184. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7185. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7186. */
  7187. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7188. super();
  7189. /**
  7190. * The node that should be remapped.
  7191. *
  7192. * @type {Node}
  7193. */
  7194. this.node = node;
  7195. /**
  7196. * The source or current lower bound of the range.
  7197. *
  7198. * @type {Node}
  7199. */
  7200. this.inLowNode = inLowNode;
  7201. /**
  7202. * The source or current upper bound of the range.
  7203. *
  7204. * @type {Node}
  7205. */
  7206. this.inHighNode = inHighNode;
  7207. /**
  7208. * The target lower bound of the range.
  7209. *
  7210. * @type {Node}
  7211. * @default float(0)
  7212. */
  7213. this.outLowNode = outLowNode;
  7214. /**
  7215. * The target upper bound of the range.
  7216. *
  7217. * @type {Node}
  7218. * @default float(1)
  7219. */
  7220. this.outHighNode = outHighNode;
  7221. /**
  7222. * Whether the node value should be clamped before
  7223. * remapping it to the target range.
  7224. *
  7225. * @type {boolean}
  7226. * @default true
  7227. */
  7228. this.doClamp = true;
  7229. }
  7230. setup() {
  7231. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7232. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7233. if ( doClamp === true ) t = t.clamp();
  7234. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7235. }
  7236. }
  7237. /**
  7238. * TSL function for creating a remap node.
  7239. *
  7240. * @tsl
  7241. * @function
  7242. * @param {Node} node - The node that should be remapped.
  7243. * @param {Node} inLowNode - The source or current lower bound of the range.
  7244. * @param {Node} inHighNode - The source or current upper bound of the range.
  7245. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7246. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7247. * @returns {RemapNode}
  7248. */
  7249. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7250. /**
  7251. * TSL function for creating a remap node, but with enabled clamping.
  7252. *
  7253. * @tsl
  7254. * @function
  7255. * @param {Node} node - The node that should be remapped.
  7256. * @param {Node} inLowNode - The source or current lower bound of the range.
  7257. * @param {Node} inHighNode - The source or current upper bound of the range.
  7258. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7259. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7260. * @returns {RemapNode}
  7261. */
  7262. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7263. addMethodChaining( 'remap', remap );
  7264. addMethodChaining( 'remapClamp', remapClamp );
  7265. /**
  7266. * This class can be used to implement basic expressions in shader code.
  7267. * Basic examples for that are `return`, `continue` or `discard` statements.
  7268. *
  7269. * @augments Node
  7270. */
  7271. class ExpressionNode extends Node {
  7272. static get type() {
  7273. return 'ExpressionNode';
  7274. }
  7275. /**
  7276. * Constructs a new expression node.
  7277. *
  7278. * @param {string} [snippet=''] - The native code snippet.
  7279. * @param {string} [nodeType='void'] - The node type.
  7280. */
  7281. constructor( snippet = '', nodeType = 'void' ) {
  7282. super( nodeType );
  7283. /**
  7284. * The native code snippet.
  7285. *
  7286. * @type {string}
  7287. * @default ''
  7288. */
  7289. this.snippet = snippet;
  7290. }
  7291. generate( builder, output ) {
  7292. const type = this.getNodeType( builder );
  7293. const snippet = this.snippet;
  7294. if ( type === 'void' ) {
  7295. builder.addLineFlowCode( snippet, this );
  7296. } else {
  7297. return builder.format( snippet, type, output );
  7298. }
  7299. }
  7300. }
  7301. /**
  7302. * TSL function for creating an expression node.
  7303. *
  7304. * @tsl
  7305. * @function
  7306. * @param {string} [snippet] - The native code snippet.
  7307. * @param {?string} [nodeType='void'] - The node type.
  7308. * @returns {ExpressionNode}
  7309. */
  7310. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7311. /**
  7312. * Represents a `discard` shader operation in TSL.
  7313. *
  7314. * @tsl
  7315. * @function
  7316. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7317. * @return {Node} The `discard` expression.
  7318. */
  7319. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7320. /**
  7321. * Represents a `return` shader operation in TSL.
  7322. *
  7323. * @tsl
  7324. * @function
  7325. * @return {ExpressionNode} The `return` expression.
  7326. */
  7327. const Return = () => expression( 'return' ).toStack();
  7328. addMethodChaining( 'discard', Discard );
  7329. /**
  7330. * Normally, tone mapping and color conversion happens automatically
  7331. * before outputting pixel too the default (screen) framebuffer. In certain
  7332. * post processing setups this happens to late because certain effects
  7333. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7334. * to apply tone mapping and color space conversion at an arbitrary point
  7335. * in the effect chain.
  7336. *
  7337. * When applying tone mapping and color space conversion manually with this node,
  7338. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7339. *
  7340. * ```js
  7341. * const postProcessing = new PostProcessing( renderer );
  7342. * postProcessing.outputColorTransform = false;
  7343. *
  7344. * const scenePass = pass( scene, camera );
  7345. * const outputPass = renderOutput( scenePass );
  7346. *
  7347. * postProcessing.outputNode = outputPass;
  7348. * ```
  7349. *
  7350. * @augments TempNode
  7351. */
  7352. class RenderOutputNode extends TempNode {
  7353. static get type() {
  7354. return 'RenderOutputNode';
  7355. }
  7356. /**
  7357. * Constructs a new render output node.
  7358. *
  7359. * @param {Node} colorNode - The color node to process.
  7360. * @param {?number} toneMapping - The tone mapping type.
  7361. * @param {?string} outputColorSpace - The output color space.
  7362. */
  7363. constructor( colorNode, toneMapping, outputColorSpace ) {
  7364. super( 'vec4' );
  7365. /**
  7366. * The color node to process.
  7367. *
  7368. * @type {Node}
  7369. */
  7370. this.colorNode = colorNode;
  7371. /**
  7372. * The tone mapping type.
  7373. *
  7374. * @type {?number}
  7375. */
  7376. this.toneMapping = toneMapping;
  7377. /**
  7378. * The output color space.
  7379. *
  7380. * @type {?string}
  7381. */
  7382. this.outputColorSpace = outputColorSpace;
  7383. /**
  7384. * This flag can be used for type testing.
  7385. *
  7386. * @type {boolean}
  7387. * @readonly
  7388. * @default true
  7389. */
  7390. this.isRenderOutputNode = true;
  7391. }
  7392. setup( { context } ) {
  7393. let outputNode = this.colorNode || context.color;
  7394. // tone mapping
  7395. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  7396. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7397. if ( toneMapping !== NoToneMapping ) {
  7398. outputNode = outputNode.toneMapping( toneMapping );
  7399. }
  7400. // working to output color space
  7401. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7402. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7403. }
  7404. return outputNode;
  7405. }
  7406. }
  7407. /**
  7408. * TSL function for creating a posterize node.
  7409. *
  7410. * @tsl
  7411. * @function
  7412. * @param {Node} color - The color node to process.
  7413. * @param {?number} [toneMapping=null] - The tone mapping type.
  7414. * @param {?string} [outputColorSpace=null] - The output color space.
  7415. * @returns {RenderOutputNode}
  7416. */
  7417. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7418. addMethodChaining( 'renderOutput', renderOutput );
  7419. class DebugNode extends TempNode {
  7420. static get type() {
  7421. return 'DebugNode';
  7422. }
  7423. constructor( node, callback = null ) {
  7424. super();
  7425. this.node = node;
  7426. this.callback = callback;
  7427. }
  7428. getNodeType( builder ) {
  7429. return this.node.getNodeType( builder );
  7430. }
  7431. setup( builder ) {
  7432. return this.node.build( builder );
  7433. }
  7434. analyze( builder ) {
  7435. return this.node.build( builder );
  7436. }
  7437. generate( builder ) {
  7438. const callback = this.callback;
  7439. const snippet = this.node.build( builder );
  7440. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7441. const border = '-'.repeat( title.length );
  7442. let code = '';
  7443. code += '// #' + title + '#\n';
  7444. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7445. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7446. code += '// #' + border + '#\n';
  7447. if ( callback !== null ) {
  7448. callback( builder, code );
  7449. } else {
  7450. log$1( code );
  7451. }
  7452. return snippet;
  7453. }
  7454. }
  7455. /**
  7456. * TSL function for creating a debug node.
  7457. *
  7458. * @tsl
  7459. * @function
  7460. * @param {Node} node - The node to debug.
  7461. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7462. * @returns {DebugNode}
  7463. */
  7464. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7465. addMethodChaining( 'debug', debug );
  7466. /**
  7467. * InspectorBase is the base class for all inspectors.
  7468. *
  7469. * @class InspectorBase
  7470. */
  7471. class InspectorBase {
  7472. /**
  7473. * Creates a new InspectorBase.
  7474. */
  7475. constructor() {
  7476. /**
  7477. * The renderer associated with this inspector.
  7478. *
  7479. * @type {WebGLRenderer}
  7480. * @private
  7481. */
  7482. this._renderer = null;
  7483. /**
  7484. * The current frame being processed.
  7485. *
  7486. * @type {Object}
  7487. */
  7488. this.currentFrame = null;
  7489. }
  7490. /**
  7491. * Returns the node frame for the current renderer.
  7492. *
  7493. * @return {Object} The node frame.
  7494. */
  7495. get nodeFrame() {
  7496. return this._renderer._nodes.nodeFrame;
  7497. }
  7498. /**
  7499. * Sets the renderer for this inspector.
  7500. *
  7501. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  7502. * @return {InspectorBase} This inspector instance.
  7503. */
  7504. setRenderer( renderer ) {
  7505. this._renderer = renderer;
  7506. return this;
  7507. }
  7508. /**
  7509. * Returns the renderer associated with this inspector.
  7510. *
  7511. * @return {WebGLRenderer} The associated renderer.
  7512. */
  7513. getRenderer() {
  7514. return this._renderer;
  7515. }
  7516. /**
  7517. * Initializes the inspector.
  7518. */
  7519. init() { }
  7520. /**
  7521. * Called when a frame begins.
  7522. */
  7523. begin() { }
  7524. /**
  7525. * Called when a frame ends.
  7526. */
  7527. finish() { }
  7528. /**
  7529. * Inspects a node.
  7530. *
  7531. * @param {Node} node - The node to inspect.
  7532. */
  7533. inspect( /*node*/ ) { }
  7534. /**
  7535. * When a compute operation is performed.
  7536. *
  7537. * @param {ComputeNode} computeNode - The compute node being executed.
  7538. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  7539. */
  7540. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  7541. /**
  7542. * Called when a compute operation begins.
  7543. *
  7544. * @param {string} uid - A unique identifier for the render context.
  7545. * @param {ComputeNode} computeNode - The compute node being executed.
  7546. */
  7547. beginCompute( /*uid, computeNode*/ ) { }
  7548. /**
  7549. * Called when a compute operation ends.
  7550. *
  7551. * @param {string} uid - A unique identifier for the render context.
  7552. * @param {ComputeNode} computeNode - The compute node being executed.
  7553. */
  7554. finishCompute( /*uid*/ ) { }
  7555. /**
  7556. * Called when a render operation begins.
  7557. *
  7558. * @param {string} uid - A unique identifier for the render context.
  7559. * @param {Scene} scene - The scene being rendered.
  7560. * @param {Camera} camera - The camera being used for rendering.
  7561. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  7562. */
  7563. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  7564. /**
  7565. * Called when an animation loop ends.
  7566. *
  7567. * @param {string} uid - A unique identifier for the render context.
  7568. */
  7569. finishRender( /*uid*/ ) { }
  7570. /**
  7571. * Called when a texture copy operation is performed.
  7572. *
  7573. * @param {Texture} srcTexture - The source texture.
  7574. * @param {Texture} dstTexture - The destination texture.
  7575. */
  7576. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  7577. /**
  7578. * Called when a framebuffer copy operation is performed.
  7579. *
  7580. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  7581. */
  7582. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  7583. }
  7584. /**
  7585. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  7586. * It can be used to debug or analyze node outputs in the rendering pipeline.
  7587. *
  7588. * @augments Node
  7589. */
  7590. class InspectorNode extends Node {
  7591. /**
  7592. * Returns the type of the node.
  7593. *
  7594. * @returns {string}
  7595. */
  7596. static get type() {
  7597. return 'InspectorNode';
  7598. }
  7599. /**
  7600. * Creates an InspectorNode.
  7601. *
  7602. * @param {Node} node - The node to inspect.
  7603. * @param {string} [name=''] - Optional name for the inspector node.
  7604. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7605. */
  7606. constructor( node, name = '', callback = null ) {
  7607. super();
  7608. this.node = node;
  7609. this.name = name;
  7610. this.callback = callback;
  7611. this.updateType = NodeUpdateType.FRAME;
  7612. this.isInspectorNode = true;
  7613. }
  7614. /**
  7615. * Returns the name of the inspector node.
  7616. *
  7617. * @returns {string}
  7618. */
  7619. getName() {
  7620. return this.name || this.node.name;
  7621. }
  7622. /**
  7623. * Updates the inspector node, allowing inspection of the wrapped node.
  7624. *
  7625. * @param {NodeFrame} frame - A reference to the current node frame.
  7626. */
  7627. update( frame ) {
  7628. frame.renderer.inspector.inspect( this );
  7629. }
  7630. /**
  7631. * Returns the type of the wrapped node.
  7632. *
  7633. * @param {NodeBuilder} builder - The node builder.
  7634. * @returns {string}
  7635. */
  7636. getNodeType( builder ) {
  7637. return this.node.getNodeType( builder );
  7638. }
  7639. /**
  7640. * Sets up the inspector node.
  7641. *
  7642. * @param {NodeBuilder} builder - The node builder.
  7643. * @returns {Node} The setup node.
  7644. */
  7645. setup( builder ) {
  7646. let node = this.node;
  7647. if ( builder.context.inspector === true && this.callback !== null ) {
  7648. node = this.callback( node );
  7649. }
  7650. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  7651. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  7652. }
  7653. return node;
  7654. }
  7655. }
  7656. /**
  7657. * Creates an inspector node to wrap around a given node for inspection purposes.
  7658. *
  7659. * @tsl
  7660. * @param {Node} node - The node to inspect.
  7661. * @param {string} [name=''] - Optional name for the inspector node.
  7662. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7663. * @returns {Node} The inspector node.
  7664. */
  7665. function inspector( node, name = '', callback = null ) {
  7666. node = nodeObject( node );
  7667. return node.before( new InspectorNode( node, name, callback ) );
  7668. }
  7669. addMethodChaining( 'toInspector', inspector );
  7670. function addNodeElement( name/*, nodeElement*/ ) {
  7671. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7672. }
  7673. /**
  7674. * Base class for representing shader attributes as nodes.
  7675. *
  7676. * @augments Node
  7677. */
  7678. class AttributeNode extends Node {
  7679. static get type() {
  7680. return 'AttributeNode';
  7681. }
  7682. /**
  7683. * Constructs a new attribute node.
  7684. *
  7685. * @param {string} attributeName - The name of the attribute.
  7686. * @param {?string} nodeType - The node type.
  7687. */
  7688. constructor( attributeName, nodeType = null ) {
  7689. super( nodeType );
  7690. /**
  7691. * `AttributeNode` sets this property to `true` by default.
  7692. *
  7693. * @type {boolean}
  7694. * @default true
  7695. */
  7696. this.global = true;
  7697. this._attributeName = attributeName;
  7698. }
  7699. getHash( builder ) {
  7700. return this.getAttributeName( builder );
  7701. }
  7702. getNodeType( builder ) {
  7703. let nodeType = this.nodeType;
  7704. if ( nodeType === null ) {
  7705. const attributeName = this.getAttributeName( builder );
  7706. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7707. const attribute = builder.geometry.getAttribute( attributeName );
  7708. nodeType = builder.getTypeFromAttribute( attribute );
  7709. } else {
  7710. nodeType = 'float';
  7711. }
  7712. }
  7713. return nodeType;
  7714. }
  7715. /**
  7716. * Sets the attribute name to the given value. The method can be
  7717. * overwritten in derived classes if the final name must be computed
  7718. * analytically.
  7719. *
  7720. * @param {string} attributeName - The name of the attribute.
  7721. * @return {AttributeNode} A reference to this node.
  7722. */
  7723. setAttributeName( attributeName ) {
  7724. this._attributeName = attributeName;
  7725. return this;
  7726. }
  7727. /**
  7728. * Returns the attribute name of this node. The method can be
  7729. * overwritten in derived classes if the final name must be computed
  7730. * analytically.
  7731. *
  7732. * @param {NodeBuilder} builder - The current node builder.
  7733. * @return {string} The attribute name.
  7734. */
  7735. getAttributeName( /*builder*/ ) {
  7736. return this._attributeName;
  7737. }
  7738. generate( builder ) {
  7739. const attributeName = this.getAttributeName( builder );
  7740. const nodeType = this.getNodeType( builder );
  7741. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7742. if ( geometryAttribute === true ) {
  7743. const attribute = builder.geometry.getAttribute( attributeName );
  7744. const attributeType = builder.getTypeFromAttribute( attribute );
  7745. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7746. if ( builder.shaderStage === 'vertex' ) {
  7747. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7748. } else {
  7749. const nodeVarying = varying( this );
  7750. return nodeVarying.build( builder, nodeType );
  7751. }
  7752. } else {
  7753. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7754. return builder.generateConst( nodeType );
  7755. }
  7756. }
  7757. serialize( data ) {
  7758. super.serialize( data );
  7759. data.global = this.global;
  7760. data._attributeName = this._attributeName;
  7761. }
  7762. deserialize( data ) {
  7763. super.deserialize( data );
  7764. this.global = data.global;
  7765. this._attributeName = data._attributeName;
  7766. }
  7767. }
  7768. /**
  7769. * TSL function for creating an attribute node.
  7770. *
  7771. * @tsl
  7772. * @function
  7773. * @param {string} name - The name of the attribute.
  7774. * @param {?string} [nodeType=null] - The node type.
  7775. * @returns {AttributeNode}
  7776. */
  7777. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7778. /**
  7779. * TSL function for creating an uv attribute node with the given index.
  7780. *
  7781. * @tsl
  7782. * @function
  7783. * @param {number} [index=0] - The uv index.
  7784. * @return {AttributeNode<vec2>} The uv attribute node.
  7785. */
  7786. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7787. /**
  7788. * A node that represents the dimensions of a texture. The texture size is
  7789. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7790. * or `textureSize()`.
  7791. *
  7792. * @augments Node
  7793. */
  7794. class TextureSizeNode extends Node {
  7795. static get type() {
  7796. return 'TextureSizeNode';
  7797. }
  7798. /**
  7799. * Constructs a new texture size node.
  7800. *
  7801. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7802. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7803. */
  7804. constructor( textureNode, levelNode = null ) {
  7805. super( 'uvec2' );
  7806. /**
  7807. * This flag can be used for type testing.
  7808. *
  7809. * @type {boolean}
  7810. * @readonly
  7811. * @default true
  7812. */
  7813. this.isTextureSizeNode = true;
  7814. /**
  7815. * A texture node which size should be retrieved.
  7816. *
  7817. * @type {TextureNode}
  7818. */
  7819. this.textureNode = textureNode;
  7820. /**
  7821. * A level node which defines the requested mip.
  7822. *
  7823. * @type {Node<int>}
  7824. * @default null
  7825. */
  7826. this.levelNode = levelNode;
  7827. }
  7828. generate( builder, output ) {
  7829. const textureProperty = this.textureNode.build( builder, 'property' );
  7830. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7831. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7832. }
  7833. }
  7834. /**
  7835. * TSL function for creating a texture size node.
  7836. *
  7837. * @tsl
  7838. * @function
  7839. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7840. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7841. * @returns {TextureSizeNode}
  7842. */
  7843. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7844. /**
  7845. * A special type of uniform node that computes the
  7846. * maximum mipmap level for a given texture node.
  7847. *
  7848. * ```js
  7849. * const level = maxMipLevel( textureNode );
  7850. * ```
  7851. *
  7852. * @augments UniformNode
  7853. */
  7854. class MaxMipLevelNode extends UniformNode {
  7855. static get type() {
  7856. return 'MaxMipLevelNode';
  7857. }
  7858. /**
  7859. * Constructs a new max mip level node.
  7860. *
  7861. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7862. */
  7863. constructor( textureNode ) {
  7864. super( 0 );
  7865. /**
  7866. * The texture node to compute the max mip level for.
  7867. *
  7868. * @private
  7869. * @type {TextureNode}
  7870. */
  7871. this._textureNode = textureNode;
  7872. /**
  7873. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7874. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7875. *
  7876. * @type {string}
  7877. * @default 'frame'
  7878. */
  7879. this.updateType = NodeUpdateType.FRAME;
  7880. }
  7881. /**
  7882. * The texture node to compute the max mip level for.
  7883. *
  7884. * @readonly
  7885. * @type {TextureNode}
  7886. */
  7887. get textureNode() {
  7888. return this._textureNode;
  7889. }
  7890. /**
  7891. * The texture.
  7892. *
  7893. * @readonly
  7894. * @type {Texture}
  7895. */
  7896. get texture() {
  7897. return this._textureNode.value;
  7898. }
  7899. update() {
  7900. const texture = this.texture;
  7901. const images = texture.images;
  7902. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7903. if ( image && image.width !== undefined ) {
  7904. const { width, height } = image;
  7905. this.value = Math.log2( Math.max( width, height ) );
  7906. }
  7907. }
  7908. }
  7909. /**
  7910. * TSL function for creating a max mip level node.
  7911. *
  7912. * @tsl
  7913. * @function
  7914. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7915. * @returns {MaxMipLevelNode}
  7916. */
  7917. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7918. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  7919. /**
  7920. * This type of uniform node represents a 2D texture.
  7921. *
  7922. * @augments UniformNode
  7923. */
  7924. class TextureNode extends UniformNode {
  7925. static get type() {
  7926. return 'TextureNode';
  7927. }
  7928. /**
  7929. * Constructs a new texture node.
  7930. *
  7931. * @param {Texture} [value=EmptyTexture] - The texture.
  7932. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7933. * @param {?Node<int>} [levelNode=null] - The level node.
  7934. * @param {?Node<float>} [biasNode=null] - The bias node.
  7935. */
  7936. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  7937. super( value );
  7938. /**
  7939. * This flag can be used for type testing.
  7940. *
  7941. * @type {boolean}
  7942. * @readonly
  7943. * @default true
  7944. */
  7945. this.isTextureNode = true;
  7946. /**
  7947. * Represents the texture coordinates.
  7948. *
  7949. * @type {?Node<vec2|vec3>}
  7950. * @default null
  7951. */
  7952. this.uvNode = uvNode;
  7953. /**
  7954. * Represents the mip level that should be selected.
  7955. *
  7956. * @type {?Node<int>}
  7957. * @default null
  7958. */
  7959. this.levelNode = levelNode;
  7960. /**
  7961. * Represents the bias to be applied during level-of-detail computation.
  7962. *
  7963. * @type {?Node<float>}
  7964. * @default null
  7965. */
  7966. this.biasNode = biasNode;
  7967. /**
  7968. * Represents a reference value a texture sample is compared to.
  7969. *
  7970. * @type {?Node<float>}
  7971. * @default null
  7972. */
  7973. this.compareNode = null;
  7974. /**
  7975. * When using texture arrays, the depth node defines the layer to select.
  7976. *
  7977. * @type {?Node<int>}
  7978. * @default null
  7979. */
  7980. this.depthNode = null;
  7981. /**
  7982. * When defined, a texture is sampled using explicit gradients.
  7983. *
  7984. * @type {?Array<Node<vec2>>}
  7985. * @default null
  7986. */
  7987. this.gradNode = null;
  7988. /**
  7989. * Represents the optional texel offset applied to the unnormalized texture
  7990. * coordinate before sampling the texture.
  7991. *
  7992. * @type {?Node<ivec2|ivec3>}
  7993. * @default null
  7994. */
  7995. this.offsetNode = null;
  7996. /**
  7997. * Whether texture values should be sampled or fetched.
  7998. *
  7999. * @type {boolean}
  8000. * @default true
  8001. */
  8002. this.sampler = true;
  8003. /**
  8004. * Whether the uv transformation matrix should be
  8005. * automatically updated or not. Use `setUpdateMatrix()`
  8006. * if you want to change the value of the property.
  8007. *
  8008. * @type {boolean}
  8009. * @default false
  8010. */
  8011. this.updateMatrix = false;
  8012. /**
  8013. * By default the `update()` method is not executed. Depending on
  8014. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8015. * is executed per object.
  8016. *
  8017. * @type {string}
  8018. * @default 'none'
  8019. */
  8020. this.updateType = NodeUpdateType.NONE;
  8021. /**
  8022. * The reference node.
  8023. *
  8024. * @type {?Node}
  8025. * @default null
  8026. */
  8027. this.referenceNode = null;
  8028. /**
  8029. * The texture value is stored in a private property.
  8030. *
  8031. * @private
  8032. * @type {Texture}
  8033. */
  8034. this._value = value;
  8035. /**
  8036. * The uniform node that represents the uv transformation matrix.
  8037. *
  8038. * @private
  8039. * @type {?UniformNode<mat3>}
  8040. * @default null
  8041. */
  8042. this._matrixUniform = null;
  8043. /**
  8044. * The uniform node that represents the y-flip. Only required for WebGL.
  8045. *
  8046. * @private
  8047. * @type {?UniformNode<bool>}
  8048. * @default null
  8049. */
  8050. this._flipYUniform = null;
  8051. this.setUpdateMatrix( uvNode === null );
  8052. }
  8053. set value( value ) {
  8054. if ( this.referenceNode ) {
  8055. this.referenceNode.value = value;
  8056. } else {
  8057. this._value = value;
  8058. }
  8059. }
  8060. /**
  8061. * The texture value.
  8062. *
  8063. * @type {Texture}
  8064. */
  8065. get value() {
  8066. return this.referenceNode ? this.referenceNode.value : this._value;
  8067. }
  8068. /**
  8069. * Overwritten since the uniform hash is defined by the texture's UUID.
  8070. *
  8071. * @param {NodeBuilder} builder - The current node builder.
  8072. * @return {string} The uniform hash.
  8073. */
  8074. getUniformHash( /*builder*/ ) {
  8075. return this.value.uuid;
  8076. }
  8077. /**
  8078. * Overwritten since the node type is inferred from the texture type.
  8079. *
  8080. * @param {NodeBuilder} builder - The current node builder.
  8081. * @return {string} The node type.
  8082. */
  8083. getNodeType( /*builder*/ ) {
  8084. if ( this.value.isDepthTexture === true ) return 'float';
  8085. if ( this.value.type === UnsignedIntType ) {
  8086. return 'uvec4';
  8087. } else if ( this.value.type === IntType ) {
  8088. return 'ivec4';
  8089. }
  8090. return 'vec4';
  8091. }
  8092. /**
  8093. * Overwrites the default implementation to return a fixed value `'texture'`.
  8094. *
  8095. * @param {NodeBuilder} builder - The current node builder.
  8096. * @return {string} The input type.
  8097. */
  8098. getInputType( /*builder*/ ) {
  8099. return 'texture';
  8100. }
  8101. /**
  8102. * Returns a default uvs based on the current texture's channel.
  8103. *
  8104. * @return {AttributeNode<vec2>} The default uvs.
  8105. */
  8106. getDefaultUV() {
  8107. return uv$1( this.value.channel );
  8108. }
  8109. /**
  8110. * Overwritten to always return the texture reference of the node.
  8111. *
  8112. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8113. * @return {Texture} The texture reference.
  8114. */
  8115. updateReference( /*state*/ ) {
  8116. return this.value;
  8117. }
  8118. /**
  8119. * Transforms the given uv node with the texture transformation matrix.
  8120. *
  8121. * @param {Node} uvNode - The uv node to transform.
  8122. * @return {Node} The transformed uv node.
  8123. */
  8124. getTransformedUV( uvNode ) {
  8125. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8126. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8127. }
  8128. /**
  8129. * Defines whether the uv transformation matrix should automatically be updated or not.
  8130. *
  8131. * @param {boolean} value - The update toggle.
  8132. * @return {TextureNode} A reference to this node.
  8133. */
  8134. setUpdateMatrix( value ) {
  8135. this.updateMatrix = value;
  8136. return this;
  8137. }
  8138. /**
  8139. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8140. * to modify the uv node for correct sampling.
  8141. *
  8142. * @param {NodeBuilder} builder - The current node builder.
  8143. * @param {Node} uvNode - The uv node to setup.
  8144. * @return {Node} The updated uv node.
  8145. */
  8146. setupUV( builder, uvNode ) {
  8147. if ( builder.isFlipY() ) {
  8148. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8149. uvNode = uvNode.toVar();
  8150. if ( this.sampler ) {
  8151. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8152. } else {
  8153. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8154. }
  8155. }
  8156. return uvNode;
  8157. }
  8158. /**
  8159. * Setups texture node by preparing the internal nodes for code generation.
  8160. *
  8161. * @param {NodeBuilder} builder - The current node builder.
  8162. */
  8163. setup( builder ) {
  8164. const properties = builder.getNodeProperties( this );
  8165. properties.referenceNode = this.referenceNode;
  8166. //
  8167. const texture = this.value;
  8168. if ( ! texture || texture.isTexture !== true ) {
  8169. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  8170. }
  8171. //
  8172. const uvNode = Fn( () => {
  8173. let uvNode = this.uvNode;
  8174. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8175. uvNode = builder.context.getUV( this, builder );
  8176. }
  8177. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8178. if ( this.updateMatrix === true ) {
  8179. uvNode = this.getTransformedUV( uvNode );
  8180. }
  8181. uvNode = this.setupUV( builder, uvNode );
  8182. //
  8183. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8184. //
  8185. return uvNode;
  8186. } )();
  8187. //
  8188. let levelNode = this.levelNode;
  8189. if ( levelNode === null && builder.context.getTextureLevel ) {
  8190. levelNode = builder.context.getTextureLevel( this );
  8191. }
  8192. //
  8193. properties.uvNode = uvNode;
  8194. properties.levelNode = levelNode;
  8195. properties.biasNode = this.biasNode;
  8196. properties.compareNode = this.compareNode;
  8197. properties.gradNode = this.gradNode;
  8198. properties.depthNode = this.depthNode;
  8199. properties.offsetNode = this.offsetNode;
  8200. }
  8201. /**
  8202. * Generates the uv code snippet.
  8203. *
  8204. * @param {NodeBuilder} builder - The current node builder.
  8205. * @param {Node} uvNode - The uv node to generate code for.
  8206. * @return {string} The generated code snippet.
  8207. */
  8208. generateUV( builder, uvNode ) {
  8209. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8210. }
  8211. /**
  8212. * Generates the offset code snippet.
  8213. *
  8214. * @param {NodeBuilder} builder - The current node builder.
  8215. * @param {Node} offsetNode - The offset node to generate code for.
  8216. * @return {string} The generated code snippet.
  8217. */
  8218. generateOffset( builder, offsetNode ) {
  8219. return offsetNode.build( builder, 'ivec2' );
  8220. }
  8221. /**
  8222. * Generates the snippet for the texture sampling.
  8223. *
  8224. * @param {NodeBuilder} builder - The current node builder.
  8225. * @param {string} textureProperty - The texture property.
  8226. * @param {string} uvSnippet - The uv snippet.
  8227. * @param {?string} levelSnippet - The level snippet.
  8228. * @param {?string} biasSnippet - The bias snippet.
  8229. * @param {?string} depthSnippet - The depth snippet.
  8230. * @param {?string} compareSnippet - The compare snippet.
  8231. * @param {?Array<string>} gradSnippet - The grad snippet.
  8232. * @param {?string} offsetSnippet - The offset snippet.
  8233. * @return {string} The generated code snippet.
  8234. */
  8235. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  8236. const texture = this.value;
  8237. let snippet;
  8238. if ( biasSnippet ) {
  8239. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8240. } else if ( gradSnippet ) {
  8241. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8242. } else if ( compareSnippet ) {
  8243. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8244. } else if ( this.sampler === false ) {
  8245. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8246. } else if ( levelSnippet ) {
  8247. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8248. } else {
  8249. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8250. }
  8251. return snippet;
  8252. }
  8253. /**
  8254. * Generates the code snippet of the texture node.
  8255. *
  8256. * @param {NodeBuilder} builder - The current node builder.
  8257. * @param {string} output - The current output.
  8258. * @return {string} The generated code snippet.
  8259. */
  8260. generate( builder, output ) {
  8261. const texture = this.value;
  8262. const properties = builder.getNodeProperties( this );
  8263. const textureProperty = super.generate( builder, 'property' );
  8264. if ( /^sampler/.test( output ) ) {
  8265. return textureProperty + '_sampler';
  8266. } else if ( builder.isReference( output ) ) {
  8267. return textureProperty;
  8268. } else {
  8269. const nodeData = builder.getDataFromNode( this );
  8270. let propertyName = nodeData.propertyName;
  8271. if ( propertyName === undefined ) {
  8272. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode, offsetNode } = properties;
  8273. const uvSnippet = this.generateUV( builder, uvNode );
  8274. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8275. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8276. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8277. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8278. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8279. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8280. const nodeVar = builder.getVarFromNode( this );
  8281. propertyName = builder.getPropertyName( nodeVar );
  8282. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  8283. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  8284. nodeData.snippet = snippet;
  8285. nodeData.propertyName = propertyName;
  8286. }
  8287. let snippet = propertyName;
  8288. const nodeType = this.getNodeType( builder );
  8289. if ( builder.needsToWorkingColorSpace( texture ) ) {
  8290. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  8291. }
  8292. return builder.format( snippet, nodeType, output );
  8293. }
  8294. }
  8295. /**
  8296. * Sets the sampler value.
  8297. *
  8298. * @param {boolean} value - The sampler value to set.
  8299. * @return {TextureNode} A reference to this texture node.
  8300. */
  8301. setSampler( value ) {
  8302. this.sampler = value;
  8303. return this;
  8304. }
  8305. /**
  8306. * Returns the sampler value.
  8307. *
  8308. * @return {boolean} The sampler value.
  8309. */
  8310. getSampler() {
  8311. return this.sampler;
  8312. }
  8313. // @TODO: Move to TSL
  8314. /**
  8315. * @function
  8316. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  8317. *
  8318. * @param {Node} uvNode - The uv node.
  8319. * @return {TextureNode} A texture node representing the texture sample.
  8320. */
  8321. uv( uvNode ) { // @deprecated, r172
  8322. warn( 'TextureNode: .uv() has been renamed. Use .sample() instead.' );
  8323. return this.sample( uvNode );
  8324. }
  8325. /**
  8326. * Samples the texture with the given uv node.
  8327. *
  8328. * @param {Node} uvNode - The uv node.
  8329. * @return {TextureNode} A texture node representing the texture sample.
  8330. */
  8331. sample( uvNode ) {
  8332. const textureNode = this.clone();
  8333. textureNode.uvNode = nodeObject( uvNode );
  8334. textureNode.referenceNode = this.getBase();
  8335. return nodeObject( textureNode );
  8336. }
  8337. /**
  8338. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8339. *
  8340. * @param {Node<uvec2>} uvNode - The uv node.
  8341. * @returns {TextureNode} A texture node representing the texture load.
  8342. */
  8343. load( uvNode ) {
  8344. return this.sample( uvNode ).setSampler( false );
  8345. }
  8346. /**
  8347. * Samples a blurred version of the texture by defining an internal bias.
  8348. *
  8349. * @param {Node<float>} amountNode - How blurred the texture should be.
  8350. * @return {TextureNode} A texture node representing the texture sample.
  8351. */
  8352. blur( amountNode ) {
  8353. const textureNode = this.clone();
  8354. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8355. textureNode.referenceNode = this.getBase();
  8356. const map = textureNode.value;
  8357. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8358. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8359. textureNode.biasNode = null;
  8360. }
  8361. return nodeObject( textureNode );
  8362. }
  8363. /**
  8364. * Samples a specific mip of the texture.
  8365. *
  8366. * @param {Node<int>} levelNode - The mip level to sample.
  8367. * @return {TextureNode} A texture node representing the texture sample.
  8368. */
  8369. level( levelNode ) {
  8370. const textureNode = this.clone();
  8371. textureNode.levelNode = nodeObject( levelNode );
  8372. textureNode.referenceNode = this.getBase();
  8373. return nodeObject( textureNode );
  8374. }
  8375. /**
  8376. * Returns the texture size of the requested level.
  8377. *
  8378. * @param {Node<int>} levelNode - The level to compute the size for.
  8379. * @return {TextureSizeNode} The texture size.
  8380. */
  8381. size( levelNode ) {
  8382. return textureSize( this, levelNode );
  8383. }
  8384. /**
  8385. * Samples the texture with the given bias.
  8386. *
  8387. * @param {Node<float>} biasNode - The bias node.
  8388. * @return {TextureNode} A texture node representing the texture sample.
  8389. */
  8390. bias( biasNode ) {
  8391. const textureNode = this.clone();
  8392. textureNode.biasNode = nodeObject( biasNode );
  8393. textureNode.referenceNode = this.getBase();
  8394. return nodeObject( textureNode );
  8395. }
  8396. /**
  8397. * Returns the base texture of this node.
  8398. * @return {TextureNode} The base texture node.
  8399. */
  8400. getBase() {
  8401. return this.referenceNode ? this.referenceNode.getBase() : this;
  8402. }
  8403. /**
  8404. * Samples the texture by executing a compare operation.
  8405. *
  8406. * @param {Node<float>} compareNode - The node that defines the compare value.
  8407. * @return {TextureNode} A texture node representing the texture sample.
  8408. */
  8409. compare( compareNode ) {
  8410. const textureNode = this.clone();
  8411. textureNode.compareNode = nodeObject( compareNode );
  8412. textureNode.referenceNode = this.getBase();
  8413. return nodeObject( textureNode );
  8414. }
  8415. /**
  8416. * Samples the texture using an explicit gradient.
  8417. *
  8418. * @param {Node<vec2>} gradNodeX - The gradX node.
  8419. * @param {Node<vec2>} gradNodeY - The gradY node.
  8420. * @return {TextureNode} A texture node representing the texture sample.
  8421. */
  8422. grad( gradNodeX, gradNodeY ) {
  8423. const textureNode = this.clone();
  8424. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8425. textureNode.referenceNode = this.getBase();
  8426. return nodeObject( textureNode );
  8427. }
  8428. /**
  8429. * Samples the texture by defining a depth node.
  8430. *
  8431. * @param {Node<int>} depthNode - The depth node.
  8432. * @return {TextureNode} A texture node representing the texture sample.
  8433. */
  8434. depth( depthNode ) {
  8435. const textureNode = this.clone();
  8436. textureNode.depthNode = nodeObject( depthNode );
  8437. textureNode.referenceNode = this.getBase();
  8438. return nodeObject( textureNode );
  8439. }
  8440. /**
  8441. * Samples the texture by defining an offset node.
  8442. *
  8443. * @param {Node<ivec2>} offsetNode - The offset node.
  8444. * @return {TextureNode} A texture node representing the texture sample.
  8445. */
  8446. offset( offsetNode ) {
  8447. const textureNode = this.clone();
  8448. textureNode.offsetNode = nodeObject( offsetNode );
  8449. textureNode.referenceNode = this.getBase();
  8450. return nodeObject( textureNode );
  8451. }
  8452. // --
  8453. serialize( data ) {
  8454. super.serialize( data );
  8455. data.value = this.value.toJSON( data.meta ).uuid;
  8456. data.sampler = this.sampler;
  8457. data.updateMatrix = this.updateMatrix;
  8458. data.updateType = this.updateType;
  8459. }
  8460. deserialize( data ) {
  8461. super.deserialize( data );
  8462. this.value = data.meta.textures[ data.value ];
  8463. this.sampler = data.sampler;
  8464. this.updateMatrix = data.updateMatrix;
  8465. this.updateType = data.updateType;
  8466. }
  8467. /**
  8468. * The update is used to implement the update of the uv transformation matrix.
  8469. */
  8470. update() {
  8471. const texture = this.value;
  8472. const matrixUniform = this._matrixUniform;
  8473. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8474. if ( texture.matrixAutoUpdate === true ) {
  8475. texture.updateMatrix();
  8476. }
  8477. //
  8478. const flipYUniform = this._flipYUniform;
  8479. if ( flipYUniform !== null ) {
  8480. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  8481. }
  8482. }
  8483. /**
  8484. * Clones the texture node.
  8485. *
  8486. * @return {TextureNode} The cloned texture node.
  8487. */
  8488. clone() {
  8489. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8490. newNode.sampler = this.sampler;
  8491. newNode.depthNode = this.depthNode;
  8492. newNode.compareNode = this.compareNode;
  8493. newNode.gradNode = this.gradNode;
  8494. newNode.offsetNode = this.offsetNode;
  8495. return newNode;
  8496. }
  8497. }
  8498. /**
  8499. * TSL function for creating a texture node.
  8500. *
  8501. * @tsl
  8502. * @function
  8503. * @param {?Texture} value - The texture.
  8504. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8505. * @param {?Node<int>} [levelNode=null] - The level node.
  8506. * @param {?Node<float>} [biasNode=null] - The bias node.
  8507. * @returns {TextureNode}
  8508. */
  8509. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8510. /**
  8511. * TSL function for creating a texture node or sample a texture node already existing.
  8512. *
  8513. * @tsl
  8514. * @function
  8515. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8516. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8517. * @param {?Node<int>} [levelNode=null] - The level node.
  8518. * @param {?Node<float>} [biasNode=null] - The bias node.
  8519. * @returns {TextureNode}
  8520. */
  8521. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8522. let textureNode;
  8523. if ( value && value.isTextureNode === true ) {
  8524. textureNode = nodeObject( value.clone() );
  8525. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8526. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8527. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8528. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8529. } else {
  8530. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8531. }
  8532. return textureNode;
  8533. };
  8534. /**
  8535. * TSL function for creating a uniform texture node.
  8536. *
  8537. * @tsl
  8538. * @function
  8539. * @param {?Texture} value - The texture.
  8540. * @returns {TextureNode}
  8541. */
  8542. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8543. /**
  8544. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8545. *
  8546. * @tsl
  8547. * @function
  8548. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8549. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8550. * @param {?Node<int>} [levelNode=null] - The level node.
  8551. * @param {?Node<float>} [biasNode=null] - The bias node.
  8552. * @returns {TextureNode}
  8553. */
  8554. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8555. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8556. /**
  8557. * Converts a texture or texture node to a sampler.
  8558. *
  8559. * @tsl
  8560. * @function
  8561. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8562. * @returns {Node}
  8563. */
  8564. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8565. /**
  8566. * Converts a texture or texture node to a sampler comparison.
  8567. *
  8568. * @tsl
  8569. * @function
  8570. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8571. * @returns {Node}
  8572. */
  8573. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8574. /**
  8575. * A special type of uniform node which represents array-like data
  8576. * as uniform buffers. The access usually happens via `element()`
  8577. * which returns an instance of {@link ArrayElementNode}. For example:
  8578. *
  8579. * ```js
  8580. * const bufferNode = buffer( array, 'mat4', count );
  8581. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8582. * ```
  8583. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8584. * since it handles more input types and automatically cares about buffer paddings.
  8585. *
  8586. * @augments UniformNode
  8587. */
  8588. class BufferNode extends UniformNode {
  8589. static get type() {
  8590. return 'BufferNode';
  8591. }
  8592. /**
  8593. * Constructs a new buffer node.
  8594. *
  8595. * @param {Array<number>} value - Array-like buffer data.
  8596. * @param {string} bufferType - The data type of the buffer.
  8597. * @param {number} [bufferCount=0] - The count of buffer elements.
  8598. */
  8599. constructor( value, bufferType, bufferCount = 0 ) {
  8600. super( value, bufferType );
  8601. /**
  8602. * This flag can be used for type testing.
  8603. *
  8604. * @type {boolean}
  8605. * @readonly
  8606. * @default true
  8607. */
  8608. this.isBufferNode = true;
  8609. /**
  8610. * The data type of the buffer.
  8611. *
  8612. * @type {string}
  8613. */
  8614. this.bufferType = bufferType;
  8615. /**
  8616. * The uniform node that holds the value of the reference node.
  8617. *
  8618. * @type {number}
  8619. * @default 0
  8620. */
  8621. this.bufferCount = bufferCount;
  8622. }
  8623. /**
  8624. * The data type of the buffer elements.
  8625. *
  8626. * @param {NodeBuilder} builder - The current node builder.
  8627. * @return {string} The element type.
  8628. */
  8629. getElementType( builder ) {
  8630. return this.getNodeType( builder );
  8631. }
  8632. /**
  8633. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8634. *
  8635. * @param {NodeBuilder} builder - The current node builder.
  8636. * @return {string} The input type.
  8637. */
  8638. getInputType( /*builder*/ ) {
  8639. return 'buffer';
  8640. }
  8641. }
  8642. /**
  8643. * TSL function for creating a buffer node.
  8644. *
  8645. * @tsl
  8646. * @function
  8647. * @param {Array<number>} value - Array-like buffer data.
  8648. * @param {string} type - The data type of a buffer element.
  8649. * @param {number} count - The count of buffer elements.
  8650. * @returns {BufferNode}
  8651. */
  8652. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8653. /**
  8654. * Represents the element access on uniform array nodes.
  8655. *
  8656. * @augments ArrayElementNode
  8657. */
  8658. class UniformArrayElementNode extends ArrayElementNode {
  8659. static get type() {
  8660. return 'UniformArrayElementNode';
  8661. }
  8662. /**
  8663. * Constructs a new buffer node.
  8664. *
  8665. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8666. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8667. */
  8668. constructor( uniformArrayNode, indexNode ) {
  8669. super( uniformArrayNode, indexNode );
  8670. /**
  8671. * This flag can be used for type testing.
  8672. *
  8673. * @type {boolean}
  8674. * @readonly
  8675. * @default true
  8676. */
  8677. this.isArrayBufferElementNode = true;
  8678. }
  8679. generate( builder ) {
  8680. const snippet = super.generate( builder );
  8681. const type = this.getNodeType();
  8682. const paddedType = this.node.getPaddedType();
  8683. return builder.format( snippet, paddedType, type );
  8684. }
  8685. }
  8686. /**
  8687. * Similar to {@link BufferNode} this module represents array-like data as
  8688. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8689. * data types in the array (e.g `three.js` primitives) and automatically
  8690. * manage buffer padding. It should be the first choice when working with
  8691. * uniforms buffers.
  8692. * ```js
  8693. * const tintColors = uniformArray( [
  8694. * new Color( 1, 0, 0 ),
  8695. * new Color( 0, 1, 0 ),
  8696. * new Color( 0, 0, 1 )
  8697. * ], 'color' );
  8698. *
  8699. * const redColor = tintColors.element( 0 );
  8700. *
  8701. * @augments BufferNode
  8702. */
  8703. class UniformArrayNode extends BufferNode {
  8704. static get type() {
  8705. return 'UniformArrayNode';
  8706. }
  8707. /**
  8708. * Constructs a new uniform array node.
  8709. *
  8710. * @param {Array<any>} value - Array holding the buffer data.
  8711. * @param {?string} [elementType=null] - The data type of a buffer element.
  8712. */
  8713. constructor( value, elementType = null ) {
  8714. super( null );
  8715. /**
  8716. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8717. * hold number primitives as well as three.js objects like vectors, matrices
  8718. * or colors.
  8719. *
  8720. * @type {Array<any>}
  8721. */
  8722. this.array = value;
  8723. /**
  8724. * The data type of an array element.
  8725. *
  8726. * @type {string}
  8727. */
  8728. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8729. /**
  8730. * The padded type. Uniform buffers must conform to a certain buffer layout
  8731. * so a separate type is computed to ensure correct buffer size.
  8732. *
  8733. * @type {string}
  8734. */
  8735. this.paddedType = this.getPaddedType();
  8736. /**
  8737. * Overwritten since uniform array nodes are updated per render.
  8738. *
  8739. * @type {string}
  8740. * @default 'render'
  8741. */
  8742. this.updateType = NodeUpdateType.RENDER;
  8743. /**
  8744. * This flag can be used for type testing.
  8745. *
  8746. * @type {boolean}
  8747. * @readonly
  8748. * @default true
  8749. */
  8750. this.isArrayBufferNode = true;
  8751. }
  8752. /**
  8753. * This method is overwritten since the node type is inferred from the
  8754. * {@link UniformArrayNode#paddedType}.
  8755. *
  8756. * @param {NodeBuilder} builder - The current node builder.
  8757. * @return {string} The node type.
  8758. */
  8759. getNodeType( /*builder*/ ) {
  8760. return this.paddedType;
  8761. }
  8762. /**
  8763. * The data type of the array elements.
  8764. *
  8765. * @param {NodeBuilder} builder - The current node builder.
  8766. * @return {string} The element type.
  8767. */
  8768. getElementType() {
  8769. return this.elementType;
  8770. }
  8771. /**
  8772. * Returns the padded type based on the element type.
  8773. *
  8774. * @return {string} The padded type.
  8775. */
  8776. getPaddedType() {
  8777. const elementType = this.elementType;
  8778. let paddedType = 'vec4';
  8779. if ( elementType === 'mat2' ) {
  8780. paddedType = 'mat2';
  8781. } else if ( /mat/.test( elementType ) === true ) {
  8782. paddedType = 'mat4';
  8783. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8784. paddedType = 'ivec4';
  8785. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8786. paddedType = 'uvec4';
  8787. }
  8788. return paddedType;
  8789. }
  8790. /**
  8791. * The update makes sure to correctly transfer the data from the (complex) objects
  8792. * in the array to the internal, correctly padded value buffer.
  8793. *
  8794. * @param {NodeFrame} frame - A reference to the current node frame.
  8795. */
  8796. update( /*frame*/ ) {
  8797. const { array, value } = this;
  8798. const elementType = this.elementType;
  8799. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8800. for ( let i = 0; i < array.length; i ++ ) {
  8801. const index = i * 4;
  8802. value[ index ] = array[ i ];
  8803. }
  8804. } else if ( elementType === 'color' ) {
  8805. for ( let i = 0; i < array.length; i ++ ) {
  8806. const index = i * 4;
  8807. const vector = array[ i ];
  8808. value[ index ] = vector.r;
  8809. value[ index + 1 ] = vector.g;
  8810. value[ index + 2 ] = vector.b || 0;
  8811. //value[ index + 3 ] = vector.a || 0;
  8812. }
  8813. } else if ( elementType === 'mat2' ) {
  8814. for ( let i = 0; i < array.length; i ++ ) {
  8815. const index = i * 4;
  8816. const matrix = array[ i ];
  8817. value[ index ] = matrix.elements[ 0 ];
  8818. value[ index + 1 ] = matrix.elements[ 1 ];
  8819. value[ index + 2 ] = matrix.elements[ 2 ];
  8820. value[ index + 3 ] = matrix.elements[ 3 ];
  8821. }
  8822. } else if ( elementType === 'mat3' ) {
  8823. for ( let i = 0; i < array.length; i ++ ) {
  8824. const index = i * 16;
  8825. const matrix = array[ i ];
  8826. value[ index ] = matrix.elements[ 0 ];
  8827. value[ index + 1 ] = matrix.elements[ 1 ];
  8828. value[ index + 2 ] = matrix.elements[ 2 ];
  8829. value[ index + 4 ] = matrix.elements[ 3 ];
  8830. value[ index + 5 ] = matrix.elements[ 4 ];
  8831. value[ index + 6 ] = matrix.elements[ 5 ];
  8832. value[ index + 8 ] = matrix.elements[ 6 ];
  8833. value[ index + 9 ] = matrix.elements[ 7 ];
  8834. value[ index + 10 ] = matrix.elements[ 8 ];
  8835. value[ index + 15 ] = 1;
  8836. }
  8837. } else if ( elementType === 'mat4' ) {
  8838. for ( let i = 0; i < array.length; i ++ ) {
  8839. const index = i * 16;
  8840. const matrix = array[ i ];
  8841. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  8842. value[ index + i ] = matrix.elements[ i ];
  8843. }
  8844. }
  8845. } else {
  8846. for ( let i = 0; i < array.length; i ++ ) {
  8847. const index = i * 4;
  8848. const vector = array[ i ];
  8849. value[ index ] = vector.x;
  8850. value[ index + 1 ] = vector.y;
  8851. value[ index + 2 ] = vector.z || 0;
  8852. value[ index + 3 ] = vector.w || 0;
  8853. }
  8854. }
  8855. }
  8856. /**
  8857. * Implement the value buffer creation based on the array data.
  8858. *
  8859. * @param {NodeBuilder} builder - A reference to the current node builder.
  8860. * @return {null}
  8861. */
  8862. setup( builder ) {
  8863. const length = this.array.length;
  8864. const elementType = this.elementType;
  8865. let arrayType = Float32Array;
  8866. const paddedType = this.paddedType;
  8867. const paddedElementLength = builder.getTypeLength( paddedType );
  8868. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  8869. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  8870. this.value = new arrayType( length * paddedElementLength );
  8871. this.bufferCount = length;
  8872. this.bufferType = paddedType;
  8873. return super.setup( builder );
  8874. }
  8875. /**
  8876. * Overwrites the default `element()` method to provide element access
  8877. * based on {@link UniformArrayNode}.
  8878. *
  8879. * @param {IndexNode} indexNode - The index node.
  8880. * @return {UniformArrayElementNode}
  8881. */
  8882. element( indexNode ) {
  8883. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  8884. }
  8885. }
  8886. /**
  8887. * TSL function for creating an uniform array node.
  8888. *
  8889. * @tsl
  8890. * @function
  8891. * @param {Array<any>} values - Array-like data.
  8892. * @param {?string} [nodeType] - The data type of the array elements.
  8893. * @returns {UniformArrayNode}
  8894. */
  8895. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  8896. /**
  8897. * The node allows to set values for built-in shader variables. That is
  8898. * required for features like hardware-accelerated vertex clipping.
  8899. *
  8900. * @augments Node
  8901. */
  8902. class BuiltinNode extends Node {
  8903. /**
  8904. * Constructs a new builtin node.
  8905. *
  8906. * @param {string} name - The name of the built-in shader variable.
  8907. */
  8908. constructor( name ) {
  8909. super( 'float' );
  8910. /**
  8911. * The name of the built-in shader variable.
  8912. *
  8913. * @type {string}
  8914. */
  8915. this.name = name;
  8916. /**
  8917. * This flag can be used for type testing.
  8918. *
  8919. * @type {boolean}
  8920. * @readonly
  8921. * @default true
  8922. */
  8923. this.isBuiltinNode = true;
  8924. }
  8925. /**
  8926. * Generates the code snippet of the builtin node.
  8927. *
  8928. * @param {NodeBuilder} builder - The current node builder.
  8929. * @return {string} The generated code snippet.
  8930. */
  8931. generate( /* builder */ ) {
  8932. return this.name;
  8933. }
  8934. }
  8935. /**
  8936. * TSL function for creating a builtin node.
  8937. *
  8938. * @tsl
  8939. * @function
  8940. * @param {string} name - The name of the built-in shader variable.
  8941. * @returns {BuiltinNode}
  8942. */
  8943. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8944. let _screenSizeVec, _viewportVec;
  8945. /**
  8946. * This node provides a collection of screen related metrics.
  8947. * Depending on {@link ScreenNode#scope}, the nodes can represent
  8948. * resolution or viewport data as well as fragment or uv coordinates.
  8949. *
  8950. * @augments Node
  8951. */
  8952. class ScreenNode extends Node {
  8953. static get type() {
  8954. return 'ScreenNode';
  8955. }
  8956. /**
  8957. * Constructs a new screen node.
  8958. *
  8959. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  8960. */
  8961. constructor( scope ) {
  8962. super();
  8963. /**
  8964. * The node represents different metric depending on which scope is selected.
  8965. *
  8966. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  8967. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  8968. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  8969. * - `ScreenNode.UV`: Normalized coordinates.
  8970. * - `ScreenNode.DPR`: Device pixel ratio.
  8971. *
  8972. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  8973. */
  8974. this.scope = scope;
  8975. /**
  8976. * This output node.
  8977. *
  8978. * @type {?Node}
  8979. * @default null
  8980. */
  8981. this._output = null;
  8982. /**
  8983. * This flag can be used for type testing.
  8984. *
  8985. * @type {boolean}
  8986. * @readonly
  8987. * @default true
  8988. */
  8989. this.isViewportNode = true;
  8990. }
  8991. /**
  8992. * This method is overwritten since the node type depends on the selected scope.
  8993. *
  8994. * @return {('float'|'vec2'|'vec4')} The node type.
  8995. */
  8996. getNodeType() {
  8997. if ( this.scope === ScreenNode.DPR ) return 'float';
  8998. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  8999. else return 'vec2';
  9000. }
  9001. /**
  9002. * This method is overwritten since the node's update type depends on the selected scope.
  9003. *
  9004. * @return {NodeUpdateType} The update type.
  9005. */
  9006. getUpdateType() {
  9007. let updateType = NodeUpdateType.NONE;
  9008. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9009. updateType = NodeUpdateType.RENDER;
  9010. }
  9011. this.updateType = updateType;
  9012. return updateType;
  9013. }
  9014. /**
  9015. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9016. * from the current renderer.
  9017. *
  9018. * @param {NodeFrame} frame - A reference to the current node frame.
  9019. */
  9020. update( { renderer } ) {
  9021. const renderTarget = renderer.getRenderTarget();
  9022. if ( this.scope === ScreenNode.VIEWPORT ) {
  9023. if ( renderTarget !== null ) {
  9024. _viewportVec.copy( renderTarget.viewport );
  9025. } else {
  9026. renderer.getViewport( _viewportVec );
  9027. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9028. }
  9029. } else if ( this.scope === ScreenNode.DPR ) {
  9030. this._output.value = renderer.getPixelRatio();
  9031. } else {
  9032. if ( renderTarget !== null ) {
  9033. _screenSizeVec.width = renderTarget.width;
  9034. _screenSizeVec.height = renderTarget.height;
  9035. } else {
  9036. renderer.getDrawingBufferSize( _screenSizeVec );
  9037. }
  9038. }
  9039. }
  9040. setup( /*builder*/ ) {
  9041. const scope = this.scope;
  9042. let output = null;
  9043. if ( scope === ScreenNode.SIZE ) {
  9044. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9045. } else if ( scope === ScreenNode.VIEWPORT ) {
  9046. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9047. } else if ( scope === ScreenNode.DPR ) {
  9048. output = uniform( 1 );
  9049. } else {
  9050. output = vec2( screenCoordinate.div( screenSize ) );
  9051. }
  9052. this._output = output;
  9053. return output;
  9054. }
  9055. generate( builder ) {
  9056. if ( this.scope === ScreenNode.COORDINATE ) {
  9057. let coord = builder.getFragCoord();
  9058. if ( builder.isFlipY() ) {
  9059. // follow webgpu standards
  9060. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9061. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9062. }
  9063. return coord;
  9064. }
  9065. return super.generate( builder );
  9066. }
  9067. }
  9068. ScreenNode.COORDINATE = 'coordinate';
  9069. ScreenNode.VIEWPORT = 'viewport';
  9070. ScreenNode.SIZE = 'size';
  9071. ScreenNode.UV = 'uv';
  9072. ScreenNode.DPR = 'dpr';
  9073. // Screen
  9074. /**
  9075. * TSL object that represents the current DPR.
  9076. *
  9077. * @tsl
  9078. * @type {ScreenNode<float>}
  9079. */
  9080. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9081. /**
  9082. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9083. *
  9084. * @tsl
  9085. * @type {ScreenNode<vec2>}
  9086. */
  9087. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9088. /**
  9089. * TSL object that represents the screen resolution in physical pixel units.
  9090. *
  9091. * @tsl
  9092. * @type {ScreenNode<vec2>}
  9093. */
  9094. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9095. /**
  9096. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9097. *
  9098. * @tsl
  9099. * @type {ScreenNode<vec2>}
  9100. */
  9101. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9102. // Viewport
  9103. /**
  9104. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9105. *
  9106. * @tsl
  9107. * @type {ScreenNode<vec4>}
  9108. */
  9109. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9110. /**
  9111. * TSL object that represents the viewport resolution in physical pixel units.
  9112. *
  9113. * @tsl
  9114. * @type {ScreenNode<vec2>}
  9115. */
  9116. const viewportSize = viewport.zw;
  9117. /**
  9118. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9119. *
  9120. * @tsl
  9121. * @type {ScreenNode<vec2>}
  9122. */
  9123. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9124. /**
  9125. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9126. *
  9127. * @tsl
  9128. * @type {ScreenNode<vec2>}
  9129. */
  9130. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9131. // Deprecated
  9132. /**
  9133. * @deprecated since r169. Use {@link screenSize} instead.
  9134. */
  9135. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  9136. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  9137. return screenSize;
  9138. }, 'vec2' ).once() )();
  9139. /**
  9140. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  9141. *
  9142. * @tsl
  9143. * @type {UniformNode<uint>}
  9144. */
  9145. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  9146. /**
  9147. * TSL object that represents the `near` value of the camera used for the current render.
  9148. *
  9149. * @tsl
  9150. * @type {UniformNode<float>}
  9151. */
  9152. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  9153. /**
  9154. * TSL object that represents the `far` value of the camera used for the current render.
  9155. *
  9156. * @tsl
  9157. * @type {UniformNode<float>}
  9158. */
  9159. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  9160. /**
  9161. * TSL object that represents the projection matrix of the camera used for the current render.
  9162. *
  9163. * @tsl
  9164. * @type {UniformNode<mat4>}
  9165. */
  9166. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9167. let cameraProjectionMatrix;
  9168. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9169. const matrices = [];
  9170. for ( const subCamera of camera.cameras ) {
  9171. matrices.push( subCamera.projectionMatrix );
  9172. }
  9173. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9174. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9175. } else {
  9176. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9177. }
  9178. return cameraProjectionMatrix;
  9179. } ).once() )();
  9180. /**
  9181. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9182. *
  9183. * @tsl
  9184. * @type {UniformNode<mat4>}
  9185. */
  9186. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9187. let cameraProjectionMatrixInverse;
  9188. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9189. const matrices = [];
  9190. for ( const subCamera of camera.cameras ) {
  9191. matrices.push( subCamera.projectionMatrixInverse );
  9192. }
  9193. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9194. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9195. } else {
  9196. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9197. }
  9198. return cameraProjectionMatrixInverse;
  9199. } ).once() )();
  9200. /**
  9201. * TSL object that represents the view matrix of the camera used for the current render.
  9202. *
  9203. * @tsl
  9204. * @type {UniformNode<mat4>}
  9205. */
  9206. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9207. let cameraViewMatrix;
  9208. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9209. const matrices = [];
  9210. for ( const subCamera of camera.cameras ) {
  9211. matrices.push( subCamera.matrixWorldInverse );
  9212. }
  9213. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9214. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  9215. } else {
  9216. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  9217. }
  9218. return cameraViewMatrix;
  9219. } ).once() )();
  9220. /**
  9221. * TSL object that represents the world matrix of the camera used for the current render.
  9222. *
  9223. * @tsl
  9224. * @type {UniformNode<mat4>}
  9225. */
  9226. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9227. let cameraWorldMatrix;
  9228. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9229. const matrices = [];
  9230. for ( const subCamera of camera.cameras ) {
  9231. matrices.push( subCamera.matrixWorld );
  9232. }
  9233. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  9234. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  9235. } else {
  9236. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  9237. }
  9238. return cameraWorldMatrix;
  9239. } ).once() )();
  9240. /**
  9241. * TSL object that represents the normal matrix of the camera used for the current render.
  9242. *
  9243. * @tsl
  9244. * @type {UniformNode<mat3>}
  9245. */
  9246. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9247. let cameraNormalMatrix;
  9248. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9249. const matrices = [];
  9250. for ( const subCamera of camera.cameras ) {
  9251. matrices.push( subCamera.normalMatrix );
  9252. }
  9253. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  9254. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  9255. } else {
  9256. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  9257. }
  9258. return cameraNormalMatrix;
  9259. } ).once() )();
  9260. /**
  9261. * TSL object that represents the position in world space of the camera used for the current render.
  9262. *
  9263. * @tsl
  9264. * @type {UniformNode<vec3>}
  9265. */
  9266. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9267. let cameraPosition;
  9268. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9269. const positions = [];
  9270. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  9271. positions.push( new Vector3() );
  9272. }
  9273. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  9274. const subCameras = camera.cameras;
  9275. const array = self.array;
  9276. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  9277. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  9278. }
  9279. } );
  9280. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  9281. } else {
  9282. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  9283. }
  9284. return cameraPosition;
  9285. } ).once() )();
  9286. /**
  9287. * TSL object that represents the viewport of the camera used for the current render.
  9288. *
  9289. * @tsl
  9290. * @type {UniformNode<vec4>}
  9291. */
  9292. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9293. let cameraViewport;
  9294. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9295. const viewports = [];
  9296. for ( const subCamera of camera.cameras ) {
  9297. viewports.push( subCamera.viewport );
  9298. }
  9299. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  9300. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  9301. } else {
  9302. // Fallback for single camera
  9303. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  9304. }
  9305. return cameraViewport;
  9306. } ).once() )();
  9307. const _sphere = /*@__PURE__*/ new Sphere();
  9308. /**
  9309. * This node can be used to access transformation related metrics of 3D objects.
  9310. * Depending on the selected scope, a different metric is represented as a uniform
  9311. * in the shader. The following scopes are supported:
  9312. *
  9313. * - `POSITION`: The object's position in world space.
  9314. * - `VIEW_POSITION`: The object's position in view/camera space.
  9315. * - `DIRECTION`: The object's direction in world space.
  9316. * - `SCALE`: The object's scale in world space.
  9317. * - `WORLD_MATRIX`: The object's matrix in world space.
  9318. *
  9319. * @augments Node
  9320. */
  9321. class Object3DNode extends Node {
  9322. static get type() {
  9323. return 'Object3DNode';
  9324. }
  9325. /**
  9326. * Constructs a new object 3D node.
  9327. *
  9328. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9329. * @param {?Object3D} [object3d=null] - The 3D object.
  9330. */
  9331. constructor( scope, object3d = null ) {
  9332. super();
  9333. /**
  9334. * The node reports a different type of transformation depending on the scope.
  9335. *
  9336. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9337. */
  9338. this.scope = scope;
  9339. /**
  9340. * The 3D object.
  9341. *
  9342. * @type {?Object3D}
  9343. * @default null
  9344. */
  9345. this.object3d = object3d;
  9346. /**
  9347. * Overwritten since this type of node is updated per object.
  9348. *
  9349. * @type {string}
  9350. * @default 'object'
  9351. */
  9352. this.updateType = NodeUpdateType.OBJECT;
  9353. /**
  9354. * Holds the value of the node as a uniform.
  9355. *
  9356. * @type {UniformNode}
  9357. */
  9358. this.uniformNode = new UniformNode( null );
  9359. }
  9360. /**
  9361. * Overwritten since the node type is inferred from the scope.
  9362. *
  9363. * @return {('mat4'|'vec3'|'float')} The node type.
  9364. */
  9365. getNodeType() {
  9366. const scope = this.scope;
  9367. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9368. return 'mat4';
  9369. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9370. return 'vec3';
  9371. } else if ( scope === Object3DNode.RADIUS ) {
  9372. return 'float';
  9373. }
  9374. }
  9375. /**
  9376. * Updates the uniform value depending on the scope.
  9377. *
  9378. * @param {NodeFrame} frame - The current node frame.
  9379. */
  9380. update( frame ) {
  9381. const object = this.object3d;
  9382. const uniformNode = this.uniformNode;
  9383. const scope = this.scope;
  9384. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9385. uniformNode.value = object.matrixWorld;
  9386. } else if ( scope === Object3DNode.POSITION ) {
  9387. uniformNode.value = uniformNode.value || new Vector3();
  9388. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9389. } else if ( scope === Object3DNode.SCALE ) {
  9390. uniformNode.value = uniformNode.value || new Vector3();
  9391. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9392. } else if ( scope === Object3DNode.DIRECTION ) {
  9393. uniformNode.value = uniformNode.value || new Vector3();
  9394. object.getWorldDirection( uniformNode.value );
  9395. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9396. const camera = frame.camera;
  9397. uniformNode.value = uniformNode.value || new Vector3();
  9398. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9399. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9400. } else if ( scope === Object3DNode.RADIUS ) {
  9401. const geometry = frame.object.geometry;
  9402. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9403. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9404. uniformNode.value = _sphere.radius;
  9405. }
  9406. }
  9407. /**
  9408. * Generates the code snippet of the uniform node. The node type of the uniform
  9409. * node also depends on the selected scope.
  9410. *
  9411. * @param {NodeBuilder} builder - The current node builder.
  9412. * @return {string} The generated code snippet.
  9413. */
  9414. generate( builder ) {
  9415. const scope = this.scope;
  9416. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9417. this.uniformNode.nodeType = 'mat4';
  9418. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9419. this.uniformNode.nodeType = 'vec3';
  9420. } else if ( scope === Object3DNode.RADIUS ) {
  9421. this.uniformNode.nodeType = 'float';
  9422. }
  9423. return this.uniformNode.build( builder );
  9424. }
  9425. serialize( data ) {
  9426. super.serialize( data );
  9427. data.scope = this.scope;
  9428. }
  9429. deserialize( data ) {
  9430. super.deserialize( data );
  9431. this.scope = data.scope;
  9432. }
  9433. }
  9434. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9435. Object3DNode.POSITION = 'position';
  9436. Object3DNode.SCALE = 'scale';
  9437. Object3DNode.VIEW_POSITION = 'viewPosition';
  9438. Object3DNode.DIRECTION = 'direction';
  9439. Object3DNode.RADIUS = 'radius';
  9440. /**
  9441. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9442. *
  9443. * @tsl
  9444. * @function
  9445. * @param {?Object3D} [object3d] - The 3D object.
  9446. * @returns {Object3DNode<vec3>}
  9447. */
  9448. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9449. /**
  9450. * TSL function for creating an object 3D node that represents the object's world matrix.
  9451. *
  9452. * @tsl
  9453. * @function
  9454. * @param {?Object3D} [object3d] - The 3D object.
  9455. * @returns {Object3DNode<mat4>}
  9456. */
  9457. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9458. /**
  9459. * TSL function for creating an object 3D node that represents the object's position in world space.
  9460. *
  9461. * @tsl
  9462. * @function
  9463. * @param {?Object3D} [object3d] - The 3D object.
  9464. * @returns {Object3DNode<vec3>}
  9465. */
  9466. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9467. /**
  9468. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9469. *
  9470. * @tsl
  9471. * @function
  9472. * @param {?Object3D} [object3d] - The 3D object.
  9473. * @returns {Object3DNode<vec3>}
  9474. */
  9475. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9476. /**
  9477. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9478. *
  9479. * @tsl
  9480. * @function
  9481. * @param {?Object3D} [object3d] - The 3D object.
  9482. * @returns {Object3DNode<vec3>}
  9483. */
  9484. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9485. /**
  9486. * TSL function for creating an object 3D node that represents the object's radius.
  9487. *
  9488. * @tsl
  9489. * @function
  9490. * @param {?Object3D} [object3d] - The 3D object.
  9491. * @returns {Object3DNode<float>}
  9492. */
  9493. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9494. /**
  9495. * This type of node is a specialized version of `Object3DNode`
  9496. * with larger set of model related metrics. Unlike `Object3DNode`,
  9497. * `ModelNode` extracts the reference to the 3D object from the
  9498. * current node frame state.
  9499. *
  9500. * @augments Object3DNode
  9501. */
  9502. class ModelNode extends Object3DNode {
  9503. static get type() {
  9504. return 'ModelNode';
  9505. }
  9506. /**
  9507. * Constructs a new object model node.
  9508. *
  9509. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9510. */
  9511. constructor( scope ) {
  9512. super( scope );
  9513. }
  9514. /**
  9515. * Extracts the model reference from the frame state and then
  9516. * updates the uniform value depending on the scope.
  9517. *
  9518. * @param {NodeFrame} frame - The current node frame.
  9519. */
  9520. update( frame ) {
  9521. this.object3d = frame.object;
  9522. super.update( frame );
  9523. }
  9524. }
  9525. /**
  9526. * TSL object that represents the object's direction in world space.
  9527. *
  9528. * @tsl
  9529. * @type {ModelNode<vec3>}
  9530. */
  9531. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9532. /**
  9533. * TSL object that represents the object's world matrix.
  9534. *
  9535. * @tsl
  9536. * @type {ModelNode<mat4>}
  9537. */
  9538. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9539. /**
  9540. * TSL object that represents the object's position in world space.
  9541. *
  9542. * @tsl
  9543. * @type {ModelNode<vec3>}
  9544. */
  9545. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9546. /**
  9547. * TSL object that represents the object's scale in world space.
  9548. *
  9549. * @tsl
  9550. * @type {ModelNode<vec3>}
  9551. */
  9552. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9553. /**
  9554. * TSL object that represents the object's position in view/camera space.
  9555. *
  9556. * @tsl
  9557. * @type {ModelNode<vec3>}
  9558. */
  9559. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9560. /**
  9561. * TSL object that represents the object's radius.
  9562. *
  9563. * @tsl
  9564. * @type {ModelNode<float>}
  9565. */
  9566. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9567. /**
  9568. * TSL object that represents the object's normal matrix.
  9569. *
  9570. * @tsl
  9571. * @type {UniformNode<mat3>}
  9572. */
  9573. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9574. /**
  9575. * TSL object that represents the object's inverse world matrix.
  9576. *
  9577. * @tsl
  9578. * @type {UniformNode<mat4>}
  9579. */
  9580. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9581. /**
  9582. * TSL object that represents the object's model view matrix.
  9583. *
  9584. * @tsl
  9585. * @type {Node<mat4>}
  9586. */
  9587. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9588. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  9589. } ).once() )().toVar( 'modelViewMatrix' );
  9590. // GPU Precision
  9591. /**
  9592. * TSL object that represents the object's model view in `mediump` precision.
  9593. *
  9594. * @tsl
  9595. * @type {Node<mat4>}
  9596. */
  9597. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9598. // CPU Precision
  9599. /**
  9600. * TSL object that represents the object's model view in `highp` precision
  9601. * which is achieved by computing the matrix in JS and not in the shader.
  9602. *
  9603. * @tsl
  9604. * @type {Node<mat4>}
  9605. */
  9606. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9607. builder.context.isHighPrecisionModelViewMatrix = true;
  9608. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9609. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9610. } );
  9611. } ).once() )().toVar( 'highpModelViewMatrix' );
  9612. /**
  9613. * TSL object that represents the object's model normal view in `highp` precision
  9614. * which is achieved by computing the matrix in JS and not in the shader.
  9615. *
  9616. * @tsl
  9617. * @type {Node<mat3>}
  9618. */
  9619. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9620. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9621. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9622. if ( isHighPrecisionModelViewMatrix !== true ) {
  9623. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9624. }
  9625. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9626. } );
  9627. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9628. /**
  9629. * TSL object that represents the position attribute of the current rendered object.
  9630. *
  9631. * @tsl
  9632. * @type {AttributeNode<vec3>}
  9633. */
  9634. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9635. /**
  9636. * TSL object that represents the vertex position in local space of the current rendered object.
  9637. *
  9638. * @tsl
  9639. * @type {AttributeNode<vec3>}
  9640. */
  9641. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9642. /**
  9643. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9644. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9645. *
  9646. * @tsl
  9647. * @type {AttributeNode<vec3>}
  9648. */
  9649. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9650. /**
  9651. * TSL object that represents the vertex position in world space of the current rendered object.
  9652. *
  9653. * @tsl
  9654. * @type {VaryingNode<vec3>}
  9655. */
  9656. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9657. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9658. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9659. /**
  9660. * TSL object that represents the position world direction of the current rendered object.
  9661. *
  9662. * @tsl
  9663. * @type {Node<vec3>}
  9664. */
  9665. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9666. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9667. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9668. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9669. /**
  9670. * TSL object that represents the vertex position in view space of the current rendered object.
  9671. *
  9672. * @tsl
  9673. * @type {VaryingNode<vec3>}
  9674. */
  9675. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9676. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9677. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9678. /**
  9679. * TSL object that represents the position view direction of the current rendered object.
  9680. *
  9681. * @tsl
  9682. * @type {VaryingNode<vec3>}
  9683. */
  9684. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  9685. /**
  9686. * This node can be used to evaluate whether a primitive is front or back facing.
  9687. *
  9688. * @augments Node
  9689. */
  9690. class FrontFacingNode extends Node {
  9691. static get type() {
  9692. return 'FrontFacingNode';
  9693. }
  9694. /**
  9695. * Constructs a new front facing node.
  9696. */
  9697. constructor() {
  9698. super( 'bool' );
  9699. /**
  9700. * This flag can be used for type testing.
  9701. *
  9702. * @type {boolean}
  9703. * @readonly
  9704. * @default true
  9705. */
  9706. this.isFrontFacingNode = true;
  9707. }
  9708. generate( builder ) {
  9709. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9710. //
  9711. const { material } = builder;
  9712. if ( material.side === BackSide ) {
  9713. return 'false';
  9714. }
  9715. return builder.getFrontFacing();
  9716. }
  9717. }
  9718. /**
  9719. * TSL object that represents whether a primitive is front or back facing
  9720. *
  9721. * @tsl
  9722. * @type {FrontFacingNode<bool>}
  9723. */
  9724. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9725. /**
  9726. * TSL object that represents the front facing status as a number instead of a bool.
  9727. * `1` means front facing, `-1` means back facing.
  9728. *
  9729. * @tsl
  9730. * @type {Node<float>}
  9731. */
  9732. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9733. /**
  9734. * Converts a direction vector to a face direction vector based on the material's side.
  9735. *
  9736. * If the material is set to `BackSide`, the direction is inverted.
  9737. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9738. *
  9739. * @tsl
  9740. * @param {Node<vec3>} direction - The direction vector to convert.
  9741. * @returns {Node<vec3>} The converted direction vector.
  9742. */
  9743. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9744. const side = material.side;
  9745. if ( side === BackSide ) {
  9746. direction = direction.mul( -1 );
  9747. } else if ( side === DoubleSide ) {
  9748. direction = direction.mul( faceDirection );
  9749. }
  9750. return direction;
  9751. } );
  9752. /**
  9753. * TSL object that represents the normal attribute of the current rendered object in local space.
  9754. *
  9755. * @tsl
  9756. * @type {Node<vec3>}
  9757. */
  9758. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  9759. /**
  9760. * TSL object that represents the vertex normal of the current rendered object in local space.
  9761. *
  9762. * @tsl
  9763. * @type {Node<vec3>}
  9764. */
  9765. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  9766. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  9767. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  9768. return vec3( 0, 1, 0 );
  9769. }
  9770. return normalGeometry;
  9771. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  9772. /**
  9773. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  9774. *
  9775. * @tsl
  9776. * @type {Node<vec3>}
  9777. */
  9778. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  9779. /**
  9780. * TSL object that represents the vertex normal of the current rendered object in view space.
  9781. *
  9782. * @tsl
  9783. * @type {Node<vec3>}
  9784. */
  9785. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9786. let node;
  9787. if ( builder.material.flatShading === true ) {
  9788. node = normalFlat;
  9789. } else {
  9790. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  9791. }
  9792. return node;
  9793. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  9794. /**
  9795. * TSL object that represents the vertex normal of the current rendered object in world space.
  9796. *
  9797. * @tsl
  9798. * @type {Node<vec3>}
  9799. */
  9800. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9801. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  9802. if ( builder.material.flatShading !== true ) {
  9803. normal = normal.toVarying( 'v_normalWorldGeometry' );
  9804. }
  9805. return normal.normalize().toVar( 'normalWorldGeometry' );
  9806. }, 'vec3' ).once() )();
  9807. /**
  9808. * TSL object that represents the vertex normal of the current rendered object in view space.
  9809. *
  9810. * @tsl
  9811. * @type {Node<vec3>}
  9812. */
  9813. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  9814. let node;
  9815. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9816. node = normalViewGeometry;
  9817. if ( material.flatShading !== true ) {
  9818. node = directionToFaceDirection( node );
  9819. }
  9820. } else {
  9821. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9822. node = context.setupNormal().context( { getUV: null } );
  9823. }
  9824. return node;
  9825. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  9826. /**
  9827. * TSL object that represents the vertex normal of the current rendered object in world space.
  9828. *
  9829. * @tsl
  9830. * @type {Node<vec3>}
  9831. */
  9832. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  9833. /**
  9834. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  9835. *
  9836. * @tsl
  9837. * @type {Node<vec3>}
  9838. */
  9839. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  9840. let node;
  9841. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9842. node = normalView;
  9843. } else {
  9844. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9845. node = context.setupClearcoatNormal().context( { getUV: null } );
  9846. }
  9847. return node;
  9848. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  9849. /**
  9850. * Transforms the normal with the given matrix.
  9851. *
  9852. * @tsl
  9853. * @function
  9854. * @param {Node<vec3>} normal - The normal.
  9855. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  9856. * @return {Node<vec3>} The transformed normal.
  9857. */
  9858. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  9859. const m = mat3( matrix );
  9860. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  9861. return m.mul( transformedNormal ).xyz;
  9862. } );
  9863. /**
  9864. * Transforms the given normal from local to view space.
  9865. *
  9866. * @tsl
  9867. * @function
  9868. * @param {Node<vec3>} normal - The normal.
  9869. * @param {NodeBuilder} builder - The current node builder.
  9870. * @return {Node<vec3>} The transformed normal.
  9871. */
  9872. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  9873. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  9874. if ( modelNormalViewMatrix !== null ) {
  9875. return modelNormalViewMatrix.transformDirection( normal );
  9876. }
  9877. //
  9878. const transformedNormal = modelNormalMatrix.mul( normal );
  9879. return cameraViewMatrix.transformDirection( transformedNormal );
  9880. } );
  9881. // Deprecated
  9882. /**
  9883. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  9884. *
  9885. * @tsl
  9886. * @type {Node<vec3>}
  9887. * @deprecated since r178. Use `normalView` instead.
  9888. */
  9889. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  9890. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  9891. return normalView;
  9892. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9893. /**
  9894. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  9895. *
  9896. * @tsl
  9897. * @type {Node<vec3>}
  9898. * @deprecated since r178. Use `normalWorld` instead.
  9899. */
  9900. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  9901. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  9902. return normalWorld;
  9903. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9904. /**
  9905. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  9906. *
  9907. * @tsl
  9908. * @type {Node<vec3>}
  9909. * @deprecated since r178. Use `clearcoatNormalView` instead.
  9910. */
  9911. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  9912. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  9913. return clearcoatNormalView;
  9914. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9915. const _e1$1 = /*@__PURE__*/ new Euler();
  9916. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9917. /**
  9918. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  9919. *
  9920. * @tsl
  9921. * @type {UniformNode<float>}
  9922. */
  9923. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  9924. /**
  9925. * TSL object that represents the intensity of environment maps of PBR materials.
  9926. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  9927. *
  9928. * @tsl
  9929. * @type {Node<float>}
  9930. */
  9931. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  9932. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  9933. } );
  9934. /**
  9935. * TSL object that represents the rotation of environment maps.
  9936. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  9937. * rotation of `scene.environment` instead.
  9938. *
  9939. * @tsl
  9940. * @type {Node<mat4>}
  9941. */
  9942. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  9943. return frame.material;
  9944. } ).onObjectUpdate( function ( { material, scene } ) {
  9945. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  9946. if ( rotation ) {
  9947. _e1$1.copy( rotation );
  9948. _m1$1.makeRotationFromEuler( _e1$1 );
  9949. } else {
  9950. _m1$1.identity();
  9951. }
  9952. return _m1$1;
  9953. } );
  9954. /**
  9955. * The reflect vector in view space.
  9956. *
  9957. * @tsl
  9958. * @type {Node<vec3>}
  9959. */
  9960. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  9961. /**
  9962. * The refract vector in view space.
  9963. *
  9964. * @tsl
  9965. * @type {Node<vec3>}
  9966. */
  9967. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  9968. /**
  9969. * Used for sampling cube maps when using cube reflection mapping.
  9970. *
  9971. * @tsl
  9972. * @type {Node<vec3>}
  9973. */
  9974. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9975. /**
  9976. * Used for sampling cube maps when using cube refraction mapping.
  9977. *
  9978. * @tsl
  9979. * @type {Node<vec3>}
  9980. */
  9981. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9982. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  9983. /**
  9984. * This type of uniform node represents a cube texture.
  9985. *
  9986. * @augments TextureNode
  9987. */
  9988. class CubeTextureNode extends TextureNode {
  9989. static get type() {
  9990. return 'CubeTextureNode';
  9991. }
  9992. /**
  9993. * Constructs a new cube texture node.
  9994. *
  9995. * @param {CubeTexture} value - The cube texture.
  9996. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9997. * @param {?Node<int>} [levelNode=null] - The level node.
  9998. * @param {?Node<float>} [biasNode=null] - The bias node.
  9999. */
  10000. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  10001. super( value, uvNode, levelNode, biasNode );
  10002. /**
  10003. * This flag can be used for type testing.
  10004. *
  10005. * @type {boolean}
  10006. * @readonly
  10007. * @default true
  10008. */
  10009. this.isCubeTextureNode = true;
  10010. }
  10011. /**
  10012. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  10013. *
  10014. * @param {NodeBuilder} builder - The current node builder.
  10015. * @return {string} The input type.
  10016. */
  10017. getInputType( /*builder*/ ) {
  10018. return 'cubeTexture';
  10019. }
  10020. /**
  10021. * Returns a default uvs based on the mapping type of the cube texture.
  10022. *
  10023. * @return {Node<vec3>} The default uv attribute.
  10024. */
  10025. getDefaultUV() {
  10026. const texture = this.value;
  10027. if ( texture.mapping === CubeReflectionMapping ) {
  10028. return reflectVector;
  10029. } else if ( texture.mapping === CubeRefractionMapping ) {
  10030. return refractVector;
  10031. } else {
  10032. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  10033. return vec3( 0, 0, 0 );
  10034. }
  10035. }
  10036. /**
  10037. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  10038. * for cube textures. The uv transformation matrix is not applied to cube textures.
  10039. *
  10040. * @param {boolean} value - The update toggle.
  10041. */
  10042. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  10043. /**
  10044. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  10045. * to modify the uv node for correct sampling.
  10046. *
  10047. * @param {NodeBuilder} builder - The current node builder.
  10048. * @param {Node} uvNode - The uv node to setup.
  10049. * @return {Node} The updated uv node.
  10050. */
  10051. setupUV( builder, uvNode ) {
  10052. const texture = this.value;
  10053. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  10054. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  10055. }
  10056. return materialEnvRotation.mul( uvNode );
  10057. }
  10058. /**
  10059. * Generates the uv code snippet.
  10060. *
  10061. * @param {NodeBuilder} builder - The current node builder.
  10062. * @param {Node} cubeUV - The uv node to generate code for.
  10063. * @return {string} The generated code snippet.
  10064. */
  10065. generateUV( builder, cubeUV ) {
  10066. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  10067. }
  10068. }
  10069. /**
  10070. * TSL function for creating a cube texture node.
  10071. *
  10072. * @tsl
  10073. * @function
  10074. * @param {CubeTexture} value - The cube texture.
  10075. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10076. * @param {?Node<int>} [levelNode=null] - The level node.
  10077. * @param {?Node<float>} [biasNode=null] - The bias node.
  10078. * @returns {CubeTextureNode}
  10079. */
  10080. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  10081. /**
  10082. * TSL function for creating a cube texture uniform node.
  10083. *
  10084. * @tsl
  10085. * @function
  10086. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  10087. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10088. * @param {?Node<int>} [levelNode=null] - The level node.
  10089. * @param {?Node<float>} [biasNode=null] - The bias node.
  10090. * @returns {CubeTextureNode}
  10091. */
  10092. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  10093. let textureNode;
  10094. if ( value && value.isCubeTextureNode === true ) {
  10095. textureNode = nodeObject( value.clone() );
  10096. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  10097. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  10098. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  10099. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  10100. } else {
  10101. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  10102. }
  10103. return textureNode;
  10104. };
  10105. /**
  10106. * TSL function for creating a uniform cube texture node.
  10107. *
  10108. * @tsl
  10109. * @function
  10110. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  10111. * @returns {CubeTextureNode}
  10112. */
  10113. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  10114. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  10115. /**
  10116. * This class is only relevant if the referenced property is array-like.
  10117. * In this case, `ReferenceElementNode` allows to refer to a specific
  10118. * element inside the data structure via an index.
  10119. *
  10120. * @augments ArrayElementNode
  10121. */
  10122. class ReferenceElementNode extends ArrayElementNode {
  10123. static get type() {
  10124. return 'ReferenceElementNode';
  10125. }
  10126. /**
  10127. * Constructs a new reference element node.
  10128. *
  10129. * @param {?ReferenceNode} referenceNode - The reference node.
  10130. * @param {Node} indexNode - The index node that defines the element access.
  10131. */
  10132. constructor( referenceNode, indexNode ) {
  10133. super( referenceNode, indexNode );
  10134. /**
  10135. * Similar to {@link ReferenceNode#reference}, an additional
  10136. * property references to the current node.
  10137. *
  10138. * @type {?ReferenceNode}
  10139. * @default null
  10140. */
  10141. this.referenceNode = referenceNode;
  10142. /**
  10143. * This flag can be used for type testing.
  10144. *
  10145. * @type {boolean}
  10146. * @readonly
  10147. * @default true
  10148. */
  10149. this.isReferenceElementNode = true;
  10150. }
  10151. /**
  10152. * This method is overwritten since the node type is inferred from
  10153. * the uniform type of the reference node.
  10154. *
  10155. * @return {string} The node type.
  10156. */
  10157. getNodeType() {
  10158. return this.referenceNode.uniformType;
  10159. }
  10160. generate( builder ) {
  10161. const snippet = super.generate( builder );
  10162. const arrayType = this.referenceNode.getNodeType();
  10163. const elementType = this.getNodeType();
  10164. return builder.format( snippet, arrayType, elementType );
  10165. }
  10166. }
  10167. /**
  10168. * This type of node establishes a reference to a property of another object.
  10169. * In this way, the value of the node is automatically linked to the value of
  10170. * referenced object. Reference nodes internally represent the linked value
  10171. * as a uniform.
  10172. *
  10173. * @augments Node
  10174. */
  10175. class ReferenceNode extends Node {
  10176. static get type() {
  10177. return 'ReferenceNode';
  10178. }
  10179. /**
  10180. * Constructs a new reference node.
  10181. *
  10182. * @param {string} property - The name of the property the node refers to.
  10183. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  10184. * @param {?Object} [object=null] - The object the property belongs to.
  10185. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  10186. */
  10187. constructor( property, uniformType, object = null, count = null ) {
  10188. super();
  10189. /**
  10190. * The name of the property the node refers to.
  10191. *
  10192. * @type {string}
  10193. */
  10194. this.property = property;
  10195. /**
  10196. * The uniform type that should be used to represent the property value.
  10197. *
  10198. * @type {string}
  10199. */
  10200. this.uniformType = uniformType;
  10201. /**
  10202. * The object the property belongs to.
  10203. *
  10204. * @type {?Object}
  10205. * @default null
  10206. */
  10207. this.object = object;
  10208. /**
  10209. * When the linked property is an array, this parameter defines its length.
  10210. *
  10211. * @type {?number}
  10212. * @default null
  10213. */
  10214. this.count = count;
  10215. /**
  10216. * The property name might have dots so nested properties can be referred.
  10217. * The hierarchy of the names is stored inside this array.
  10218. *
  10219. * @type {Array<string>}
  10220. */
  10221. this.properties = property.split( '.' );
  10222. /**
  10223. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  10224. * since the final reference might be updated from calling code.
  10225. *
  10226. * @type {?Object}
  10227. * @default null
  10228. */
  10229. this.reference = object;
  10230. /**
  10231. * The uniform node that holds the value of the reference node.
  10232. *
  10233. * @type {UniformNode}
  10234. * @default null
  10235. */
  10236. this.node = null;
  10237. /**
  10238. * The uniform group of the internal uniform.
  10239. *
  10240. * @type {UniformGroupNode}
  10241. * @default null
  10242. */
  10243. this.group = null;
  10244. /**
  10245. * An optional label of the internal uniform node.
  10246. *
  10247. * @type {?string}
  10248. * @default null
  10249. */
  10250. this.name = null;
  10251. /**
  10252. * Overwritten since reference nodes are updated per object.
  10253. *
  10254. * @type {string}
  10255. * @default 'object'
  10256. */
  10257. this.updateType = NodeUpdateType.OBJECT;
  10258. }
  10259. /**
  10260. * When the referred property is array-like, this method can be used
  10261. * to access elements via an index node.
  10262. *
  10263. * @param {IndexNode} indexNode - indexNode.
  10264. * @return {ReferenceElementNode} A reference to an element.
  10265. */
  10266. element( indexNode ) {
  10267. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  10268. }
  10269. /**
  10270. * Sets the uniform group for this reference node.
  10271. *
  10272. * @param {UniformGroupNode} group - The uniform group to set.
  10273. * @return {ReferenceNode} A reference to this node.
  10274. */
  10275. setGroup( group ) {
  10276. this.group = group;
  10277. return this;
  10278. }
  10279. /**
  10280. * Sets the name for the internal uniform.
  10281. *
  10282. * @param {string} name - The label to set.
  10283. * @return {ReferenceNode} A reference to this node.
  10284. */
  10285. setName( name ) {
  10286. this.name = name;
  10287. return this;
  10288. }
  10289. /**
  10290. * Sets the label for the internal uniform.
  10291. *
  10292. * @deprecated
  10293. * @param {string} name - The label to set.
  10294. * @return {ReferenceNode} A reference to this node.
  10295. */
  10296. label( name ) {
  10297. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  10298. return this.setName( name );
  10299. }
  10300. /**
  10301. * Sets the node type which automatically defines the internal
  10302. * uniform type.
  10303. *
  10304. * @param {string} uniformType - The type to set.
  10305. */
  10306. setNodeType( uniformType ) {
  10307. let node = null;
  10308. if ( this.count !== null ) {
  10309. node = buffer( null, uniformType, this.count );
  10310. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  10311. node = uniformArray( null, uniformType );
  10312. } else if ( uniformType === 'texture' ) {
  10313. node = texture( null );
  10314. } else if ( uniformType === 'cubeTexture' ) {
  10315. node = cubeTexture( null );
  10316. } else {
  10317. node = uniform( null, uniformType );
  10318. }
  10319. if ( this.group !== null ) {
  10320. node.setGroup( this.group );
  10321. }
  10322. if ( this.name !== null ) node.setName( this.name );
  10323. this.node = node;
  10324. }
  10325. /**
  10326. * This method is overwritten since the node type is inferred from
  10327. * the type of the reference node.
  10328. *
  10329. * @param {NodeBuilder} builder - The current node builder.
  10330. * @return {string} The node type.
  10331. */
  10332. getNodeType( builder ) {
  10333. if ( this.node === null ) {
  10334. this.updateReference( builder );
  10335. this.updateValue();
  10336. }
  10337. return this.node.getNodeType( builder );
  10338. }
  10339. /**
  10340. * Returns the property value from the given referred object.
  10341. *
  10342. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10343. * @return {any} The value.
  10344. */
  10345. getValueFromReference( object = this.reference ) {
  10346. const { properties } = this;
  10347. let value = object[ properties[ 0 ] ];
  10348. for ( let i = 1; i < properties.length; i ++ ) {
  10349. value = value[ properties[ i ] ];
  10350. }
  10351. return value;
  10352. }
  10353. /**
  10354. * Allows to update the reference based on the given state. The state is only
  10355. * evaluated {@link ReferenceNode#object} is not set.
  10356. *
  10357. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10358. * @return {Object} The updated reference.
  10359. */
  10360. updateReference( state ) {
  10361. this.reference = this.object !== null ? this.object : state.object;
  10362. return this.reference;
  10363. }
  10364. /**
  10365. * The output of the reference node is the internal uniform node.
  10366. *
  10367. * @param {NodeBuilder} builder - The current node builder.
  10368. * @return {UniformNode} The output node.
  10369. */
  10370. setup( /* builder */ ) {
  10371. this.updateValue();
  10372. return this.node;
  10373. }
  10374. /**
  10375. * Overwritten to update the internal uniform value.
  10376. *
  10377. * @param {NodeFrame} frame - A reference to the current node frame.
  10378. */
  10379. update( /*frame*/ ) {
  10380. this.updateValue();
  10381. }
  10382. /**
  10383. * Retrieves the value from the referred object property and uses it
  10384. * to updated the internal uniform.
  10385. */
  10386. updateValue() {
  10387. if ( this.node === null ) this.setNodeType( this.uniformType );
  10388. const value = this.getValueFromReference();
  10389. if ( Array.isArray( value ) ) {
  10390. this.node.array = value;
  10391. } else {
  10392. this.node.value = value;
  10393. }
  10394. }
  10395. }
  10396. /**
  10397. * TSL function for creating a reference node.
  10398. *
  10399. * @tsl
  10400. * @function
  10401. * @param {string} name - The name of the property the node refers to.
  10402. * @param {string} type - The uniform type that should be used to represent the property value.
  10403. * @param {?Object} [object] - The object the property belongs to.
  10404. * @returns {ReferenceNode}
  10405. */
  10406. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  10407. /**
  10408. * TSL function for creating a reference node. Use this function if you want need a reference
  10409. * to an array-like property that should be represented as a uniform buffer.
  10410. *
  10411. * @tsl
  10412. * @function
  10413. * @param {string} name - The name of the property the node refers to.
  10414. * @param {string} type - The uniform type that should be used to represent the property value.
  10415. * @param {number} count - The number of value inside the array-like object.
  10416. * @param {Object} object - An array-like object the property belongs to.
  10417. * @returns {ReferenceNode}
  10418. */
  10419. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  10420. /**
  10421. * This node is a special type of reference node which is intended
  10422. * for linking material properties with node values.
  10423. * ```js
  10424. * const opacityNode = materialReference( 'opacity', 'float', material );
  10425. * ```
  10426. * When changing `material.opacity`, the node value of `opacityNode` will
  10427. * automatically be updated.
  10428. *
  10429. * @augments ReferenceNode
  10430. */
  10431. class MaterialReferenceNode extends ReferenceNode {
  10432. static get type() {
  10433. return 'MaterialReferenceNode';
  10434. }
  10435. /**
  10436. * Constructs a new material reference node.
  10437. *
  10438. * @param {string} property - The name of the property the node refers to.
  10439. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10440. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10441. * the node refers to the material of the current rendered object.
  10442. */
  10443. constructor( property, inputType, material = null ) {
  10444. super( property, inputType, material );
  10445. /**
  10446. * The material the property belongs to. When no material is set,
  10447. * the node refers to the material of the current rendered object.
  10448. *
  10449. * @type {?Material}
  10450. * @default null
  10451. */
  10452. this.material = material;
  10453. /**
  10454. * This flag can be used for type testing.
  10455. *
  10456. * @type {boolean}
  10457. * @readonly
  10458. * @default true
  10459. */
  10460. this.isMaterialReferenceNode = true;
  10461. }
  10462. /**
  10463. * Updates the reference based on the given state. The state is only evaluated
  10464. * {@link MaterialReferenceNode#material} is not set.
  10465. *
  10466. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10467. * @return {Object} The updated reference.
  10468. */
  10469. updateReference( state ) {
  10470. this.reference = this.material !== null ? this.material : state.material;
  10471. return this.reference;
  10472. }
  10473. }
  10474. /**
  10475. * TSL function for creating a material reference node.
  10476. *
  10477. * @tsl
  10478. * @function
  10479. * @param {string} name - The name of the property the node refers to.
  10480. * @param {string} type - The uniform type that should be used to represent the property value.
  10481. * @param {?Material} [material=null] - The material the property belongs to.
  10482. * When no material is set, the node refers to the material of the current rendered object.
  10483. * @returns {MaterialReferenceNode}
  10484. */
  10485. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  10486. // Normal Mapping Without Precomputed Tangents
  10487. // http://www.thetenthplanet.de/archives/1180
  10488. const uv = uv$1();
  10489. const q0 = positionView.dFdx();
  10490. const q1 = positionView.dFdy();
  10491. const st0 = uv.dFdx();
  10492. const st1 = uv.dFdy();
  10493. const N = normalView;
  10494. const q1perp = q1.cross( N );
  10495. const q0perp = N.cross( q0 );
  10496. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10497. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10498. const det = T.dot( T ).max( B.dot( B ) );
  10499. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10500. /**
  10501. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10502. * Useful for normal mapping without precomputed tangents.
  10503. *
  10504. * Reference: http://www.thetenthplanet.de/archives/1180
  10505. *
  10506. * @tsl
  10507. * @type {Node<vec3>}
  10508. */
  10509. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10510. /**
  10511. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10512. * Complements the tangentViewFrame for constructing the tangent space basis.
  10513. *
  10514. * Reference: http://www.thetenthplanet.de/archives/1180
  10515. *
  10516. * @tsl
  10517. * @type {Node<vec3>}
  10518. */
  10519. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10520. /**
  10521. * TSL object that represents the tangent attribute of the current rendered object.
  10522. *
  10523. * @tsl
  10524. * @type {Node<vec4>}
  10525. */
  10526. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  10527. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  10528. builder.geometry.computeTangents();
  10529. }
  10530. return attribute( 'tangent', 'vec4' );
  10531. } )();
  10532. /**
  10533. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10534. *
  10535. * @tsl
  10536. * @type {Node<vec3>}
  10537. */
  10538. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10539. /**
  10540. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10541. *
  10542. * @tsl
  10543. * @type {Node<vec3>}
  10544. */
  10545. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10546. let node;
  10547. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10548. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10549. } else {
  10550. node = tangentViewFrame;
  10551. }
  10552. if ( material.flatShading !== true ) {
  10553. node = directionToFaceDirection( node );
  10554. }
  10555. return node;
  10556. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10557. /**
  10558. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10559. *
  10560. * @tsl
  10561. * @type {Node<vec3>}
  10562. */
  10563. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10564. /**
  10565. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10566. *
  10567. * @tsl
  10568. * @private
  10569. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10570. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10571. * @returns {Node<vec3>} The bitangent node.
  10572. */
  10573. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10574. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10575. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10576. bitangent = bitangent.toVarying( varyingName );
  10577. }
  10578. return bitangent;
  10579. } ).once( [ 'NORMAL' ] );
  10580. /**
  10581. * TSL object that represents the bitangent attribute of the current rendered object.
  10582. *
  10583. * @tsl
  10584. * @type {Node<vec3>}
  10585. */
  10586. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10587. /**
  10588. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10589. *
  10590. * @tsl
  10591. * @type {Node<vec3>}
  10592. */
  10593. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10594. /**
  10595. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10596. *
  10597. * @tsl
  10598. * @type {Node<vec3>}
  10599. */
  10600. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10601. let node;
  10602. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10603. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10604. } else {
  10605. node = bitangentViewFrame;
  10606. }
  10607. if ( material.flatShading !== true ) {
  10608. node = directionToFaceDirection( node );
  10609. }
  10610. return node;
  10611. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10612. /**
  10613. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10614. *
  10615. * @tsl
  10616. * @type {Node<vec3>}
  10617. */
  10618. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10619. /**
  10620. * TSL object that represents the TBN matrix in view space.
  10621. *
  10622. * @tsl
  10623. * @type {Node<mat3>}
  10624. */
  10625. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10626. /**
  10627. * TSL object that represents the parallax direction.
  10628. *
  10629. * @tsl
  10630. * @type {Node<mat3>}
  10631. */
  10632. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10633. /**
  10634. * TSL function for computing parallax uv coordinates.
  10635. *
  10636. * @tsl
  10637. * @function
  10638. * @param {Node<vec2>} uv - A uv node.
  10639. * @param {Node<vec2>} scale - A scale node.
  10640. * @returns {Node<vec2>} Parallax uv coordinates.
  10641. */
  10642. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10643. /**
  10644. * TSL function for computing bent normals.
  10645. *
  10646. * @tsl
  10647. * @function
  10648. * @returns {Node<vec3>} Bent normals.
  10649. */
  10650. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10651. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10652. let bentNormal = anisotropyB.cross( positionViewDirection );
  10653. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10654. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10655. return bentNormal;
  10656. } ).once() )();
  10657. /**
  10658. * This class can be used for applying normals maps to materials.
  10659. *
  10660. * ```js
  10661. * material.normalNode = normalMap( texture( normalTex ) );
  10662. * ```
  10663. *
  10664. * @augments TempNode
  10665. */
  10666. class NormalMapNode extends TempNode {
  10667. static get type() {
  10668. return 'NormalMapNode';
  10669. }
  10670. /**
  10671. * Constructs a new normal map node.
  10672. *
  10673. * @param {Node<vec3>} node - Represents the normal map data.
  10674. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10675. */
  10676. constructor( node, scaleNode = null ) {
  10677. super( 'vec3' );
  10678. /**
  10679. * Represents the normal map data.
  10680. *
  10681. * @type {Node<vec3>}
  10682. */
  10683. this.node = node;
  10684. /**
  10685. * Controls the intensity of the effect.
  10686. *
  10687. * @type {?Node<vec2>}
  10688. * @default null
  10689. */
  10690. this.scaleNode = scaleNode;
  10691. /**
  10692. * The normal map type.
  10693. *
  10694. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10695. * @default TangentSpaceNormalMap
  10696. */
  10697. this.normalMapType = TangentSpaceNormalMap;
  10698. }
  10699. setup( { material } ) {
  10700. const { normalMapType, scaleNode } = this;
  10701. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10702. if ( scaleNode !== null ) {
  10703. let scale = scaleNode;
  10704. if ( material.flatShading === true ) {
  10705. scale = directionToFaceDirection( scale );
  10706. }
  10707. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  10708. }
  10709. let output = null;
  10710. if ( normalMapType === ObjectSpaceNormalMap ) {
  10711. output = transformNormalToView( normalMap );
  10712. } else if ( normalMapType === TangentSpaceNormalMap ) {
  10713. output = TBNViewMatrix.mul( normalMap ).normalize();
  10714. } else {
  10715. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  10716. output = normalView; // Fallback to default normal view
  10717. }
  10718. return output;
  10719. }
  10720. }
  10721. /**
  10722. * TSL function for creating a normal map node.
  10723. *
  10724. * @tsl
  10725. * @function
  10726. * @param {Node<vec3>} node - Represents the normal map data.
  10727. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10728. * @returns {NormalMapNode}
  10729. */
  10730. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  10731. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  10732. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  10733. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  10734. // It's used to preserve the same TextureNode instance
  10735. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  10736. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  10737. return vec2(
  10738. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  10739. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  10740. ).mul( bumpScale );
  10741. } );
  10742. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10743. const perturbNormalArb = Fn( ( inputs ) => {
  10744. const { surf_pos, surf_norm, dHdxy } = inputs;
  10745. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  10746. const vSigmaX = surf_pos.dFdx().normalize();
  10747. const vSigmaY = surf_pos.dFdy().normalize();
  10748. const vN = surf_norm; // normalized
  10749. const R1 = vSigmaY.cross( vN );
  10750. const R2 = vN.cross( vSigmaX );
  10751. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  10752. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  10753. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  10754. } );
  10755. /**
  10756. * This class can be used for applying bump maps to materials.
  10757. *
  10758. * ```js
  10759. * material.normalNode = bumpMap( texture( bumpTex ) );
  10760. * ```
  10761. *
  10762. * @augments TempNode
  10763. */
  10764. class BumpMapNode extends TempNode {
  10765. static get type() {
  10766. return 'BumpMapNode';
  10767. }
  10768. /**
  10769. * Constructs a new bump map node.
  10770. *
  10771. * @param {Node<float>} textureNode - Represents the bump map data.
  10772. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10773. */
  10774. constructor( textureNode, scaleNode = null ) {
  10775. super( 'vec3' );
  10776. /**
  10777. * Represents the bump map data.
  10778. *
  10779. * @type {Node<float>}
  10780. */
  10781. this.textureNode = textureNode;
  10782. /**
  10783. * Controls the intensity of the bump effect.
  10784. *
  10785. * @type {?Node<float>}
  10786. * @default null
  10787. */
  10788. this.scaleNode = scaleNode;
  10789. }
  10790. setup() {
  10791. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  10792. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  10793. return perturbNormalArb( {
  10794. surf_pos: positionView,
  10795. surf_norm: normalView,
  10796. dHdxy
  10797. } );
  10798. }
  10799. }
  10800. /**
  10801. * TSL function for creating a bump map node.
  10802. *
  10803. * @tsl
  10804. * @function
  10805. * @param {Node<float>} textureNode - Represents the bump map data.
  10806. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10807. * @returns {BumpMapNode}
  10808. */
  10809. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  10810. const _propertyCache = new Map();
  10811. /**
  10812. * This class should simplify the node access to material properties.
  10813. * It internal uses reference nodes to make sure changes to material
  10814. * properties are automatically reflected to predefined TSL objects
  10815. * like e.g. `materialColor`.
  10816. *
  10817. * @augments Node
  10818. */
  10819. class MaterialNode extends Node {
  10820. static get type() {
  10821. return 'MaterialNode';
  10822. }
  10823. /**
  10824. * Constructs a new material node.
  10825. *
  10826. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  10827. */
  10828. constructor( scope ) {
  10829. super();
  10830. /**
  10831. * The scope defines what material property is referred by the node.
  10832. *
  10833. * @type {string}
  10834. */
  10835. this.scope = scope;
  10836. }
  10837. /**
  10838. * Returns a cached reference node for the given property and type.
  10839. *
  10840. * @param {string} property - The name of the material property.
  10841. * @param {string} type - The uniform type of the property.
  10842. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10843. */
  10844. getCache( property, type ) {
  10845. let node = _propertyCache.get( property );
  10846. if ( node === undefined ) {
  10847. node = materialReference( property, type );
  10848. _propertyCache.set( property, node );
  10849. }
  10850. return node;
  10851. }
  10852. /**
  10853. * Returns a float-typed material reference node for the given property name.
  10854. *
  10855. * @param {string} property - The name of the material property.
  10856. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  10857. */
  10858. getFloat( property ) {
  10859. return this.getCache( property, 'float' );
  10860. }
  10861. /**
  10862. * Returns a color-typed material reference node for the given property name.
  10863. *
  10864. * @param {string} property - The name of the material property.
  10865. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  10866. */
  10867. getColor( property ) {
  10868. return this.getCache( property, 'color' );
  10869. }
  10870. /**
  10871. * Returns a texture-typed material reference node for the given property name.
  10872. *
  10873. * @param {string} property - The name of the material property.
  10874. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10875. */
  10876. getTexture( property ) {
  10877. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  10878. }
  10879. /**
  10880. * The node setup is done depending on the selected scope. Multiple material properties
  10881. * might be grouped into a single node composition if they logically belong together.
  10882. *
  10883. * @param {NodeBuilder} builder - The current node builder.
  10884. * @return {Node} The node representing the selected scope.
  10885. */
  10886. setup( builder ) {
  10887. const material = builder.context.material;
  10888. const scope = this.scope;
  10889. let node = null;
  10890. if ( scope === MaterialNode.COLOR ) {
  10891. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  10892. if ( material.map && material.map.isTexture === true ) {
  10893. node = colorNode.mul( this.getTexture( 'map' ) );
  10894. } else {
  10895. node = colorNode;
  10896. }
  10897. } else if ( scope === MaterialNode.OPACITY ) {
  10898. const opacityNode = this.getFloat( scope );
  10899. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  10900. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  10901. } else {
  10902. node = opacityNode;
  10903. }
  10904. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  10905. if ( material.specularMap && material.specularMap.isTexture === true ) {
  10906. node = this.getTexture( 'specular' ).r;
  10907. } else {
  10908. node = float( 1 );
  10909. }
  10910. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  10911. const specularIntensityNode = this.getFloat( scope );
  10912. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  10913. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  10914. } else {
  10915. node = specularIntensityNode;
  10916. }
  10917. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  10918. const specularColorNode = this.getColor( scope );
  10919. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  10920. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  10921. } else {
  10922. node = specularColorNode;
  10923. }
  10924. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  10925. const roughnessNode = this.getFloat( scope );
  10926. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  10927. node = roughnessNode.mul( this.getTexture( scope ).g );
  10928. } else {
  10929. node = roughnessNode;
  10930. }
  10931. } else if ( scope === MaterialNode.METALNESS ) {
  10932. const metalnessNode = this.getFloat( scope );
  10933. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  10934. node = metalnessNode.mul( this.getTexture( scope ).b );
  10935. } else {
  10936. node = metalnessNode;
  10937. }
  10938. } else if ( scope === MaterialNode.EMISSIVE ) {
  10939. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  10940. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  10941. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  10942. node = emissiveNode.mul( this.getTexture( scope ) );
  10943. } else {
  10944. node = emissiveNode;
  10945. }
  10946. } else if ( scope === MaterialNode.NORMAL ) {
  10947. if ( material.normalMap ) {
  10948. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  10949. node.normalMapType = material.normalMapType;
  10950. } else if ( material.bumpMap ) {
  10951. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  10952. } else {
  10953. node = normalView;
  10954. }
  10955. } else if ( scope === MaterialNode.CLEARCOAT ) {
  10956. const clearcoatNode = this.getFloat( scope );
  10957. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  10958. node = clearcoatNode.mul( this.getTexture( scope ).r );
  10959. } else {
  10960. node = clearcoatNode;
  10961. }
  10962. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  10963. const clearcoatRoughnessNode = this.getFloat( scope );
  10964. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  10965. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  10966. } else {
  10967. node = clearcoatRoughnessNode;
  10968. }
  10969. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  10970. if ( material.clearcoatNormalMap ) {
  10971. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  10972. } else {
  10973. node = normalView;
  10974. }
  10975. } else if ( scope === MaterialNode.SHEEN ) {
  10976. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  10977. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  10978. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  10979. } else {
  10980. node = sheenNode;
  10981. }
  10982. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  10983. const sheenRoughnessNode = this.getFloat( scope );
  10984. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  10985. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  10986. } else {
  10987. node = sheenRoughnessNode;
  10988. }
  10989. node = node.clamp( 0.07, 1.0 );
  10990. } else if ( scope === MaterialNode.ANISOTROPY ) {
  10991. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  10992. const anisotropyPolar = this.getTexture( scope );
  10993. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  10994. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  10995. } else {
  10996. node = materialAnisotropyVector;
  10997. }
  10998. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  10999. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  11000. if ( material.iridescenceThicknessMap ) {
  11001. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  11002. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  11003. } else {
  11004. node = iridescenceThicknessMaximum;
  11005. }
  11006. } else if ( scope === MaterialNode.TRANSMISSION ) {
  11007. const transmissionNode = this.getFloat( scope );
  11008. if ( material.transmissionMap ) {
  11009. node = transmissionNode.mul( this.getTexture( scope ).r );
  11010. } else {
  11011. node = transmissionNode;
  11012. }
  11013. } else if ( scope === MaterialNode.THICKNESS ) {
  11014. const thicknessNode = this.getFloat( scope );
  11015. if ( material.thicknessMap ) {
  11016. node = thicknessNode.mul( this.getTexture( scope ).g );
  11017. } else {
  11018. node = thicknessNode;
  11019. }
  11020. } else if ( scope === MaterialNode.IOR ) {
  11021. node = this.getFloat( scope );
  11022. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  11023. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  11024. } else if ( scope === MaterialNode.AO ) {
  11025. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  11026. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  11027. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  11028. } else {
  11029. const outputType = this.getNodeType( builder );
  11030. node = this.getCache( scope, outputType );
  11031. }
  11032. return node;
  11033. }
  11034. }
  11035. MaterialNode.ALPHA_TEST = 'alphaTest';
  11036. MaterialNode.COLOR = 'color';
  11037. MaterialNode.OPACITY = 'opacity';
  11038. MaterialNode.SHININESS = 'shininess';
  11039. MaterialNode.SPECULAR = 'specular';
  11040. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  11041. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  11042. MaterialNode.SPECULAR_COLOR = 'specularColor';
  11043. MaterialNode.REFLECTIVITY = 'reflectivity';
  11044. MaterialNode.ROUGHNESS = 'roughness';
  11045. MaterialNode.METALNESS = 'metalness';
  11046. MaterialNode.NORMAL = 'normal';
  11047. MaterialNode.CLEARCOAT = 'clearcoat';
  11048. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  11049. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  11050. MaterialNode.EMISSIVE = 'emissive';
  11051. MaterialNode.ROTATION = 'rotation';
  11052. MaterialNode.SHEEN = 'sheen';
  11053. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  11054. MaterialNode.ANISOTROPY = 'anisotropy';
  11055. MaterialNode.IRIDESCENCE = 'iridescence';
  11056. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  11057. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  11058. MaterialNode.IOR = 'ior';
  11059. MaterialNode.TRANSMISSION = 'transmission';
  11060. MaterialNode.THICKNESS = 'thickness';
  11061. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  11062. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  11063. MaterialNode.LINE_SCALE = 'scale';
  11064. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  11065. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  11066. MaterialNode.LINE_WIDTH = 'linewidth';
  11067. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  11068. MaterialNode.POINT_SIZE = 'size';
  11069. MaterialNode.DISPERSION = 'dispersion';
  11070. MaterialNode.LIGHT_MAP = 'light';
  11071. MaterialNode.AO = 'ao';
  11072. /**
  11073. * TSL object that represents alpha test of the current material.
  11074. *
  11075. * @tsl
  11076. * @type {Node<float>}
  11077. */
  11078. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  11079. /**
  11080. * TSL object that represents the diffuse color of the current material.
  11081. * The value is composed via `color` * `map`.
  11082. *
  11083. * @tsl
  11084. * @type {Node<vec3>}
  11085. */
  11086. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  11087. /**
  11088. * TSL object that represents the shininess of the current material.
  11089. *
  11090. * @tsl
  11091. * @type {Node<float>}
  11092. */
  11093. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  11094. /**
  11095. * TSL object that represents the emissive color of the current material.
  11096. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  11097. *
  11098. * @tsl
  11099. * @type {Node<vec3>}
  11100. */
  11101. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  11102. /**
  11103. * TSL object that represents the opacity of the current material.
  11104. * The value is composed via `opacity` * `alphaMap`.
  11105. *
  11106. * @tsl
  11107. * @type {Node<float>}
  11108. */
  11109. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  11110. /**
  11111. * TSL object that represents the specular of the current material.
  11112. *
  11113. * @tsl
  11114. * @type {Node<vec3>}
  11115. */
  11116. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  11117. /**
  11118. * TSL object that represents the specular intensity of the current material.
  11119. * The value is composed via `specularIntensity` * `specularMap.a`.
  11120. *
  11121. * @tsl
  11122. * @type {Node<float>}
  11123. */
  11124. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  11125. /**
  11126. * TSL object that represents the specular color of the current material.
  11127. * The value is composed via `specularColor` * `specularMap.rgb`.
  11128. *
  11129. * @tsl
  11130. * @type {Node<vec3>}
  11131. */
  11132. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  11133. /**
  11134. * TSL object that represents the specular strength of the current material.
  11135. * The value is composed via `specularMap.r`.
  11136. *
  11137. * @tsl
  11138. * @type {Node<float>}
  11139. */
  11140. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  11141. /**
  11142. * TSL object that represents the reflectivity of the current material.
  11143. *
  11144. * @tsl
  11145. * @type {Node<float>}
  11146. */
  11147. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  11148. /**
  11149. * TSL object that represents the roughness of the current material.
  11150. * The value is composed via `roughness` * `roughnessMap.g`.
  11151. *
  11152. * @tsl
  11153. * @type {Node<float>}
  11154. */
  11155. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  11156. /**
  11157. * TSL object that represents the metalness of the current material.
  11158. * The value is composed via `metalness` * `metalnessMap.b`.
  11159. *
  11160. * @tsl
  11161. * @type {Node<float>}
  11162. */
  11163. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  11164. /**
  11165. * TSL object that represents the normal of the current material.
  11166. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  11167. *
  11168. * @tsl
  11169. * @type {Node<vec3>}
  11170. */
  11171. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  11172. /**
  11173. * TSL object that represents the clearcoat of the current material.
  11174. * The value is composed via `clearcoat` * `clearcoatMap.r`
  11175. *
  11176. * @tsl
  11177. * @type {Node<float>}
  11178. */
  11179. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  11180. /**
  11181. * TSL object that represents the clearcoat roughness of the current material.
  11182. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  11183. *
  11184. * @tsl
  11185. * @type {Node<float>}
  11186. */
  11187. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  11188. /**
  11189. * TSL object that represents the clearcoat normal of the current material.
  11190. * The value will be either `clearcoatNormalMap` or `normalView`.
  11191. *
  11192. * @tsl
  11193. * @type {Node<vec3>}
  11194. */
  11195. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  11196. /**
  11197. * TSL object that represents the rotation of the current sprite material.
  11198. *
  11199. * @tsl
  11200. * @type {Node<float>}
  11201. */
  11202. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  11203. /**
  11204. * TSL object that represents the sheen color of the current material.
  11205. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  11206. *
  11207. * @tsl
  11208. * @type {Node<vec3>}
  11209. */
  11210. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  11211. /**
  11212. * TSL object that represents the sheen roughness of the current material.
  11213. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  11214. *
  11215. * @tsl
  11216. * @type {Node<float>}
  11217. */
  11218. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  11219. /**
  11220. * TSL object that represents the anisotropy of the current material.
  11221. *
  11222. * @tsl
  11223. * @type {Node<vec2>}
  11224. */
  11225. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  11226. /**
  11227. * TSL object that represents the iridescence of the current material.
  11228. *
  11229. * @tsl
  11230. * @type {Node<float>}
  11231. */
  11232. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  11233. /**
  11234. * TSL object that represents the iridescence IOR of the current material.
  11235. *
  11236. * @tsl
  11237. * @type {Node<float>}
  11238. */
  11239. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  11240. /**
  11241. * TSL object that represents the iridescence thickness of the current material.
  11242. *
  11243. * @tsl
  11244. * @type {Node<float>}
  11245. */
  11246. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  11247. /**
  11248. * TSL object that represents the transmission of the current material.
  11249. * The value is composed via `transmission` * `transmissionMap.r`.
  11250. *
  11251. * @tsl
  11252. * @type {Node<float>}
  11253. */
  11254. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  11255. /**
  11256. * TSL object that represents the thickness of the current material.
  11257. * The value is composed via `thickness` * `thicknessMap.g`.
  11258. *
  11259. * @tsl
  11260. * @type {Node<float>}
  11261. */
  11262. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  11263. /**
  11264. * TSL object that represents the IOR of the current material.
  11265. *
  11266. * @tsl
  11267. * @type {Node<float>}
  11268. */
  11269. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  11270. /**
  11271. * TSL object that represents the attenuation distance of the current material.
  11272. *
  11273. * @tsl
  11274. * @type {Node<float>}
  11275. */
  11276. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  11277. /**
  11278. * TSL object that represents the attenuation color of the current material.
  11279. *
  11280. * @tsl
  11281. * @type {Node<vec3>}
  11282. */
  11283. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  11284. /**
  11285. * TSL object that represents the scale of the current dashed line material.
  11286. *
  11287. * @tsl
  11288. * @type {Node<float>}
  11289. */
  11290. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  11291. /**
  11292. * TSL object that represents the dash size of the current dashed line material.
  11293. *
  11294. * @tsl
  11295. * @type {Node<float>}
  11296. */
  11297. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  11298. /**
  11299. * TSL object that represents the gap size of the current dashed line material.
  11300. *
  11301. * @tsl
  11302. * @type {Node<float>}
  11303. */
  11304. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  11305. /**
  11306. * TSL object that represents the line width of the current line material.
  11307. *
  11308. * @tsl
  11309. * @type {Node<float>}
  11310. */
  11311. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  11312. /**
  11313. * TSL object that represents the dash offset of the current line material.
  11314. *
  11315. * @tsl
  11316. * @type {Node<float>}
  11317. */
  11318. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  11319. /**
  11320. * TSL object that represents the point size of the current points material.
  11321. *
  11322. * @tsl
  11323. * @type {Node<float>}
  11324. */
  11325. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  11326. /**
  11327. * TSL object that represents the dispersion of the current material.
  11328. *
  11329. * @tsl
  11330. * @type {Node<float>}
  11331. */
  11332. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11333. /**
  11334. * TSL object that represents the light map of the current material.
  11335. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11336. *
  11337. * @tsl
  11338. * @type {Node<vec3>}
  11339. */
  11340. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11341. /**
  11342. * TSL object that represents the ambient occlusion map of the current material.
  11343. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11344. *
  11345. * @tsl
  11346. * @type {Node<float>}
  11347. */
  11348. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11349. /**
  11350. * TSL object that represents the anisotropy vector of the current material.
  11351. *
  11352. * @tsl
  11353. * @type {Node<vec2>}
  11354. */
  11355. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11356. return frame.material;
  11357. } ).onRenderUpdate( function ( { material } ) {
  11358. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11359. } );
  11360. /**
  11361. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11362. *
  11363. * @tsl
  11364. * @type {VaryingNode<vec4>}
  11365. */
  11366. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11367. return builder.context.setupModelViewProjection();
  11368. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11369. /**
  11370. * This class represents shader indices of different types. The following predefined node
  11371. * objects cover frequent use cases:
  11372. *
  11373. * - `vertexIndex`: The index of a vertex within a mesh.
  11374. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  11375. * - `drawIndex`: The index of a draw call.
  11376. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  11377. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  11378. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  11379. *
  11380. * @augments Node
  11381. */
  11382. class IndexNode extends Node {
  11383. static get type() {
  11384. return 'IndexNode';
  11385. }
  11386. /**
  11387. * Constructs a new index node.
  11388. *
  11389. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  11390. */
  11391. constructor( scope ) {
  11392. super( 'uint' );
  11393. /**
  11394. * The scope of the index node.
  11395. *
  11396. * @type {string}
  11397. */
  11398. this.scope = scope;
  11399. /**
  11400. * This flag can be used for type testing.
  11401. *
  11402. * @type {boolean}
  11403. * @readonly
  11404. * @default true
  11405. */
  11406. this.isIndexNode = true;
  11407. }
  11408. generate( builder ) {
  11409. const nodeType = this.getNodeType( builder );
  11410. const scope = this.scope;
  11411. let propertyName;
  11412. if ( scope === IndexNode.VERTEX ) {
  11413. propertyName = builder.getVertexIndex();
  11414. } else if ( scope === IndexNode.INSTANCE ) {
  11415. propertyName = builder.getInstanceIndex();
  11416. } else if ( scope === IndexNode.DRAW ) {
  11417. propertyName = builder.getDrawIndex();
  11418. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  11419. propertyName = builder.getInvocationLocalIndex();
  11420. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  11421. propertyName = builder.getInvocationSubgroupIndex();
  11422. } else if ( scope === IndexNode.SUBGROUP ) {
  11423. propertyName = builder.getSubgroupIndex();
  11424. } else {
  11425. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  11426. }
  11427. let output;
  11428. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  11429. output = propertyName;
  11430. } else {
  11431. const nodeVarying = varying( this );
  11432. output = nodeVarying.build( builder, nodeType );
  11433. }
  11434. return output;
  11435. }
  11436. }
  11437. IndexNode.VERTEX = 'vertex';
  11438. IndexNode.INSTANCE = 'instance';
  11439. IndexNode.SUBGROUP = 'subgroup';
  11440. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  11441. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  11442. IndexNode.DRAW = 'draw';
  11443. /**
  11444. * TSL object that represents the index of a vertex within a mesh.
  11445. *
  11446. * @tsl
  11447. * @type {IndexNode}
  11448. */
  11449. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  11450. /**
  11451. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  11452. *
  11453. * @tsl
  11454. * @type {IndexNode}
  11455. */
  11456. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  11457. /**
  11458. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  11459. *
  11460. * @tsl
  11461. * @type {IndexNode}
  11462. */
  11463. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  11464. /**
  11465. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  11466. *
  11467. * @tsl
  11468. * @type {IndexNode}
  11469. */
  11470. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  11471. /**
  11472. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  11473. *
  11474. * @tsl
  11475. * @type {IndexNode}
  11476. */
  11477. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  11478. /**
  11479. * TSL object that represents the index of a draw call.
  11480. *
  11481. * @tsl
  11482. * @type {IndexNode}
  11483. */
  11484. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  11485. /**
  11486. * This node implements the vertex shader logic which is required
  11487. * when rendering 3D objects via instancing. The code makes sure
  11488. * vertex positions, normals and colors can be modified via instanced
  11489. * data.
  11490. *
  11491. * @augments Node
  11492. */
  11493. class InstanceNode extends Node {
  11494. static get type() {
  11495. return 'InstanceNode';
  11496. }
  11497. /**
  11498. * Constructs a new instance node.
  11499. *
  11500. * @param {number} count - The number of instances.
  11501. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11502. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11503. */
  11504. constructor( count, instanceMatrix, instanceColor = null ) {
  11505. super( 'void' );
  11506. /**
  11507. * The number of instances.
  11508. *
  11509. * @type {number}
  11510. */
  11511. this.count = count;
  11512. /**
  11513. * Instanced buffer attribute representing the transformation of instances.
  11514. *
  11515. * @type {InstancedBufferAttribute}
  11516. */
  11517. this.instanceMatrix = instanceMatrix;
  11518. /**
  11519. * Instanced buffer attribute representing the color of instances.
  11520. *
  11521. * @type {InstancedBufferAttribute}
  11522. */
  11523. this.instanceColor = instanceColor;
  11524. /**
  11525. * The node that represents the instance matrix data.
  11526. *
  11527. * @type {?Node}
  11528. */
  11529. this.instanceMatrixNode = null;
  11530. /**
  11531. * The node that represents the instance color data.
  11532. *
  11533. * @type {?Node}
  11534. * @default null
  11535. */
  11536. this.instanceColorNode = null;
  11537. /**
  11538. * The update type is set to `frame` since an update
  11539. * of instanced buffer data must be checked per frame.
  11540. *
  11541. * @type {string}
  11542. * @default 'frame'
  11543. */
  11544. this.updateType = NodeUpdateType.FRAME;
  11545. /**
  11546. * A reference to a buffer that is used by `instanceMatrixNode`.
  11547. *
  11548. * @type {?InstancedInterleavedBuffer}
  11549. */
  11550. this.buffer = null;
  11551. /**
  11552. * A reference to a buffer that is used by `instanceColorNode`.
  11553. *
  11554. * @type {?InstancedBufferAttribute}
  11555. */
  11556. this.bufferColor = null;
  11557. }
  11558. /**
  11559. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11560. * to predefined node variables for accumulation. That follows the same patterns
  11561. * like with morph and skinning nodes.
  11562. *
  11563. * @param {NodeBuilder} builder - The current node builder.
  11564. */
  11565. setup( builder ) {
  11566. const { instanceMatrix, instanceColor } = this;
  11567. const { count } = instanceMatrix;
  11568. let { instanceMatrixNode, instanceColorNode } = this;
  11569. if ( instanceMatrixNode === null ) {
  11570. // Both WebGPU and WebGL backends have UBO max limited to 64kb. Matrix count number bigger than 1000 ( 16 * 4 * 1000 = 64kb ) will fallback to attribute.
  11571. if ( count <= 1000 ) {
  11572. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  11573. } else {
  11574. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  11575. this.buffer = buffer;
  11576. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11577. const instanceBuffers = [
  11578. // F.Signature -> bufferAttribute( array, type, stride, offset )
  11579. bufferFn( buffer, 'vec4', 16, 0 ),
  11580. bufferFn( buffer, 'vec4', 16, 4 ),
  11581. bufferFn( buffer, 'vec4', 16, 8 ),
  11582. bufferFn( buffer, 'vec4', 16, 12 )
  11583. ];
  11584. instanceMatrixNode = mat4( ...instanceBuffers );
  11585. }
  11586. this.instanceMatrixNode = instanceMatrixNode;
  11587. }
  11588. if ( instanceColor && instanceColorNode === null ) {
  11589. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  11590. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11591. this.bufferColor = buffer;
  11592. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  11593. this.instanceColorNode = instanceColorNode;
  11594. }
  11595. // POSITION
  11596. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  11597. positionLocal.assign( instancePosition );
  11598. // NORMAL
  11599. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11600. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  11601. // ASSIGNS
  11602. normalLocal.assign( instanceNormal );
  11603. }
  11604. // COLOR
  11605. if ( this.instanceColorNode !== null ) {
  11606. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  11607. }
  11608. }
  11609. /**
  11610. * Checks if the internal buffers required an update.
  11611. *
  11612. * @param {NodeFrame} frame - The current node frame.
  11613. */
  11614. update( /*frame*/ ) {
  11615. if ( this.buffer !== null ) {
  11616. // keep update ranges in sync
  11617. this.buffer.clearUpdateRanges();
  11618. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  11619. // update version if necessary
  11620. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMatrix.version !== this.buffer.version ) {
  11621. this.buffer.version = this.instanceMatrix.version;
  11622. }
  11623. }
  11624. if ( this.instanceColor && this.bufferColor !== null ) {
  11625. this.bufferColor.clearUpdateRanges();
  11626. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  11627. if ( this.instanceColor.usage !== DynamicDrawUsage && this.instanceColor.version !== this.bufferColor.version ) {
  11628. this.bufferColor.version = this.instanceColor.version;
  11629. }
  11630. }
  11631. }
  11632. }
  11633. /**
  11634. * TSL function for creating an instance node.
  11635. *
  11636. * @tsl
  11637. * @function
  11638. * @param {number} count - The number of instances.
  11639. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11640. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11641. * @returns {InstanceNode}
  11642. */
  11643. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  11644. /**
  11645. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  11646. * It allows an easier setup of the instance node.
  11647. *
  11648. * @augments InstanceNode
  11649. */
  11650. class InstancedMeshNode extends InstanceNode {
  11651. static get type() {
  11652. return 'InstancedMeshNode';
  11653. }
  11654. /**
  11655. * Constructs a new instanced mesh node.
  11656. *
  11657. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  11658. */
  11659. constructor( instancedMesh ) {
  11660. const { count, instanceMatrix, instanceColor } = instancedMesh;
  11661. super( count, instanceMatrix, instanceColor );
  11662. /**
  11663. * A reference to the instanced mesh.
  11664. *
  11665. * @type {InstancedMesh}
  11666. */
  11667. this.instancedMesh = instancedMesh;
  11668. }
  11669. }
  11670. /**
  11671. * TSL function for creating an instanced mesh node.
  11672. *
  11673. * @tsl
  11674. * @function
  11675. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  11676. * @returns {InstancedMeshNode}
  11677. */
  11678. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  11679. /**
  11680. * This node implements the vertex shader logic which is required
  11681. * when rendering 3D objects via batching. `BatchNode` must be used
  11682. * with instances of {@link BatchedMesh}.
  11683. *
  11684. * @augments Node
  11685. */
  11686. class BatchNode extends Node {
  11687. static get type() {
  11688. return 'BatchNode';
  11689. }
  11690. /**
  11691. * Constructs a new batch node.
  11692. *
  11693. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11694. */
  11695. constructor( batchMesh ) {
  11696. super( 'void' );
  11697. /**
  11698. * A reference to batched mesh.
  11699. *
  11700. * @type {BatchedMesh}
  11701. */
  11702. this.batchMesh = batchMesh;
  11703. /**
  11704. * The batching index node.
  11705. *
  11706. * @type {?IndexNode}
  11707. * @default null
  11708. */
  11709. this.batchingIdNode = null;
  11710. }
  11711. /**
  11712. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11713. * to predefined node variables for accumulation. That follows the same patterns
  11714. * like with morph and skinning nodes.
  11715. *
  11716. * @param {NodeBuilder} builder - The current node builder.
  11717. */
  11718. setup( builder ) {
  11719. if ( this.batchingIdNode === null ) {
  11720. if ( builder.getDrawIndex() === null ) {
  11721. this.batchingIdNode = instanceIndex;
  11722. } else {
  11723. this.batchingIdNode = drawIndex;
  11724. }
  11725. }
  11726. const getIndirectIndex = Fn( ( [ id ] ) => {
  11727. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  11728. const x = int( id ).mod( size );
  11729. const y = int( id ).div( size );
  11730. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  11731. } ).setLayout( {
  11732. name: 'getIndirectIndex',
  11733. type: 'uint',
  11734. inputs: [
  11735. { name: 'id', type: 'int' }
  11736. ]
  11737. } );
  11738. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  11739. const matricesTexture = this.batchMesh._matricesTexture;
  11740. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  11741. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  11742. const x = j.mod( size );
  11743. const y = j.div( size );
  11744. const batchingMatrix = mat4(
  11745. textureLoad( matricesTexture, ivec2( x, y ) ),
  11746. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  11747. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  11748. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  11749. );
  11750. const colorsTexture = this.batchMesh._colorsTexture;
  11751. if ( colorsTexture !== null ) {
  11752. const getBatchingColor = Fn( ( [ id ] ) => {
  11753. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  11754. const j = id;
  11755. const x = j.mod( size );
  11756. const y = j.div( size );
  11757. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  11758. } ).setLayout( {
  11759. name: 'getBatchingColor',
  11760. type: 'vec3',
  11761. inputs: [
  11762. { name: 'id', type: 'int' }
  11763. ]
  11764. } );
  11765. const color = getBatchingColor( indirectId );
  11766. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  11767. }
  11768. const bm = mat3( batchingMatrix );
  11769. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  11770. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  11771. const batchingNormal = bm.mul( transformedNormal ).xyz;
  11772. normalLocal.assign( batchingNormal );
  11773. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11774. tangentLocal.mulAssign( bm );
  11775. }
  11776. }
  11777. }
  11778. /**
  11779. * TSL function for creating a batch node.
  11780. *
  11781. * @tsl
  11782. * @function
  11783. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11784. * @returns {BatchNode}
  11785. */
  11786. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  11787. /**
  11788. * This class enables element access on instances of {@link StorageBufferNode}.
  11789. * In most cases, it is indirectly used when accessing elements with the
  11790. * {@link StorageBufferNode#element} method.
  11791. *
  11792. * ```js
  11793. * const position = positionStorage.element( instanceIndex );
  11794. * ```
  11795. *
  11796. * @augments ArrayElementNode
  11797. */
  11798. class StorageArrayElementNode extends ArrayElementNode {
  11799. static get type() {
  11800. return 'StorageArrayElementNode';
  11801. }
  11802. /**
  11803. * Constructs storage buffer element node.
  11804. *
  11805. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11806. * @param {Node} indexNode - The index node that defines the element access.
  11807. */
  11808. constructor( storageBufferNode, indexNode ) {
  11809. super( storageBufferNode, indexNode );
  11810. /**
  11811. * This flag can be used for type testing.
  11812. *
  11813. * @type {boolean}
  11814. * @readonly
  11815. * @default true
  11816. */
  11817. this.isStorageArrayElementNode = true;
  11818. }
  11819. /**
  11820. * The storage buffer node.
  11821. *
  11822. * @param {Node} value
  11823. * @type {StorageBufferNode}
  11824. */
  11825. set storageBufferNode( value ) {
  11826. this.node = value;
  11827. }
  11828. get storageBufferNode() {
  11829. return this.node;
  11830. }
  11831. getMemberType( builder, name ) {
  11832. const structTypeNode = this.storageBufferNode.structTypeNode;
  11833. if ( structTypeNode ) {
  11834. return structTypeNode.getMemberType( builder, name );
  11835. }
  11836. return 'void';
  11837. }
  11838. setup( builder ) {
  11839. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11840. if ( this.node.isPBO === true ) {
  11841. builder.setupPBO( this.node );
  11842. }
  11843. }
  11844. return super.setup( builder );
  11845. }
  11846. generate( builder, output ) {
  11847. let snippet;
  11848. const isAssignContext = builder.context.assign;
  11849. //
  11850. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11851. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11852. snippet = builder.generatePBO( this );
  11853. } else {
  11854. snippet = this.node.build( builder );
  11855. }
  11856. } else {
  11857. snippet = super.generate( builder );
  11858. }
  11859. if ( isAssignContext !== true ) {
  11860. const type = this.getNodeType( builder );
  11861. snippet = builder.format( snippet, type, output );
  11862. }
  11863. return snippet;
  11864. }
  11865. }
  11866. /**
  11867. * TSL function for creating a storage element node.
  11868. *
  11869. * @tsl
  11870. * @function
  11871. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11872. * @param {Node} indexNode - The index node that defines the element access.
  11873. * @returns {StorageArrayElementNode}
  11874. */
  11875. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11876. /**
  11877. * This node is used in context of compute shaders and allows to define a
  11878. * storage buffer for data. A typical workflow is to create instances of
  11879. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11880. * setup up a compute shader that writes into the buffers and then convert
  11881. * the storage buffers to attribute nodes for rendering.
  11882. *
  11883. * ```js
  11884. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11885. *
  11886. * const computeInit = Fn( () => { // the compute shader
  11887. *
  11888. * const position = positionBuffer.element( instanceIndex );
  11889. *
  11890. * // compute position data
  11891. *
  11892. * position.x = 1;
  11893. * position.y = 1;
  11894. * position.z = 1;
  11895. *
  11896. * } )().compute( particleCount );
  11897. *
  11898. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11899. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11900. *
  11901. * renderer.computeAsync( computeInit );
  11902. *
  11903. * ```
  11904. *
  11905. * @augments BufferNode
  11906. */
  11907. class StorageBufferNode extends BufferNode {
  11908. static get type() {
  11909. return 'StorageBufferNode';
  11910. }
  11911. /**
  11912. * Constructs a new storage buffer node.
  11913. *
  11914. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11915. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11916. * @param {number} [bufferCount=0] - The buffer count.
  11917. */
  11918. constructor( value, bufferType = null, bufferCount = 0 ) {
  11919. let nodeType, structTypeNode = null;
  11920. if ( bufferType && bufferType.isStruct ) {
  11921. nodeType = 'struct';
  11922. structTypeNode = bufferType.layout;
  11923. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11924. bufferCount = value.count;
  11925. }
  11926. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11927. nodeType = getTypeFromLength( value.itemSize );
  11928. bufferCount = value.count;
  11929. } else {
  11930. nodeType = bufferType;
  11931. }
  11932. super( value, nodeType, bufferCount );
  11933. /**
  11934. * This flag can be used for type testing.
  11935. *
  11936. * @type {boolean}
  11937. * @readonly
  11938. * @default true
  11939. */
  11940. this.isStorageBufferNode = true;
  11941. /**
  11942. * The buffer struct type.
  11943. *
  11944. * @type {?StructTypeNode}
  11945. * @default null
  11946. */
  11947. this.structTypeNode = structTypeNode;
  11948. /**
  11949. * The access type of the texture node.
  11950. *
  11951. * @type {string}
  11952. * @default 'readWrite'
  11953. */
  11954. this.access = NodeAccess.READ_WRITE;
  11955. /**
  11956. * Whether the node is atomic or not.
  11957. *
  11958. * @type {boolean}
  11959. * @default false
  11960. */
  11961. this.isAtomic = false;
  11962. /**
  11963. * Whether the node represents a PBO or not.
  11964. * Only relevant for WebGL.
  11965. *
  11966. * @type {boolean}
  11967. * @default false
  11968. */
  11969. this.isPBO = false;
  11970. /**
  11971. * A reference to the internal buffer attribute node.
  11972. *
  11973. * @type {?BufferAttributeNode}
  11974. * @default null
  11975. */
  11976. this._attribute = null;
  11977. /**
  11978. * A reference to the internal varying node.
  11979. *
  11980. * @type {?VaryingNode}
  11981. * @default null
  11982. */
  11983. this._varying = null;
  11984. /**
  11985. * `StorageBufferNode` sets this property to `true` by default.
  11986. *
  11987. * @type {boolean}
  11988. * @default true
  11989. */
  11990. this.global = true;
  11991. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11992. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11993. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11994. else value.isStorageBufferAttribute = true;
  11995. }
  11996. }
  11997. /**
  11998. * This method is overwritten since the buffer data might be shared
  11999. * and thus the hash should be shared as well.
  12000. *
  12001. * @param {NodeBuilder} builder - The current node builder.
  12002. * @return {string} The hash.
  12003. */
  12004. getHash( builder ) {
  12005. if ( this.bufferCount === 0 ) {
  12006. let bufferData = builder.globalCache.getData( this.value );
  12007. if ( bufferData === undefined ) {
  12008. bufferData = {
  12009. node: this
  12010. };
  12011. builder.globalCache.setData( this.value, bufferData );
  12012. }
  12013. return bufferData.node.uuid;
  12014. }
  12015. return this.uuid;
  12016. }
  12017. /**
  12018. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  12019. *
  12020. * @param {NodeBuilder} builder - The current node builder.
  12021. * @return {string} The input type.
  12022. */
  12023. getInputType( /*builder*/ ) {
  12024. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  12025. }
  12026. /**
  12027. * Enables element access with the given index node.
  12028. *
  12029. * @param {IndexNode} indexNode - The index node.
  12030. * @return {StorageArrayElementNode} A node representing the element access.
  12031. */
  12032. element( indexNode ) {
  12033. return storageElement( this, indexNode );
  12034. }
  12035. /**
  12036. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  12037. *
  12038. * @param {boolean} value - The value so set.
  12039. * @return {StorageBufferNode} A reference to this node.
  12040. */
  12041. setPBO( value ) {
  12042. this.isPBO = value;
  12043. return this;
  12044. }
  12045. /**
  12046. * Returns the `isPBO` value.
  12047. *
  12048. * @return {boolean} Whether the node represents a PBO or not.
  12049. */
  12050. getPBO() {
  12051. return this.isPBO;
  12052. }
  12053. /**
  12054. * Defines the node access.
  12055. *
  12056. * @param {string} value - The node access.
  12057. * @return {StorageBufferNode} A reference to this node.
  12058. */
  12059. setAccess( value ) {
  12060. this.access = value;
  12061. return this;
  12062. }
  12063. /**
  12064. * Convenience method for configuring a read-only node access.
  12065. *
  12066. * @return {StorageBufferNode} A reference to this node.
  12067. */
  12068. toReadOnly() {
  12069. return this.setAccess( NodeAccess.READ_ONLY );
  12070. }
  12071. /**
  12072. * Defines whether the node is atomic or not.
  12073. *
  12074. * @param {boolean} value - The atomic flag.
  12075. * @return {StorageBufferNode} A reference to this node.
  12076. */
  12077. setAtomic( value ) {
  12078. this.isAtomic = value;
  12079. return this;
  12080. }
  12081. /**
  12082. * Convenience method for making this node atomic.
  12083. *
  12084. * @return {StorageBufferNode} A reference to this node.
  12085. */
  12086. toAtomic() {
  12087. return this.setAtomic( true );
  12088. }
  12089. /**
  12090. * Returns attribute data for this storage buffer node.
  12091. *
  12092. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  12093. */
  12094. getAttributeData() {
  12095. if ( this._attribute === null ) {
  12096. this._attribute = bufferAttribute( this.value );
  12097. this._varying = varying( this._attribute );
  12098. }
  12099. return {
  12100. attribute: this._attribute,
  12101. varying: this._varying
  12102. };
  12103. }
  12104. /**
  12105. * This method is overwritten since the node type from the availability of storage buffers
  12106. * and the attribute data.
  12107. *
  12108. * @param {NodeBuilder} builder - The current node builder.
  12109. * @return {string} The node type.
  12110. */
  12111. getNodeType( builder ) {
  12112. if ( this.structTypeNode !== null ) {
  12113. return this.structTypeNode.getNodeType( builder );
  12114. }
  12115. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12116. return super.getNodeType( builder );
  12117. }
  12118. const { attribute } = this.getAttributeData();
  12119. return attribute.getNodeType( builder );
  12120. }
  12121. /**
  12122. * Returns the type of a member of the struct.
  12123. *
  12124. * @param {NodeBuilder} builder - The current node builder.
  12125. * @param {string} name - The name of the member.
  12126. * @return {string} The type of the member.
  12127. */
  12128. getMemberType( builder, name ) {
  12129. if ( this.structTypeNode !== null ) {
  12130. return this.structTypeNode.getMemberType( builder, name );
  12131. }
  12132. return 'void';
  12133. }
  12134. /**
  12135. * Generates the code snippet of the storage buffer node.
  12136. *
  12137. * @param {NodeBuilder} builder - The current node builder.
  12138. * @return {string} The generated code snippet.
  12139. */
  12140. generate( builder ) {
  12141. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  12142. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12143. return super.generate( builder );
  12144. }
  12145. const { attribute, varying } = this.getAttributeData();
  12146. const output = varying.build( builder );
  12147. builder.registerTransform( output, attribute );
  12148. return output;
  12149. }
  12150. }
  12151. /**
  12152. * TSL function for creating a storage buffer node.
  12153. *
  12154. * @tsl
  12155. * @function
  12156. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12157. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  12158. * @param {number} [count=0] - The buffer count.
  12159. * @returns {StorageBufferNode}
  12160. */
  12161. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  12162. /**
  12163. * @tsl
  12164. * @function
  12165. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  12166. *
  12167. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12168. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  12169. * @param {number} count - The buffer count.
  12170. * @returns {StorageBufferNode}
  12171. */
  12172. const storageObject = ( value, type, count ) => { // @deprecated, r171
  12173. warn( 'TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  12174. return storage( value, type, count ).setPBO( true );
  12175. };
  12176. const _frameId = new WeakMap();
  12177. /**
  12178. * This node implements the vertex transformation shader logic which is required
  12179. * for skinning/skeletal animation.
  12180. *
  12181. * @augments Node
  12182. */
  12183. class SkinningNode extends Node {
  12184. static get type() {
  12185. return 'SkinningNode';
  12186. }
  12187. /**
  12188. * Constructs a new skinning node.
  12189. *
  12190. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12191. */
  12192. constructor( skinnedMesh ) {
  12193. super( 'void' );
  12194. /**
  12195. * The skinned mesh.
  12196. *
  12197. * @type {SkinnedMesh}
  12198. */
  12199. this.skinnedMesh = skinnedMesh;
  12200. /**
  12201. * The update type overwritten since skinning nodes are updated per object.
  12202. *
  12203. * @type {string}
  12204. */
  12205. this.updateType = NodeUpdateType.OBJECT;
  12206. //
  12207. /**
  12208. * The skin index attribute.
  12209. *
  12210. * @type {AttributeNode}
  12211. */
  12212. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  12213. /**
  12214. * The skin weight attribute.
  12215. *
  12216. * @type {AttributeNode}
  12217. */
  12218. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  12219. /**
  12220. * The bind matrix node.
  12221. *
  12222. * @type {Node<mat4>}
  12223. */
  12224. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  12225. /**
  12226. * The bind matrix inverse node.
  12227. *
  12228. * @type {Node<mat4>}
  12229. */
  12230. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  12231. /**
  12232. * The bind matrices as a uniform buffer node.
  12233. *
  12234. * @type {Node}
  12235. */
  12236. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12237. /**
  12238. * The current vertex position in local space.
  12239. *
  12240. * @type {Node<vec3>}
  12241. */
  12242. this.positionNode = positionLocal;
  12243. /**
  12244. * The result of vertex position in local space.
  12245. *
  12246. * @type {Node<vec3>}
  12247. */
  12248. this.toPositionNode = positionLocal;
  12249. /**
  12250. * The previous bind matrices as a uniform buffer node.
  12251. * Required for computing motion vectors.
  12252. *
  12253. * @type {?Node}
  12254. * @default null
  12255. */
  12256. this.previousBoneMatricesNode = null;
  12257. }
  12258. /**
  12259. * Transforms the given vertex position via skinning.
  12260. *
  12261. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12262. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  12263. * @return {Node<vec3>} The transformed vertex position.
  12264. */
  12265. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  12266. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12267. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12268. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12269. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12270. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12271. // POSITION
  12272. const skinVertex = bindMatrixNode.mul( position );
  12273. const skinned = add(
  12274. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  12275. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  12276. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  12277. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  12278. );
  12279. return bindMatrixInverseNode.mul( skinned ).xyz;
  12280. }
  12281. /**
  12282. * Transforms the given vertex normal via skinning.
  12283. *
  12284. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12285. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  12286. * @return {Node<vec3>} The transformed vertex normal.
  12287. */
  12288. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  12289. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12290. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12291. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12292. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12293. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12294. // NORMAL
  12295. let skinMatrix = add(
  12296. skinWeightNode.x.mul( boneMatX ),
  12297. skinWeightNode.y.mul( boneMatY ),
  12298. skinWeightNode.z.mul( boneMatZ ),
  12299. skinWeightNode.w.mul( boneMatW )
  12300. );
  12301. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  12302. return skinMatrix.transformDirection( normal ).xyz;
  12303. }
  12304. /**
  12305. * Computes the transformed/skinned vertex position of the previous frame.
  12306. *
  12307. * @param {NodeBuilder} builder - The current node builder.
  12308. * @return {Node<vec3>} The skinned position from the previous frame.
  12309. */
  12310. getPreviousSkinnedPosition( builder ) {
  12311. const skinnedMesh = builder.object;
  12312. if ( this.previousBoneMatricesNode === null ) {
  12313. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  12314. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12315. }
  12316. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  12317. }
  12318. /**
  12319. * Returns `true` if bone matrices from the previous frame are required. Relevant
  12320. * when computing motion vectors with {@link VelocityNode}.
  12321. *
  12322. * @param {NodeBuilder} builder - The current node builder.
  12323. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  12324. */
  12325. needsPreviousBoneMatrices( builder ) {
  12326. const mrt = builder.renderer.getMRT();
  12327. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  12328. }
  12329. /**
  12330. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  12331. *
  12332. * @param {NodeBuilder} builder - The current node builder.
  12333. * @return {Node<vec3>} The transformed vertex position.
  12334. */
  12335. setup( builder ) {
  12336. if ( this.needsPreviousBoneMatrices( builder ) ) {
  12337. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  12338. }
  12339. const skinPosition = this.getSkinnedPosition();
  12340. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12341. //
  12342. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12343. const skinNormal = this.getSkinnedNormal();
  12344. normalLocal.assign( skinNormal );
  12345. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12346. tangentLocal.assign( skinNormal );
  12347. }
  12348. }
  12349. return skinPosition;
  12350. }
  12351. /**
  12352. * Generates the code snippet of the skinning node.
  12353. *
  12354. * @param {NodeBuilder} builder - The current node builder.
  12355. * @param {string} output - The current output.
  12356. * @return {string} The generated code snippet.
  12357. */
  12358. generate( builder, output ) {
  12359. if ( output !== 'void' ) {
  12360. return super.generate( builder, output );
  12361. }
  12362. }
  12363. /**
  12364. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12365. *
  12366. * @param {NodeFrame} frame - The current node frame.
  12367. */
  12368. update( frame ) {
  12369. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12370. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12371. _frameId.set( skeleton, frame.frameId );
  12372. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12373. skeleton.update();
  12374. }
  12375. }
  12376. /**
  12377. * TSL function for creating a skinning node.
  12378. *
  12379. * @tsl
  12380. * @function
  12381. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12382. * @returns {SkinningNode}
  12383. */
  12384. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  12385. /**
  12386. * TSL function for computing skinning.
  12387. *
  12388. * @tsl
  12389. * @function
  12390. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12391. * @param {Node<vec3>} [toPosition=null] - The target position.
  12392. * @returns {SkinningNode}
  12393. */
  12394. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12395. const node = new SkinningNode( skinnedMesh );
  12396. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12397. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12398. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12399. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12400. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12401. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12402. node.toPositionNode = toPosition;
  12403. return nodeObject( node );
  12404. };
  12405. /**
  12406. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12407. * ```js
  12408. * Loop( count, ( { i } ) => {
  12409. *
  12410. * } );
  12411. * ```
  12412. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12413. * ```js
  12414. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12415. *
  12416. * } );
  12417. *```
  12418. * Nested loops can be defined in a compacted form:
  12419. * ```js
  12420. * Loop( 10, 5, ( { i, j } ) => {
  12421. *
  12422. * } );
  12423. * ```
  12424. * Loops that should run backwards can be defined like so:
  12425. * ```js
  12426. * Loop( { start: 10 }, () => {} );
  12427. * ```
  12428. * It is possible to execute with boolean values, similar to the `while` syntax.
  12429. * ```js
  12430. * const value = float( 0 ).toVar();
  12431. *
  12432. * Loop( value.lessThan( 10 ), () => {
  12433. *
  12434. * value.addAssign( 1 );
  12435. *
  12436. * } );
  12437. * ```
  12438. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  12439. * @augments Node
  12440. */
  12441. class LoopNode extends Node {
  12442. static get type() {
  12443. return 'LoopNode';
  12444. }
  12445. /**
  12446. * Constructs a new loop node.
  12447. *
  12448. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  12449. */
  12450. constructor( params = [] ) {
  12451. super();
  12452. this.params = params;
  12453. }
  12454. /**
  12455. * Returns a loop variable name based on an index. The pattern is
  12456. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  12457. *
  12458. * @param {number} index - The index.
  12459. * @return {string} The loop variable name.
  12460. */
  12461. getVarName( index ) {
  12462. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  12463. }
  12464. /**
  12465. * Returns properties about this node.
  12466. *
  12467. * @param {NodeBuilder} builder - The current node builder.
  12468. * @return {Object} The node properties.
  12469. */
  12470. getProperties( builder ) {
  12471. const properties = builder.getNodeProperties( this );
  12472. if ( properties.stackNode !== undefined ) return properties;
  12473. //
  12474. const inputs = {};
  12475. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12476. const param = this.params[ i ];
  12477. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12478. const type = ( param.isNode !== true && param.type ) || 'int';
  12479. inputs[ name ] = expression( name, type );
  12480. }
  12481. const stack = builder.addStack(); // TODO: cache() it
  12482. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  12483. properties.stackNode = stack;
  12484. const baseParam = this.params[ 0 ];
  12485. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12486. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  12487. }
  12488. builder.removeStack();
  12489. return properties;
  12490. }
  12491. /**
  12492. * This method is overwritten since the node type is inferred based on the loop configuration.
  12493. *
  12494. * @param {NodeBuilder} builder - The current node builder.
  12495. * @return {string} The node type.
  12496. */
  12497. getNodeType( builder ) {
  12498. const { returnsNode } = this.getProperties( builder );
  12499. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  12500. }
  12501. setup( builder ) {
  12502. // setup properties
  12503. this.getProperties( builder );
  12504. if ( builder.fnCall ) {
  12505. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  12506. shaderNodeData.hasLoop = true;
  12507. }
  12508. }
  12509. generate( builder ) {
  12510. const properties = this.getProperties( builder );
  12511. const params = this.params;
  12512. const stackNode = properties.stackNode;
  12513. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12514. const param = params[ i ];
  12515. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12516. if ( param.isNode ) {
  12517. if ( param.getNodeType( builder ) === 'bool' ) {
  12518. isWhile = true;
  12519. type = 'bool';
  12520. end = param.build( builder, type );
  12521. } else {
  12522. type = 'int';
  12523. name = this.getVarName( i );
  12524. start = '0';
  12525. end = param.build( builder, type );
  12526. condition = '<';
  12527. }
  12528. } else {
  12529. type = param.type || 'int';
  12530. name = param.name || this.getVarName( i );
  12531. start = param.start;
  12532. end = param.end;
  12533. condition = param.condition;
  12534. update = param.update;
  12535. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12536. else if ( start && start.isNode ) start = start.build( builder, type );
  12537. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12538. else if ( end && end.isNode ) end = end.build( builder, type );
  12539. if ( start !== undefined && end === undefined ) {
  12540. start = start + ' - 1';
  12541. end = '0';
  12542. condition = '>=';
  12543. } else if ( end !== undefined && start === undefined ) {
  12544. start = '0';
  12545. condition = '<';
  12546. }
  12547. if ( condition === undefined ) {
  12548. if ( Number( start ) > Number( end ) ) {
  12549. condition = '>=';
  12550. } else {
  12551. condition = '<';
  12552. }
  12553. }
  12554. }
  12555. let loopSnippet;
  12556. if ( isWhile ) {
  12557. loopSnippet = `while ( ${ end } )`;
  12558. } else {
  12559. const internalParam = { start, end};
  12560. //
  12561. const startSnippet = internalParam.start;
  12562. const endSnippet = internalParam.end;
  12563. let updateSnippet;
  12564. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12565. if ( update !== undefined && update !== null ) {
  12566. switch ( typeof update ) {
  12567. case 'function':
  12568. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12569. const snippet = flow.code.replace( /\t|;/g, '' );
  12570. updateSnippet = snippet;
  12571. break;
  12572. case 'number':
  12573. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12574. break;
  12575. case 'string':
  12576. updateSnippet = name + ' ' + update;
  12577. break;
  12578. default:
  12579. if ( update.isNode ) {
  12580. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12581. } else {
  12582. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12583. updateSnippet = 'break /* invalid update */';
  12584. }
  12585. }
  12586. } else {
  12587. if ( type === 'int' || type === 'uint' ) {
  12588. update = condition.includes( '<' ) ? '++' : '--';
  12589. } else {
  12590. update = deltaOperator() + ' 1.';
  12591. }
  12592. updateSnippet = name + ' ' + update;
  12593. }
  12594. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12595. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12596. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12597. }
  12598. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12599. }
  12600. const stackSnippet = stackNode.build( builder, 'void' );
  12601. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  12602. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12603. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12604. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12605. }
  12606. builder.addFlowTab();
  12607. return returnsSnippet;
  12608. }
  12609. }
  12610. /**
  12611. * TSL function for creating a loop node.
  12612. *
  12613. * @tsl
  12614. * @function
  12615. * @param {...any} params - A list of parameters.
  12616. * @returns {LoopNode}
  12617. */
  12618. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  12619. /**
  12620. * TSL function for creating a `Continue()` expression.
  12621. *
  12622. * @tsl
  12623. * @function
  12624. * @returns {ExpressionNode}
  12625. */
  12626. const Continue = () => expression( 'continue' ).toStack();
  12627. /**
  12628. * TSL function for creating a `Break()` expression.
  12629. *
  12630. * @tsl
  12631. * @function
  12632. * @returns {ExpressionNode}
  12633. */
  12634. const Break = () => expression( 'break' ).toStack();
  12635. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12636. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12637. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12638. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12639. const y = texelIndex.div( width );
  12640. const x = texelIndex.sub( y.mul( width ) );
  12641. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12642. return bufferAttrib.mul( influence );
  12643. } );
  12644. function getEntry( geometry ) {
  12645. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12646. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12647. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12648. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12649. // into an array of data textures. Each layer represents a single morph target.
  12650. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12651. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12652. let entry = _morphTextures.get( geometry );
  12653. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12654. if ( entry !== undefined ) entry.texture.dispose();
  12655. const morphTargets = geometry.morphAttributes.position || [];
  12656. const morphNormals = geometry.morphAttributes.normal || [];
  12657. const morphColors = geometry.morphAttributes.color || [];
  12658. let vertexDataCount = 0;
  12659. if ( hasMorphPosition === true ) vertexDataCount = 1;
  12660. if ( hasMorphNormals === true ) vertexDataCount = 2;
  12661. if ( hasMorphColors === true ) vertexDataCount = 3;
  12662. let width = geometry.attributes.position.count * vertexDataCount;
  12663. let height = 1;
  12664. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  12665. if ( width > maxTextureSize ) {
  12666. height = Math.ceil( width / maxTextureSize );
  12667. width = maxTextureSize;
  12668. }
  12669. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  12670. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  12671. bufferTexture.type = FloatType;
  12672. bufferTexture.needsUpdate = true;
  12673. // fill buffer
  12674. const vertexDataStride = vertexDataCount * 4;
  12675. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  12676. const morphTarget = morphTargets[ i ];
  12677. const morphNormal = morphNormals[ i ];
  12678. const morphColor = morphColors[ i ];
  12679. const offset = width * height * 4 * i;
  12680. for ( let j = 0; j < morphTarget.count; j ++ ) {
  12681. const stride = j * vertexDataStride;
  12682. if ( hasMorphPosition === true ) {
  12683. _morphVec4.fromBufferAttribute( morphTarget, j );
  12684. buffer[ offset + stride + 0 ] = _morphVec4.x;
  12685. buffer[ offset + stride + 1 ] = _morphVec4.y;
  12686. buffer[ offset + stride + 2 ] = _morphVec4.z;
  12687. buffer[ offset + stride + 3 ] = 0;
  12688. }
  12689. if ( hasMorphNormals === true ) {
  12690. _morphVec4.fromBufferAttribute( morphNormal, j );
  12691. buffer[ offset + stride + 4 ] = _morphVec4.x;
  12692. buffer[ offset + stride + 5 ] = _morphVec4.y;
  12693. buffer[ offset + stride + 6 ] = _morphVec4.z;
  12694. buffer[ offset + stride + 7 ] = 0;
  12695. }
  12696. if ( hasMorphColors === true ) {
  12697. _morphVec4.fromBufferAttribute( morphColor, j );
  12698. buffer[ offset + stride + 8 ] = _morphVec4.x;
  12699. buffer[ offset + stride + 9 ] = _morphVec4.y;
  12700. buffer[ offset + stride + 10 ] = _morphVec4.z;
  12701. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  12702. }
  12703. }
  12704. }
  12705. entry = {
  12706. count: morphTargetsCount,
  12707. texture: bufferTexture,
  12708. stride: vertexDataCount,
  12709. size: new Vector2( width, height )
  12710. };
  12711. _morphTextures.set( geometry, entry );
  12712. function disposeTexture() {
  12713. bufferTexture.dispose();
  12714. _morphTextures.delete( geometry );
  12715. geometry.removeEventListener( 'dispose', disposeTexture );
  12716. }
  12717. geometry.addEventListener( 'dispose', disposeTexture );
  12718. }
  12719. return entry;
  12720. }
  12721. /**
  12722. * This node implements the vertex transformation shader logic which is required
  12723. * for morph target animation.
  12724. *
  12725. * @augments Node
  12726. */
  12727. class MorphNode extends Node {
  12728. static get type() {
  12729. return 'MorphNode';
  12730. }
  12731. /**
  12732. * Constructs a new morph node.
  12733. *
  12734. * @param {Mesh} mesh - The mesh holding the morph targets.
  12735. */
  12736. constructor( mesh ) {
  12737. super( 'void' );
  12738. /**
  12739. * The mesh holding the morph targets.
  12740. *
  12741. * @type {Mesh}
  12742. */
  12743. this.mesh = mesh;
  12744. /**
  12745. * A uniform node which represents the morph base influence value.
  12746. *
  12747. * @type {UniformNode<float>}
  12748. */
  12749. this.morphBaseInfluence = uniform( 1 );
  12750. /**
  12751. * The update type overwritten since morph nodes are updated per object.
  12752. *
  12753. * @type {string}
  12754. */
  12755. this.updateType = NodeUpdateType.OBJECT;
  12756. }
  12757. /**
  12758. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  12759. *
  12760. * @param {NodeBuilder} builder - The current node builder.
  12761. */
  12762. setup( builder ) {
  12763. const { geometry } = builder;
  12764. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12765. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  12766. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12767. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12768. // nodes
  12769. const { texture: bufferMap, stride, size } = getEntry( geometry );
  12770. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  12771. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  12772. const width = int( size.width );
  12773. Loop( morphTargetsCount, ( { i } ) => {
  12774. const influence = float( 0 ).toVar();
  12775. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  12776. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  12777. } else {
  12778. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  12779. }
  12780. If( influence.notEqual( 0 ), () => {
  12781. if ( hasMorphPosition === true ) {
  12782. positionLocal.addAssign( getMorph( {
  12783. bufferMap,
  12784. influence,
  12785. stride,
  12786. width,
  12787. depth: i,
  12788. offset: int( 0 )
  12789. } ) );
  12790. }
  12791. if ( hasMorphNormals === true ) {
  12792. normalLocal.addAssign( getMorph( {
  12793. bufferMap,
  12794. influence,
  12795. stride,
  12796. width,
  12797. depth: i,
  12798. offset: int( 1 )
  12799. } ) );
  12800. }
  12801. } );
  12802. } );
  12803. }
  12804. /**
  12805. * Updates the state of the morphed mesh by updating the base influence.
  12806. *
  12807. * @param {NodeFrame} frame - The current node frame.
  12808. */
  12809. update( /*frame*/ ) {
  12810. const morphBaseInfluence = this.morphBaseInfluence;
  12811. if ( this.mesh.geometry.morphTargetsRelative ) {
  12812. morphBaseInfluence.value = 1;
  12813. } else {
  12814. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  12815. }
  12816. }
  12817. }
  12818. /**
  12819. * TSL function for creating a morph node.
  12820. *
  12821. * @tsl
  12822. * @function
  12823. * @param {Mesh} mesh - The mesh holding the morph targets.
  12824. * @returns {MorphNode}
  12825. */
  12826. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  12827. /**
  12828. * Base class for lighting nodes.
  12829. *
  12830. * @augments Node
  12831. */
  12832. class LightingNode extends Node {
  12833. static get type() {
  12834. return 'LightingNode';
  12835. }
  12836. /**
  12837. * Constructs a new lighting node.
  12838. */
  12839. constructor() {
  12840. super( 'vec3' );
  12841. /**
  12842. * This flag can be used for type testing.
  12843. *
  12844. * @type {boolean}
  12845. * @readonly
  12846. * @default true
  12847. */
  12848. this.isLightingNode = true;
  12849. }
  12850. }
  12851. /**
  12852. * A generic class that can be used by nodes which contribute
  12853. * ambient occlusion to the scene. E.g. an ambient occlusion map
  12854. * node can be used as input for this module. Used in {@link NodeMaterial}.
  12855. *
  12856. * @augments LightingNode
  12857. */
  12858. class AONode extends LightingNode {
  12859. static get type() {
  12860. return 'AONode';
  12861. }
  12862. /**
  12863. * Constructs a new AO node.
  12864. *
  12865. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  12866. */
  12867. constructor( aoNode = null ) {
  12868. super();
  12869. /**
  12870. * The ambient occlusion node.
  12871. *
  12872. * @type {?Node<float>}
  12873. * @default null
  12874. */
  12875. this.aoNode = aoNode;
  12876. }
  12877. setup( builder ) {
  12878. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  12879. }
  12880. }
  12881. /**
  12882. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  12883. * by adding lighting specific context data. It represents the runtime context of
  12884. * {@link LightsNode}.
  12885. *
  12886. * @augments ContextNode
  12887. */
  12888. class LightingContextNode extends ContextNode {
  12889. static get type() {
  12890. return 'LightingContextNode';
  12891. }
  12892. /**
  12893. * Constructs a new lighting context node.
  12894. *
  12895. * @param {LightsNode} lightsNode - The lights node.
  12896. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  12897. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  12898. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  12899. */
  12900. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  12901. super( lightsNode );
  12902. /**
  12903. * The current lighting model.
  12904. *
  12905. * @type {?LightingModel}
  12906. * @default null
  12907. */
  12908. this.lightingModel = lightingModel;
  12909. /**
  12910. * A backdrop node.
  12911. *
  12912. * @type {?Node<vec3>}
  12913. * @default null
  12914. */
  12915. this.backdropNode = backdropNode;
  12916. /**
  12917. * A backdrop alpha node.
  12918. *
  12919. * @type {?Node<float>}
  12920. * @default null
  12921. */
  12922. this.backdropAlphaNode = backdropAlphaNode;
  12923. this._value = null;
  12924. }
  12925. /**
  12926. * Returns a lighting context object.
  12927. *
  12928. * @return {{
  12929. * radiance: Node<vec3>,
  12930. * irradiance: Node<vec3>,
  12931. * iblIrradiance: Node<vec3>,
  12932. * ambientOcclusion: Node<float>,
  12933. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  12934. * backdrop: Node<vec3>,
  12935. * backdropAlpha: Node<float>
  12936. * }} The lighting context object.
  12937. */
  12938. getContext() {
  12939. const { backdropNode, backdropAlphaNode } = this;
  12940. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  12941. directSpecular = vec3().toVar( 'directSpecular' ),
  12942. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  12943. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  12944. const reflectedLight = {
  12945. directDiffuse,
  12946. directSpecular,
  12947. indirectDiffuse,
  12948. indirectSpecular
  12949. };
  12950. const context = {
  12951. radiance: vec3().toVar( 'radiance' ),
  12952. irradiance: vec3().toVar( 'irradiance' ),
  12953. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  12954. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  12955. reflectedLight,
  12956. backdrop: backdropNode,
  12957. backdropAlpha: backdropAlphaNode
  12958. };
  12959. return context;
  12960. }
  12961. setup( builder ) {
  12962. this.value = this._value || ( this._value = this.getContext() );
  12963. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  12964. return super.setup( builder );
  12965. }
  12966. }
  12967. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  12968. /**
  12969. * A generic class that can be used by nodes which contribute
  12970. * irradiance to the scene. E.g. a light map node can be used
  12971. * as input for this module. Used in {@link NodeMaterial}.
  12972. *
  12973. * @augments LightingNode
  12974. */
  12975. class IrradianceNode extends LightingNode {
  12976. static get type() {
  12977. return 'IrradianceNode';
  12978. }
  12979. /**
  12980. * Constructs a new irradiance node.
  12981. *
  12982. * @param {Node<vec3>} node - A node contributing irradiance.
  12983. */
  12984. constructor( node ) {
  12985. super();
  12986. /**
  12987. * A node contributing irradiance.
  12988. *
  12989. * @type {Node<vec3>}
  12990. */
  12991. this.node = node;
  12992. }
  12993. setup( builder ) {
  12994. builder.context.irradiance.addAssign( this.node );
  12995. }
  12996. }
  12997. const _size$5 = /*@__PURE__*/ new Vector2();
  12998. /**
  12999. * A special type of texture node which represents the data of the current viewport
  13000. * as a texture. The module extracts data from the current bound framebuffer with
  13001. * a copy operation so no extra render pass is required to produce the texture data
  13002. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13003. * variety of effects like refractive or transmissive materials.
  13004. *
  13005. * @augments TextureNode
  13006. */
  13007. class ViewportTextureNode extends TextureNode {
  13008. static get type() {
  13009. return 'ViewportTextureNode';
  13010. }
  13011. /**
  13012. * Constructs a new viewport texture node.
  13013. *
  13014. * @param {Node} [uvNode=screenUV] - The uv node.
  13015. * @param {?Node} [levelNode=null] - The level node.
  13016. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13017. */
  13018. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13019. let defaultFramebuffer = null;
  13020. if ( framebufferTexture === null ) {
  13021. defaultFramebuffer = new FramebufferTexture();
  13022. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13023. framebufferTexture = defaultFramebuffer;
  13024. } else {
  13025. defaultFramebuffer = framebufferTexture;
  13026. }
  13027. super( framebufferTexture, uvNode, levelNode );
  13028. /**
  13029. * Whether to generate mipmaps or not.
  13030. *
  13031. * @type {boolean}
  13032. * @default false
  13033. */
  13034. this.generateMipmaps = false;
  13035. /**
  13036. * The reference framebuffer texture. This is used to store the framebuffer texture
  13037. * for the current render target. If the render target changes, a new framebuffer texture
  13038. * is created automatically.
  13039. *
  13040. * @type {FramebufferTexture}
  13041. * @default null
  13042. */
  13043. this.defaultFramebuffer = defaultFramebuffer;
  13044. /**
  13045. * This flag can be used for type testing.
  13046. *
  13047. * @type {boolean}
  13048. * @readonly
  13049. * @default true
  13050. */
  13051. this.isOutputTextureNode = true;
  13052. /**
  13053. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  13054. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  13055. *
  13056. * @type {string}
  13057. * @default 'frame'
  13058. */
  13059. this.updateBeforeType = NodeUpdateType.FRAME;
  13060. /**
  13061. * The framebuffer texture for the current renderer context.
  13062. *
  13063. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13064. * @private
  13065. */
  13066. this._cacheTextures = new WeakMap();
  13067. }
  13068. /**
  13069. * This methods returns a texture for the given render target reference.
  13070. *
  13071. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13072. * for different render contexts.
  13073. *
  13074. * @param {?RenderTarget} [reference=null] - The render target reference.
  13075. * @return {Texture} The framebuffer texture.
  13076. */
  13077. getTextureForReference( reference = null ) {
  13078. let defaultFramebuffer;
  13079. let cacheTextures;
  13080. if ( this.referenceNode ) {
  13081. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13082. cacheTextures = this.referenceNode._cacheTextures;
  13083. } else {
  13084. defaultFramebuffer = this.defaultFramebuffer;
  13085. cacheTextures = this._cacheTextures;
  13086. }
  13087. if ( reference === null ) {
  13088. return defaultFramebuffer;
  13089. }
  13090. if ( cacheTextures.has( reference ) === false ) {
  13091. const framebufferTexture = defaultFramebuffer.clone();
  13092. cacheTextures.set( reference, framebufferTexture );
  13093. }
  13094. return cacheTextures.get( reference );
  13095. }
  13096. updateReference( frame ) {
  13097. const renderTarget = frame.renderer.getRenderTarget();
  13098. this.value = this.getTextureForReference( renderTarget );
  13099. return this.value;
  13100. }
  13101. updateBefore( frame ) {
  13102. const renderer = frame.renderer;
  13103. const renderTarget = renderer.getRenderTarget();
  13104. if ( renderTarget === null ) {
  13105. renderer.getDrawingBufferSize( _size$5 );
  13106. } else {
  13107. _size$5.set( renderTarget.width, renderTarget.height );
  13108. }
  13109. //
  13110. const framebufferTexture = this.getTextureForReference( renderTarget );
  13111. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  13112. framebufferTexture.image.width = _size$5.width;
  13113. framebufferTexture.image.height = _size$5.height;
  13114. framebufferTexture.needsUpdate = true;
  13115. }
  13116. //
  13117. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  13118. framebufferTexture.generateMipmaps = this.generateMipmaps;
  13119. renderer.copyFramebufferToTexture( framebufferTexture );
  13120. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  13121. }
  13122. clone() {
  13123. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  13124. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  13125. return viewportTextureNode;
  13126. }
  13127. }
  13128. /**
  13129. * TSL function for creating a viewport texture node.
  13130. *
  13131. * @tsl
  13132. * @function
  13133. * @param {?Node} [uvNode=screenUV] - The uv node.
  13134. * @param {?Node} [levelNode=null] - The level node.
  13135. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13136. * @returns {ViewportTextureNode}
  13137. */
  13138. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  13139. /**
  13140. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13141. *
  13142. * @tsl
  13143. * @function
  13144. * @param {?Node} [uvNode=screenUV] - The uv node.
  13145. * @param {?Node} [levelNode=null] - The level node.
  13146. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13147. * @returns {ViewportTextureNode}
  13148. */
  13149. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  13150. let _sharedDepthbuffer = null;
  13151. /**
  13152. * Represents the depth of the current viewport as a texture. This module
  13153. * can be used in combination with viewport texture to achieve effects
  13154. * that require depth evaluation.
  13155. *
  13156. * @augments ViewportTextureNode
  13157. */
  13158. class ViewportDepthTextureNode extends ViewportTextureNode {
  13159. static get type() {
  13160. return 'ViewportDepthTextureNode';
  13161. }
  13162. /**
  13163. * Constructs a new viewport depth texture node.
  13164. *
  13165. * @param {Node} [uvNode=screenUV] - The uv node.
  13166. * @param {?Node} [levelNode=null] - The level node.
  13167. */
  13168. constructor( uvNode = screenUV, levelNode = null ) {
  13169. if ( _sharedDepthbuffer === null ) {
  13170. _sharedDepthbuffer = new DepthTexture();
  13171. }
  13172. super( uvNode, levelNode, _sharedDepthbuffer );
  13173. }
  13174. /**
  13175. * Overwritten so the method always returns the unique shared
  13176. * depth texture.
  13177. *
  13178. * @return {DepthTexture} The shared depth texture.
  13179. */
  13180. getTextureForReference() {
  13181. return _sharedDepthbuffer;
  13182. }
  13183. }
  13184. /**
  13185. * TSL function for a viewport depth texture node.
  13186. *
  13187. * @tsl
  13188. * @function
  13189. * @param {?Node} [uvNode=screenUV] - The uv node.
  13190. * @param {?Node} [levelNode=null] - The level node.
  13191. * @returns {ViewportDepthTextureNode}
  13192. */
  13193. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  13194. /**
  13195. * This node offers a collection of features in context of the depth logic in the fragment shader.
  13196. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  13197. * fragment or for depth evaluation purposes.
  13198. *
  13199. * @augments Node
  13200. */
  13201. class ViewportDepthNode extends Node {
  13202. static get type() {
  13203. return 'ViewportDepthNode';
  13204. }
  13205. /**
  13206. * Constructs a new viewport depth node.
  13207. *
  13208. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  13209. * @param {?Node} [valueNode=null] - The value node.
  13210. */
  13211. constructor( scope, valueNode = null ) {
  13212. super( 'float' );
  13213. /**
  13214. * The node behaves differently depending on which scope is selected.
  13215. *
  13216. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  13217. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  13218. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  13219. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  13220. *
  13221. * @type {('depth'|'depthBase'|'linearDepth')}
  13222. */
  13223. this.scope = scope;
  13224. /**
  13225. * Can be used to define a custom depth value.
  13226. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  13227. *
  13228. * @type {?Node}
  13229. * @default null
  13230. */
  13231. this.valueNode = valueNode;
  13232. /**
  13233. * This flag can be used for type testing.
  13234. *
  13235. * @type {boolean}
  13236. * @readonly
  13237. * @default true
  13238. */
  13239. this.isViewportDepthNode = true;
  13240. }
  13241. generate( builder ) {
  13242. const { scope } = this;
  13243. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13244. return builder.getFragDepth();
  13245. }
  13246. return super.generate( builder );
  13247. }
  13248. setup( { camera } ) {
  13249. const { scope } = this;
  13250. const value = this.valueNode;
  13251. let node = null;
  13252. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13253. if ( value !== null ) {
  13254. node = depthBase().assign( value );
  13255. }
  13256. } else if ( scope === ViewportDepthNode.DEPTH ) {
  13257. if ( camera.isPerspectiveCamera ) {
  13258. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  13259. } else {
  13260. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13261. }
  13262. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  13263. if ( value !== null ) {
  13264. if ( camera.isPerspectiveCamera ) {
  13265. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  13266. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  13267. } else {
  13268. node = value;
  13269. }
  13270. } else {
  13271. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13272. }
  13273. }
  13274. return node;
  13275. }
  13276. }
  13277. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  13278. ViewportDepthNode.DEPTH = 'depth';
  13279. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  13280. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  13281. /**
  13282. * TSL function for converting a viewZ value to an orthographic depth value.
  13283. *
  13284. * @tsl
  13285. * @function
  13286. * @param {Node<float>} viewZ - The viewZ node.
  13287. * @param {Node<float>} near - The camera's near value.
  13288. * @param {Node<float>} far - The camera's far value.
  13289. * @returns {Node<float>}
  13290. */
  13291. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  13292. /**
  13293. * TSL function for converting an orthographic depth value to a viewZ value.
  13294. *
  13295. * @tsl
  13296. * @function
  13297. * @param {Node<float>} depth - The orthographic depth.
  13298. * @param {Node<float>} near - The camera's near value.
  13299. * @param {Node<float>} far - The camera's far value.
  13300. * @returns {Node<float>}
  13301. */
  13302. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  13303. /**
  13304. * TSL function for converting a viewZ value to a perspective depth value.
  13305. *
  13306. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  13307. *
  13308. * @tsl
  13309. * @function
  13310. * @param {Node<float>} viewZ - The viewZ node.
  13311. * @param {Node<float>} near - The camera's near value.
  13312. * @param {Node<float>} far - The camera's far value.
  13313. * @returns {Node<float>}
  13314. */
  13315. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  13316. /**
  13317. * TSL function for converting a perspective depth value to a viewZ value.
  13318. *
  13319. * @tsl
  13320. * @function
  13321. * @param {Node<float>} depth - The perspective depth.
  13322. * @param {Node<float>} near - The camera's near value.
  13323. * @param {Node<float>} far - The camera's far value.
  13324. * @returns {Node<float>}
  13325. */
  13326. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  13327. /**
  13328. * TSL function for converting a viewZ value to a logarithmic depth value.
  13329. *
  13330. * @tsl
  13331. * @function
  13332. * @param {Node<float>} viewZ - The viewZ node.
  13333. * @param {Node<float>} near - The camera's near value.
  13334. * @param {Node<float>} far - The camera's far value.
  13335. * @returns {Node<float>}
  13336. */
  13337. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  13338. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  13339. // The final logarithmic depth formula used here is adapted from one described in an
  13340. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  13341. // which was an improvement upon an earlier formula one described in an
  13342. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13343. // Ulrich's formula is the following:
  13344. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13345. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13346. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13347. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13348. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13349. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13350. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13351. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13352. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13353. // Outerra eventually made another improvement to their original "C-constant" variant,
  13354. // but it still does not incorporate the camera near plane (for this version,
  13355. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13356. // Here we make 4 changes to Ulrich's formula:
  13357. // 1. Clamp the camera near plane so we don't divide by 0.
  13358. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13359. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13360. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13361. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13362. // so we do the same here, hence the 'viewZ.negate()' call.
  13363. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13364. near = near.max( 1e-6 ).toVar();
  13365. const numerator = log2( viewZ.negate().div( near ) );
  13366. const denominator = log2( far.div( near ) );
  13367. return numerator.div( denominator );
  13368. };
  13369. /**
  13370. * TSL function for converting a logarithmic depth value to a viewZ value.
  13371. *
  13372. * @tsl
  13373. * @function
  13374. * @param {Node<float>} depth - The logarithmic depth.
  13375. * @param {Node<float>} near - The camera's near value.
  13376. * @param {Node<float>} far - The camera's far value.
  13377. * @returns {Node<float>}
  13378. */
  13379. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  13380. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13381. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13382. // a negative viewZ).
  13383. const exponent = depth.mul( log( far.div( near ) ) );
  13384. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13385. };
  13386. /**
  13387. * TSL function for defining a value for the current fragment's depth.
  13388. *
  13389. * @tsl
  13390. * @function
  13391. * @param {Node<float>} value - The depth value to set.
  13392. * @returns {ViewportDepthNode<float>}
  13393. */
  13394. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13395. /**
  13396. * TSL object that represents the depth value for the current fragment.
  13397. *
  13398. * @tsl
  13399. * @type {ViewportDepthNode}
  13400. */
  13401. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13402. /**
  13403. * TSL function for converting a perspective depth value to linear depth.
  13404. *
  13405. * @tsl
  13406. * @function
  13407. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13408. * @returns {ViewportDepthNode<float>}
  13409. */
  13410. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13411. /**
  13412. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13413. *
  13414. * @tsl
  13415. * @type {ViewportDepthNode}
  13416. */
  13417. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  13418. depth.assign = ( value ) => depthBase( value );
  13419. /**
  13420. * This node is used in {@link NodeMaterial} to setup the clipping
  13421. * which can happen hardware-accelerated (if supported) and optionally
  13422. * use alpha-to-coverage for anti-aliasing clipped edges.
  13423. *
  13424. * @augments Node
  13425. */
  13426. class ClippingNode extends Node {
  13427. static get type() {
  13428. return 'ClippingNode';
  13429. }
  13430. /**
  13431. * Constructs a new clipping node.
  13432. *
  13433. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  13434. * the selected scope influences the behavior of the node and what type of code is generated.
  13435. */
  13436. constructor( scope = ClippingNode.DEFAULT ) {
  13437. super();
  13438. /**
  13439. * The node's scope. Similar to other nodes, the selected scope influences
  13440. * the behavior of the node and what type of code is generated.
  13441. *
  13442. * @type {('default'|'hardware'|'alphaToCoverage')}
  13443. */
  13444. this.scope = scope;
  13445. }
  13446. /**
  13447. * Setups the node depending on the selected scope.
  13448. *
  13449. * @param {NodeBuilder} builder - The current node builder.
  13450. * @return {Node} The result node.
  13451. */
  13452. setup( builder ) {
  13453. super.setup( builder );
  13454. const clippingContext = builder.clippingContext;
  13455. const { intersectionPlanes, unionPlanes } = clippingContext;
  13456. this.hardwareClipping = builder.material.hardwareClipping;
  13457. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  13458. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  13459. } else if ( this.scope === ClippingNode.HARDWARE ) {
  13460. return this.setupHardwareClipping( unionPlanes, builder );
  13461. } else {
  13462. return this.setupDefault( intersectionPlanes, unionPlanes );
  13463. }
  13464. }
  13465. /**
  13466. * Setups alpha to coverage.
  13467. *
  13468. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13469. * @param {Array<Vector4>} unionPlanes - The union planes.
  13470. * @return {Node} The result node.
  13471. */
  13472. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13473. return Fn( () => {
  13474. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13475. const distanceGradient = float().toVar( 'distanceToGradient' );
  13476. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13477. const numUnionPlanes = unionPlanes.length;
  13478. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13479. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13480. Loop( numUnionPlanes, ( { i } ) => {
  13481. const plane = clippingPlanes.element( i );
  13482. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13483. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13484. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13485. } );
  13486. }
  13487. const numIntersectionPlanes = intersectionPlanes.length;
  13488. if ( numIntersectionPlanes > 0 ) {
  13489. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13490. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13491. Loop( numIntersectionPlanes, ( { i } ) => {
  13492. const plane = clippingPlanes.element( i );
  13493. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13494. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13495. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13496. } );
  13497. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13498. }
  13499. diffuseColor.a.mulAssign( clipOpacity );
  13500. diffuseColor.a.equal( 0.0 ).discard();
  13501. } )();
  13502. }
  13503. /**
  13504. * Setups the default clipping.
  13505. *
  13506. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13507. * @param {Array<Vector4>} unionPlanes - The union planes.
  13508. * @return {Node} The result node.
  13509. */
  13510. setupDefault( intersectionPlanes, unionPlanes ) {
  13511. return Fn( () => {
  13512. const numUnionPlanes = unionPlanes.length;
  13513. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13514. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13515. Loop( numUnionPlanes, ( { i } ) => {
  13516. const plane = clippingPlanes.element( i );
  13517. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13518. } );
  13519. }
  13520. const numIntersectionPlanes = intersectionPlanes.length;
  13521. if ( numIntersectionPlanes > 0 ) {
  13522. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13523. const clipped = bool( true ).toVar( 'clipped' );
  13524. Loop( numIntersectionPlanes, ( { i } ) => {
  13525. const plane = clippingPlanes.element( i );
  13526. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13527. } );
  13528. clipped.discard();
  13529. }
  13530. } )();
  13531. }
  13532. /**
  13533. * Setups hardware clipping.
  13534. *
  13535. * @param {Array<Vector4>} unionPlanes - The union planes.
  13536. * @param {NodeBuilder} builder - The current node builder.
  13537. * @return {Node} The result node.
  13538. */
  13539. setupHardwareClipping( unionPlanes, builder ) {
  13540. const numUnionPlanes = unionPlanes.length;
  13541. builder.enableHardwareClipping( numUnionPlanes );
  13542. return Fn( () => {
  13543. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13544. const hw_clip_distances = builtin( builder.getClipDistance() );
  13545. Loop( numUnionPlanes, ( { i } ) => {
  13546. const plane = clippingPlanes.element( i );
  13547. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13548. hw_clip_distances.element( i ).assign( distance );
  13549. } );
  13550. } )();
  13551. }
  13552. }
  13553. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13554. ClippingNode.DEFAULT = 'default';
  13555. ClippingNode.HARDWARE = 'hardware';
  13556. /**
  13557. * TSL function for setting up the default clipping logic.
  13558. *
  13559. * @tsl
  13560. * @function
  13561. * @returns {ClippingNode}
  13562. */
  13563. const clipping = () => nodeObject( new ClippingNode() );
  13564. /**
  13565. * TSL function for setting up alpha to coverage.
  13566. *
  13567. * @tsl
  13568. * @function
  13569. * @returns {ClippingNode}
  13570. */
  13571. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  13572. /**
  13573. * TSL function for setting up hardware-based clipping.
  13574. *
  13575. * @tsl
  13576. * @function
  13577. * @returns {ClippingNode}
  13578. */
  13579. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  13580. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13581. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13582. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13583. 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 ) ) ) ) ) );
  13584. } );
  13585. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13586. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13587. } );
  13588. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13589. // Find the discretized derivatives of our coordinates
  13590. const maxDeriv = max$1(
  13591. length( dFdx( position.xyz ) ),
  13592. length( dFdy( position.xyz ) )
  13593. );
  13594. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13595. // Find two nearest log-discretized noise scales
  13596. const pixScales = vec2(
  13597. exp2( floor( log2( pixScale ) ) ),
  13598. exp2( ceil( log2( pixScale ) ) )
  13599. );
  13600. // Compute alpha thresholds at our two noise scales
  13601. const alpha = vec2(
  13602. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13603. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13604. );
  13605. // Factor to interpolate lerp with
  13606. const lerpFactor = fract( log2( pixScale ) );
  13607. // Interpolate alpha threshold from noise at two scales
  13608. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13609. // Pass into CDF to compute uniformly distrib threshold
  13610. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13611. const cases = vec3(
  13612. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13613. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13614. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13615. // Find our final, uniformly distributed alpha threshold (ατ)
  13616. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13617. // Avoids ατ == 0. Could also do ατ =1-ατ
  13618. return clamp( threshold, 1.0e-6, 1.0 );
  13619. } ).setLayout( {
  13620. name: 'getAlphaHashThreshold',
  13621. type: 'float',
  13622. inputs: [
  13623. { name: 'position', type: 'vec3' }
  13624. ]
  13625. } );
  13626. /**
  13627. * An attribute node for representing vertex colors.
  13628. *
  13629. * @augments AttributeNode
  13630. */
  13631. class VertexColorNode extends AttributeNode {
  13632. static get type() {
  13633. return 'VertexColorNode';
  13634. }
  13635. /**
  13636. * Constructs a new vertex color node.
  13637. *
  13638. * @param {number} index - The attribute index.
  13639. */
  13640. constructor( index ) {
  13641. super( null, 'vec4' );
  13642. /**
  13643. * This flag can be used for type testing.
  13644. *
  13645. * @type {boolean}
  13646. * @readonly
  13647. * @default true
  13648. */
  13649. this.isVertexColorNode = true;
  13650. /**
  13651. * The attribute index to enable more than one sets of vertex colors.
  13652. *
  13653. * @type {number}
  13654. * @default 0
  13655. */
  13656. this.index = index;
  13657. }
  13658. /**
  13659. * Overwrites the default implementation by honoring the attribute index.
  13660. *
  13661. * @param {NodeBuilder} builder - The current node builder.
  13662. * @return {string} The attribute name.
  13663. */
  13664. getAttributeName( /*builder*/ ) {
  13665. const index = this.index;
  13666. return 'color' + ( index > 0 ? index : '' );
  13667. }
  13668. generate( builder ) {
  13669. const attributeName = this.getAttributeName( builder );
  13670. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13671. let result;
  13672. if ( geometryAttribute === true ) {
  13673. result = super.generate( builder );
  13674. } else {
  13675. // Vertex color fallback should be white
  13676. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13677. }
  13678. return result;
  13679. }
  13680. serialize( data ) {
  13681. super.serialize( data );
  13682. data.index = this.index;
  13683. }
  13684. deserialize( data ) {
  13685. super.deserialize( data );
  13686. this.index = data.index;
  13687. }
  13688. }
  13689. /**
  13690. * TSL function for creating a reference node.
  13691. *
  13692. * @tsl
  13693. * @function
  13694. * @param {number} [index=0] - The attribute index.
  13695. * @returns {VertexColorNode}
  13696. */
  13697. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  13698. /**
  13699. * Represents a "Color Burn" blend mode.
  13700. *
  13701. * It's designed to darken the base layer's colors based on the color of the blend layer.
  13702. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  13703. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  13704. *
  13705. * @tsl
  13706. * @function
  13707. * @param {Node<vec3>} base - The base color.
  13708. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  13709. * @return {Node<vec3>} The result.
  13710. */
  13711. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13712. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13713. } ).setLayout( {
  13714. name: 'blendBurn',
  13715. type: 'vec3',
  13716. inputs: [
  13717. { name: 'base', type: 'vec3' },
  13718. { name: 'blend', type: 'vec3' }
  13719. ]
  13720. } );
  13721. /**
  13722. * Represents a "Color Dodge" blend mode.
  13723. *
  13724. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  13725. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  13726. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  13727. *
  13728. * @tsl
  13729. * @function
  13730. * @param {Node<vec3>} base - The base color.
  13731. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13732. * @return {Node<vec3>} The result.
  13733. */
  13734. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13735. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13736. } ).setLayout( {
  13737. name: 'blendDodge',
  13738. type: 'vec3',
  13739. inputs: [
  13740. { name: 'base', type: 'vec3' },
  13741. { name: 'blend', type: 'vec3' }
  13742. ]
  13743. } );
  13744. /**
  13745. * Represents a "Screen" blend mode.
  13746. *
  13747. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  13748. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  13749. * effects.
  13750. *
  13751. * @tsl
  13752. * @function
  13753. * @param {Node<vec3>} base - The base color.
  13754. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13755. * @return {Node<vec3>} The result.
  13756. */
  13757. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13758. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13759. } ).setLayout( {
  13760. name: 'blendScreen',
  13761. type: 'vec3',
  13762. inputs: [
  13763. { name: 'base', type: 'vec3' },
  13764. { name: 'blend', type: 'vec3' }
  13765. ]
  13766. } );
  13767. /**
  13768. * Represents a "Overlay" blend mode.
  13769. *
  13770. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  13771. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  13772. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  13773. *
  13774. * @tsl
  13775. * @function
  13776. * @param {Node<vec3>} base - The base color.
  13777. * @param {Node<vec3>} blend - The blend color
  13778. * @return {Node<vec3>} The result.
  13779. */
  13780. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13781. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13782. } ).setLayout( {
  13783. name: 'blendOverlay',
  13784. type: 'vec3',
  13785. inputs: [
  13786. { name: 'base', type: 'vec3' },
  13787. { name: 'blend', type: 'vec3' }
  13788. ]
  13789. } );
  13790. /**
  13791. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  13792. * It assumes both input colors have non-premultiplied alpha.
  13793. *
  13794. * @tsl
  13795. * @function
  13796. * @param {Node<vec4>} base - The base color.
  13797. * @param {Node<vec4>} blend - The blend color
  13798. * @return {Node<vec4>} The result.
  13799. */
  13800. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13801. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13802. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13803. } ).setLayout( {
  13804. name: 'blendColor',
  13805. type: 'vec4',
  13806. inputs: [
  13807. { name: 'base', type: 'vec4' },
  13808. { name: 'blend', type: 'vec4' }
  13809. ]
  13810. } );
  13811. /**
  13812. * Premultiplies the RGB channels of a color by its alpha channel.
  13813. *
  13814. * This function is useful for converting a non-premultiplied alpha color
  13815. * into a premultiplied alpha format, where the RGB values are scaled
  13816. * by the alpha value. Premultiplied alpha is often used in graphics
  13817. * rendering for certain operations, such as compositing and image processing.
  13818. *
  13819. * @tsl
  13820. * @function
  13821. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  13822. * @return {Node<vec4>} The color with premultiplied alpha.
  13823. */
  13824. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13825. return vec4( color.rgb.mul( color.a ), color.a );
  13826. }, { color: 'vec4', return: 'vec4' } );
  13827. /**
  13828. * Unpremultiplies the RGB channels of a color by its alpha channel.
  13829. *
  13830. * This function is useful for converting a premultiplied alpha color
  13831. * back into a non-premultiplied alpha format, where the RGB values are
  13832. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  13833. * rendering for certain operations, such as compositing and image processing.
  13834. *
  13835. * @tsl
  13836. * @function
  13837. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  13838. * @return {Node<vec4>} The color with non-premultiplied alpha.
  13839. */
  13840. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13841. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  13842. return vec4( color.rgb.div( color.a ), color.a );
  13843. }, { color: 'vec4', return: 'vec4' } );
  13844. // Deprecated
  13845. /**
  13846. * @tsl
  13847. * @function
  13848. * @deprecated since r171. Use {@link blendBurn} instead.
  13849. *
  13850. * @param {...any} params
  13851. * @returns {Function}
  13852. */
  13853. const burn = ( ...params ) => { // @deprecated, r171
  13854. warn( 'TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13855. return blendBurn( params );
  13856. };
  13857. /**
  13858. * @tsl
  13859. * @function
  13860. * @deprecated since r171. Use {@link blendDodge} instead.
  13861. *
  13862. * @param {...any} params
  13863. * @returns {Function}
  13864. */
  13865. const dodge = ( ...params ) => { // @deprecated, r171
  13866. warn( 'TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13867. return blendDodge( params );
  13868. };
  13869. /**
  13870. * @tsl
  13871. * @function
  13872. * @deprecated since r171. Use {@link blendScreen} instead.
  13873. *
  13874. * @param {...any} params
  13875. * @returns {Function}
  13876. */
  13877. const screen = ( ...params ) => { // @deprecated, r171
  13878. warn( 'TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  13879. return blendScreen( params );
  13880. };
  13881. /**
  13882. * @tsl
  13883. * @function
  13884. * @deprecated since r171. Use {@link blendOverlay} instead.
  13885. *
  13886. * @param {...any} params
  13887. * @returns {Function}
  13888. */
  13889. const overlay = ( ...params ) => { // @deprecated, r171
  13890. warn( 'TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  13891. return blendOverlay( params );
  13892. };
  13893. /**
  13894. * Base class for all node materials.
  13895. *
  13896. * @augments Material
  13897. */
  13898. class NodeMaterial extends Material {
  13899. static get type() {
  13900. return 'NodeMaterial';
  13901. }
  13902. /**
  13903. * Represents the type of the node material.
  13904. *
  13905. * @type {string}
  13906. */
  13907. get type() {
  13908. return this.constructor.type;
  13909. }
  13910. set type( _value ) { /* */ }
  13911. /**
  13912. * Constructs a new node material.
  13913. */
  13914. constructor() {
  13915. super();
  13916. /**
  13917. * This flag can be used for type testing.
  13918. *
  13919. * @type {boolean}
  13920. * @readonly
  13921. * @default true
  13922. */
  13923. this.isNodeMaterial = true;
  13924. /**
  13925. * Whether this material is affected by fog or not.
  13926. *
  13927. * @type {boolean}
  13928. * @default true
  13929. */
  13930. this.fog = true;
  13931. /**
  13932. * Whether this material is affected by lights or not.
  13933. *
  13934. * @type {boolean}
  13935. * @default false
  13936. */
  13937. this.lights = false;
  13938. /**
  13939. * Whether this material uses hardware clipping or not.
  13940. * This property is managed by the engine and should not be
  13941. * modified by apps.
  13942. *
  13943. * @type {boolean}
  13944. * @default false
  13945. */
  13946. this.hardwareClipping = false;
  13947. /**
  13948. * Node materials which set their `lights` property to `true`
  13949. * are affected by all lights of the scene. Sometimes selective
  13950. * lighting is wanted which means only _some_ lights in the scene
  13951. * affect a material. This can be achieved by creating an instance
  13952. * of {@link LightsNode} with a list of selective
  13953. * lights and assign the node to this property.
  13954. *
  13955. * ```js
  13956. * const customLightsNode = lights( [ light1, light2 ] );
  13957. * material.lightsNode = customLightsNode;
  13958. * ```
  13959. *
  13960. * @type {?LightsNode}
  13961. * @default null
  13962. */
  13963. this.lightsNode = null;
  13964. /**
  13965. * The environment of node materials can be defined by an environment
  13966. * map assigned to the `envMap` property or by `Scene.environment`
  13967. * if the node material is a PBR material. This node property allows to overwrite
  13968. * the default behavior and define the environment with a custom node.
  13969. *
  13970. * ```js
  13971. * material.envNode = pmremTexture( renderTarget.texture );
  13972. * ```
  13973. *
  13974. * @type {?Node<vec3>}
  13975. * @default null
  13976. */
  13977. this.envNode = null;
  13978. /**
  13979. * The lighting of node materials might be influenced by ambient occlusion.
  13980. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  13981. * and the respective `aoMapIntensity`. This node property allows to overwrite
  13982. * the default and define the ambient occlusion with a custom node instead.
  13983. *
  13984. * If you don't want to overwrite the diffuse color but modify the existing
  13985. * values instead, use {@link materialAO}.
  13986. *
  13987. * @type {?Node<float>}
  13988. * @default null
  13989. */
  13990. this.aoNode = null;
  13991. /**
  13992. * The diffuse color of node materials is by default inferred from the
  13993. * `color` and `map` properties. This node property allows to overwrite the default
  13994. * and define the diffuse color with a node instead.
  13995. *
  13996. * ```js
  13997. * material.colorNode = color( 0xff0000 ); // define red color
  13998. * ```
  13999. *
  14000. * If you don't want to overwrite the diffuse color but modify the existing
  14001. * values instead, use {@link materialColor}.
  14002. *
  14003. * ```js
  14004. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14005. * ```
  14006. *
  14007. * @type {?Node<vec3>}
  14008. * @default null
  14009. */
  14010. this.colorNode = null;
  14011. /**
  14012. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14013. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14014. * and define the normals with a node instead.
  14015. *
  14016. * If you don't want to overwrite the normals but modify the existing values instead,
  14017. * use {@link materialNormal}.
  14018. *
  14019. * @type {?Node<vec3>}
  14020. * @default null
  14021. */
  14022. this.normalNode = null;
  14023. /**
  14024. * The opacity of node materials is by default inferred from the `opacity`
  14025. * and `alphaMap` properties. This node property allows to overwrite the default
  14026. * and define the opacity with a node instead.
  14027. *
  14028. * If you don't want to overwrite the normals but modify the existing
  14029. * value instead, use {@link materialOpacity}.
  14030. *
  14031. * @type {?Node<float>}
  14032. * @default null
  14033. */
  14034. this.opacityNode = null;
  14035. /**
  14036. * This node can be used to implement a variety of filter-like effects. The idea is
  14037. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14038. * to create an arbitrary effect and then assign the node composition to this property.
  14039. * Everything behind the object using this material will now be affected by a filter.
  14040. *
  14041. * ```js
  14042. * const material = new NodeMaterial()
  14043. * material.transparent = true;
  14044. *
  14045. * // everything behind the object will be monochromatic
  14046. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14047. * ```
  14048. *
  14049. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14050. *
  14051. * @type {?Node<vec3>}
  14052. * @default null
  14053. */
  14054. this.backdropNode = null;
  14055. /**
  14056. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14057. *
  14058. * @type {?Node<float>}
  14059. * @default null
  14060. */
  14061. this.backdropAlphaNode = null;
  14062. /**
  14063. * The alpha test of node materials is by default inferred from the `alphaTest`
  14064. * property. This node property allows to overwrite the default and define the
  14065. * alpha test with a node instead.
  14066. *
  14067. * If you don't want to overwrite the alpha test but modify the existing
  14068. * value instead, use {@link materialAlphaTest}.
  14069. *
  14070. * @type {?Node<float>}
  14071. * @default null
  14072. */
  14073. this.alphaTestNode = null;
  14074. /**
  14075. * Discards the fragment if the mask value is `false`.
  14076. *
  14077. * @type {?Node<bool>}
  14078. * @default null
  14079. */
  14080. this.maskNode = null;
  14081. /**
  14082. * The local vertex positions are computed based on multiple factors like the
  14083. * attribute data, morphing or skinning. This node property allows to overwrite
  14084. * the default and define local vertex positions with nodes instead.
  14085. *
  14086. * If you don't want to overwrite the vertex positions but modify the existing
  14087. * values instead, use {@link positionLocal}.
  14088. *
  14089. *```js
  14090. * material.positionNode = positionLocal.add( displace );
  14091. * ```
  14092. *
  14093. * @type {?Node<vec3>}
  14094. * @default null
  14095. */
  14096. this.positionNode = null;
  14097. /**
  14098. * This node property is intended for logic which modifies geometry data once or per animation step.
  14099. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14100. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14101. * can be implemented.
  14102. *
  14103. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14104. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14105. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14106. * eventually assigned to `geometryNode`.
  14107. *
  14108. * @type {?Function}
  14109. * @default null
  14110. */
  14111. this.geometryNode = null;
  14112. /**
  14113. * Allows to overwrite depth values in the fragment shader.
  14114. *
  14115. * @type {?Node<float>}
  14116. * @default null
  14117. */
  14118. this.depthNode = null;
  14119. /**
  14120. * Allows to overwrite the position used for shadow map rendering which
  14121. * is by default {@link positionWorld}, the vertex position
  14122. * in world space.
  14123. *
  14124. * @type {?Node<float>}
  14125. * @default null
  14126. */
  14127. this.receivedShadowPositionNode = null;
  14128. /**
  14129. * Allows to overwrite the geometry position used for shadow map projection which
  14130. * is by default {@link positionLocal}, the vertex position in local space.
  14131. *
  14132. * @type {?Node<float>}
  14133. * @default null
  14134. */
  14135. this.castShadowPositionNode = null;
  14136. /**
  14137. * This node can be used to influence how an object using this node material
  14138. * receive shadows.
  14139. *
  14140. * ```js
  14141. * const totalShadows = float( 1 ).toVar();
  14142. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14143. * totalShadows.mulAssign( shadow );
  14144. * //return float( 1 ); // bypass received shadows
  14145. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14146. * } );
  14147. *
  14148. * @type {?(Function|FunctionNode<vec4>)}
  14149. * @default null
  14150. */
  14151. this.receivedShadowNode = null;
  14152. /**
  14153. * This node can be used to influence how an object using this node material
  14154. * casts shadows. To apply a color to shadows, you can simply do:
  14155. *
  14156. * ```js
  14157. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14158. * ```
  14159. *
  14160. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14161. * is also common to use the property with `Fn` function so checks are performed
  14162. * per fragment.
  14163. *
  14164. * ```js
  14165. * materialCustomShadow.castShadowNode = Fn( () => {
  14166. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14167. * return materialColor;
  14168. * } )();
  14169. * ```
  14170. *
  14171. * @type {?Node<vec4>}
  14172. * @default null
  14173. */
  14174. this.castShadowNode = null;
  14175. /**
  14176. * This node can be used to define the final output of the material.
  14177. *
  14178. * TODO: Explain the differences to `fragmentNode`.
  14179. *
  14180. * @type {?Node<vec4>}
  14181. * @default null
  14182. */
  14183. this.outputNode = null;
  14184. /**
  14185. * MRT configuration is done on renderer or pass level. This node allows to
  14186. * overwrite what values are written into MRT targets on material level. This
  14187. * can be useful for implementing selective FX features that should only affect
  14188. * specific objects.
  14189. *
  14190. * @type {?MRTNode}
  14191. * @default null
  14192. */
  14193. this.mrtNode = null;
  14194. /**
  14195. * This node property can be used if you need complete freedom in implementing
  14196. * the fragment shader. Assigning a node will replace the built-in material
  14197. * logic used in the fragment stage.
  14198. *
  14199. * @type {?Node<vec4>}
  14200. * @default null
  14201. */
  14202. this.fragmentNode = null;
  14203. /**
  14204. * This node property can be used if you need complete freedom in implementing
  14205. * the vertex shader. Assigning a node will replace the built-in material logic
  14206. * used in the vertex stage.
  14207. *
  14208. * @type {?Node<vec4>}
  14209. * @default null
  14210. */
  14211. this.vertexNode = null;
  14212. // Deprecated properties
  14213. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  14214. get: () => {
  14215. return this.receivedShadowPositionNode;
  14216. },
  14217. set: ( value ) => {
  14218. warn( 'NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  14219. this.receivedShadowPositionNode = value;
  14220. }
  14221. } );
  14222. }
  14223. /**
  14224. * Allows to define a custom cache key that influence the material key computation
  14225. * for render objects.
  14226. *
  14227. * @return {string} The custom cache key.
  14228. */
  14229. customProgramCacheKey() {
  14230. return this.type + getCacheKey$1( this );
  14231. }
  14232. /**
  14233. * Builds this material with the given node builder.
  14234. *
  14235. * @param {NodeBuilder} builder - The current node builder.
  14236. */
  14237. build( builder ) {
  14238. this.setup( builder );
  14239. }
  14240. /**
  14241. * Setups a node material observer with the given builder.
  14242. *
  14243. * @param {NodeBuilder} builder - The current node builder.
  14244. * @return {NodeMaterialObserver} The node material observer.
  14245. */
  14246. setupObserver( builder ) {
  14247. return new NodeMaterialObserver( builder );
  14248. }
  14249. /**
  14250. * Setups the vertex and fragment stage of this node material.
  14251. *
  14252. * @param {NodeBuilder} builder - The current node builder.
  14253. */
  14254. setup( builder ) {
  14255. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  14256. builder.context.setupPositionView = () => this.setupPositionView( builder );
  14257. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  14258. const renderer = builder.renderer;
  14259. const renderTarget = renderer.getRenderTarget();
  14260. // < VERTEX STAGE >
  14261. builder.addStack();
  14262. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  14263. const vertexNode = this.vertexNode || mvp;
  14264. builder.stack.outputNode = vertexNode;
  14265. this.setupHardwareClipping( builder );
  14266. if ( this.geometryNode !== null ) {
  14267. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  14268. }
  14269. builder.addFlow( 'vertex', builder.removeStack() );
  14270. // < FRAGMENT STAGE >
  14271. builder.addStack();
  14272. let resultNode;
  14273. const clippingNode = this.setupClipping( builder );
  14274. if ( this.depthWrite === true || this.depthTest === true ) {
  14275. // only write depth if depth buffer is configured
  14276. if ( renderTarget !== null ) {
  14277. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  14278. } else {
  14279. if ( renderer.depth === true ) this.setupDepth( builder );
  14280. }
  14281. }
  14282. if ( this.fragmentNode === null ) {
  14283. this.setupDiffuseColor( builder );
  14284. this.setupVariants( builder );
  14285. const outgoingLightNode = this.setupLighting( builder );
  14286. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  14287. // force unsigned floats - useful for RenderTargets
  14288. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  14289. resultNode = this.setupOutput( builder, basicOutput );
  14290. // OUTPUT NODE
  14291. output.assign( resultNode );
  14292. //
  14293. const isCustomOutput = this.outputNode !== null;
  14294. if ( isCustomOutput ) resultNode = this.outputNode;
  14295. // MRT
  14296. if ( renderTarget !== null ) {
  14297. const mrt = renderer.getMRT();
  14298. const materialMRT = this.mrtNode;
  14299. if ( mrt !== null ) {
  14300. if ( isCustomOutput ) output.assign( resultNode );
  14301. resultNode = mrt;
  14302. if ( materialMRT !== null ) {
  14303. resultNode = mrt.merge( materialMRT );
  14304. }
  14305. } else if ( materialMRT !== null ) {
  14306. resultNode = materialMRT;
  14307. }
  14308. }
  14309. } else {
  14310. let fragmentNode = this.fragmentNode;
  14311. if ( fragmentNode.isOutputStructNode !== true ) {
  14312. fragmentNode = vec4( fragmentNode );
  14313. }
  14314. resultNode = this.setupOutput( builder, fragmentNode );
  14315. }
  14316. builder.stack.outputNode = resultNode;
  14317. builder.addFlow( 'fragment', builder.removeStack() );
  14318. // < OBSERVER >
  14319. builder.observer = this.setupObserver( builder );
  14320. }
  14321. /**
  14322. * Setups the clipping node.
  14323. *
  14324. * @param {NodeBuilder} builder - The current node builder.
  14325. * @return {ClippingNode} The clipping node.
  14326. */
  14327. setupClipping( builder ) {
  14328. if ( builder.clippingContext === null ) return null;
  14329. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  14330. let result = null;
  14331. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  14332. const samples = builder.renderer.currentSamples;
  14333. if ( this.alphaToCoverage && samples > 1 ) {
  14334. // to be added to flow when the color/alpha value has been determined
  14335. result = clippingAlpha();
  14336. } else {
  14337. builder.stack.add( clipping() );
  14338. }
  14339. }
  14340. return result;
  14341. }
  14342. /**
  14343. * Setups the hardware clipping if available on the current device.
  14344. *
  14345. * @param {NodeBuilder} builder - The current node builder.
  14346. */
  14347. setupHardwareClipping( builder ) {
  14348. this.hardwareClipping = false;
  14349. if ( builder.clippingContext === null ) return;
  14350. const candidateCount = builder.clippingContext.unionPlanes.length;
  14351. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14352. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14353. builder.stack.add( hardwareClipping() );
  14354. this.hardwareClipping = true;
  14355. }
  14356. return;
  14357. }
  14358. /**
  14359. * Setups the depth of this material.
  14360. *
  14361. * @param {NodeBuilder} builder - The current node builder.
  14362. */
  14363. setupDepth( builder ) {
  14364. const { renderer, camera } = builder;
  14365. // Depth
  14366. let depthNode = this.depthNode;
  14367. if ( depthNode === null ) {
  14368. const mrt = renderer.getMRT();
  14369. if ( mrt && mrt.has( 'depth' ) ) {
  14370. depthNode = mrt.get( 'depth' );
  14371. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14372. if ( camera.isPerspectiveCamera ) {
  14373. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14374. } else {
  14375. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14376. }
  14377. }
  14378. }
  14379. if ( depthNode !== null ) {
  14380. depth.assign( depthNode ).toStack();
  14381. }
  14382. }
  14383. /**
  14384. * Setups the position node in view space. This method exists
  14385. * so derived node materials can modify the implementation e.g. sprite materials.
  14386. *
  14387. * @param {NodeBuilder} builder - The current node builder.
  14388. * @return {Node<vec3>} The position in view space.
  14389. */
  14390. setupPositionView( /*builder*/ ) {
  14391. return modelViewMatrix.mul( positionLocal ).xyz;
  14392. }
  14393. /**
  14394. * Setups the position in clip space.
  14395. *
  14396. * @param {NodeBuilder} builder - The current node builder.
  14397. * @return {Node<vec4>} The position in view space.
  14398. */
  14399. setupModelViewProjection( /*builder*/ ) {
  14400. return cameraProjectionMatrix.mul( positionView );
  14401. }
  14402. /**
  14403. * Setups the logic for the vertex stage.
  14404. *
  14405. * @param {NodeBuilder} builder - The current node builder.
  14406. * @return {Node<vec4>} The position in clip space.
  14407. */
  14408. setupVertex( builder ) {
  14409. builder.addStack();
  14410. this.setupPosition( builder );
  14411. builder.context.vertex = builder.removeStack();
  14412. return modelViewProjection;
  14413. }
  14414. /**
  14415. * Setups the computation of the position in local space.
  14416. *
  14417. * @param {NodeBuilder} builder - The current node builder.
  14418. * @return {Node<vec3>} The position in local space.
  14419. */
  14420. setupPosition( builder ) {
  14421. const { object, geometry } = builder;
  14422. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  14423. morphReference( object ).toStack();
  14424. }
  14425. if ( object.isSkinnedMesh === true ) {
  14426. skinning( object ).toStack();
  14427. }
  14428. if ( this.displacementMap ) {
  14429. const displacementMap = materialReference( 'displacementMap', 'texture' );
  14430. const displacementScale = materialReference( 'displacementScale', 'float' );
  14431. const displacementBias = materialReference( 'displacementBias', 'float' );
  14432. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  14433. }
  14434. if ( object.isBatchedMesh ) {
  14435. batch( object ).toStack();
  14436. }
  14437. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  14438. instancedMesh( object ).toStack();
  14439. }
  14440. if ( this.positionNode !== null ) {
  14441. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  14442. }
  14443. return positionLocal;
  14444. }
  14445. /**
  14446. * Setups the computation of the material's diffuse color.
  14447. *
  14448. * @param {NodeBuilder} builder - The current node builder.
  14449. * @param {BufferGeometry} geometry - The geometry.
  14450. */
  14451. setupDiffuseColor( { object, geometry } ) {
  14452. // MASK
  14453. if ( this.maskNode !== null ) {
  14454. // Discard if the mask is `false`
  14455. bool( this.maskNode ).not().discard();
  14456. }
  14457. // COLOR
  14458. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  14459. // VERTEX COLORS
  14460. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  14461. colorNode = colorNode.mul( vertexColor() );
  14462. }
  14463. // INSTANCED COLORS
  14464. if ( object.instanceColor ) {
  14465. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  14466. colorNode = instanceColor.mul( colorNode );
  14467. }
  14468. if ( object.isBatchedMesh && object._colorsTexture ) {
  14469. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14470. colorNode = batchColor.mul( colorNode );
  14471. }
  14472. // DIFFUSE COLOR
  14473. diffuseColor.assign( colorNode );
  14474. // OPACITY
  14475. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14476. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14477. // ALPHA TEST
  14478. let alphaTestNode = null;
  14479. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14480. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14481. if ( this.alphaToCoverage === true ) {
  14482. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  14483. diffuseColor.a.lessThanEqual( 0 ).discard();
  14484. } else {
  14485. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14486. }
  14487. }
  14488. // ALPHA HASH
  14489. if ( this.alphaHash === true ) {
  14490. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14491. }
  14492. // OPAQUE
  14493. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  14494. if ( isOpaque ) {
  14495. diffuseColor.a.assign( 1.0 );
  14496. }
  14497. }
  14498. /**
  14499. * Abstract interface method that can be implemented by derived materials
  14500. * to setup material-specific node variables.
  14501. *
  14502. * @abstract
  14503. * @param {NodeBuilder} builder - The current node builder.
  14504. */
  14505. setupVariants( /*builder*/ ) {
  14506. // Interface function.
  14507. }
  14508. /**
  14509. * Setups the outgoing light node variable
  14510. *
  14511. * @return {Node<vec3>} The outgoing light node.
  14512. */
  14513. setupOutgoingLight() {
  14514. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14515. }
  14516. /**
  14517. * Setups the normal node from the material.
  14518. *
  14519. * @return {Node<vec3>} The normal node.
  14520. */
  14521. setupNormal() {
  14522. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14523. }
  14524. /**
  14525. * Setups the environment node from the material.
  14526. *
  14527. * @param {NodeBuilder} builder - The current node builder.
  14528. * @return {Node<vec4>} The environment node.
  14529. */
  14530. setupEnvironment( /*builder*/ ) {
  14531. let node = null;
  14532. if ( this.envNode ) {
  14533. node = this.envNode;
  14534. } else if ( this.envMap ) {
  14535. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14536. }
  14537. return node;
  14538. }
  14539. /**
  14540. * Setups the light map node from the material.
  14541. *
  14542. * @param {NodeBuilder} builder - The current node builder.
  14543. * @return {Node<vec3>} The light map node.
  14544. */
  14545. setupLightMap( builder ) {
  14546. let node = null;
  14547. if ( builder.material.lightMap ) {
  14548. node = new IrradianceNode( materialLightMap );
  14549. }
  14550. return node;
  14551. }
  14552. /**
  14553. * Setups the lights node based on the scene, environment and material.
  14554. *
  14555. * @param {NodeBuilder} builder - The current node builder.
  14556. * @return {LightsNode} The lights node.
  14557. */
  14558. setupLights( builder ) {
  14559. const materialLightsNode = [];
  14560. //
  14561. const envNode = this.setupEnvironment( builder );
  14562. if ( envNode && envNode.isLightingNode ) {
  14563. materialLightsNode.push( envNode );
  14564. }
  14565. const lightMapNode = this.setupLightMap( builder );
  14566. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14567. materialLightsNode.push( lightMapNode );
  14568. }
  14569. if ( this.aoNode !== null || builder.material.aoMap ) {
  14570. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  14571. materialLightsNode.push( new AONode( aoNode ) );
  14572. }
  14573. let lightsN = this.lightsNode || builder.lightsNode;
  14574. if ( materialLightsNode.length > 0 ) {
  14575. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14576. }
  14577. return lightsN;
  14578. }
  14579. /**
  14580. * This method should be implemented by most derived materials
  14581. * since it defines the material's lighting model.
  14582. *
  14583. * @abstract
  14584. * @param {NodeBuilder} builder - The current node builder.
  14585. * @return {LightingModel} The lighting model.
  14586. */
  14587. setupLightingModel( /*builder*/ ) {
  14588. // Interface function.
  14589. }
  14590. /**
  14591. * Setups the outgoing light node.
  14592. *
  14593. * @param {NodeBuilder} builder - The current node builder.
  14594. * @return {Node<vec3>} The outgoing light node.
  14595. */
  14596. setupLighting( builder ) {
  14597. const { material } = builder;
  14598. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14599. // OUTGOING LIGHT
  14600. const lights = this.lights === true || this.lightsNode !== null;
  14601. const lightsNode = lights ? this.setupLights( builder ) : null;
  14602. let outgoingLightNode = this.setupOutgoingLight( builder );
  14603. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14604. const lightingModel = this.setupLightingModel( builder ) || null;
  14605. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14606. } else if ( backdropNode !== null ) {
  14607. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14608. }
  14609. // EMISSIVE
  14610. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14611. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14612. outgoingLightNode = outgoingLightNode.add( emissive );
  14613. }
  14614. return outgoingLightNode;
  14615. }
  14616. /**
  14617. * Setup the fog.
  14618. *
  14619. * @param {NodeBuilder} builder - The current node builder.
  14620. * @param {Node<vec4>} outputNode - The existing output node.
  14621. * @return {Node<vec4>} The output node.
  14622. */
  14623. setupFog( builder, outputNode ) {
  14624. const fogNode = builder.fogNode;
  14625. if ( fogNode ) {
  14626. output.assign( outputNode );
  14627. outputNode = vec4( fogNode.toVar() );
  14628. }
  14629. return outputNode;
  14630. }
  14631. /**
  14632. * Setups premultiplied alpha.
  14633. *
  14634. * @param {NodeBuilder} builder - The current node builder.
  14635. * @param {Node<vec4>} outputNode - The existing output node.
  14636. * @return {Node<vec4>} The output node.
  14637. */
  14638. setupPremultipliedAlpha( builder, outputNode ) {
  14639. return premultiplyAlpha( outputNode );
  14640. }
  14641. /**
  14642. * Setups the output node.
  14643. *
  14644. * @param {NodeBuilder} builder - The current node builder.
  14645. * @param {Node<vec4>} outputNode - The existing output node.
  14646. * @return {Node<vec4>} The output node.
  14647. */
  14648. setupOutput( builder, outputNode ) {
  14649. // FOG
  14650. if ( this.fog === true ) {
  14651. outputNode = this.setupFog( builder, outputNode );
  14652. }
  14653. // PREMULTIPLIED ALPHA
  14654. if ( this.premultipliedAlpha === true ) {
  14655. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  14656. }
  14657. return outputNode;
  14658. }
  14659. /**
  14660. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  14661. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  14662. * defining all material properties of the classic type in the node type.
  14663. *
  14664. * @param {Material} material - The material to copy properties with their values to this node material.
  14665. */
  14666. setDefaultValues( material ) {
  14667. // This approach is to reuse the native refreshUniforms*
  14668. // and turn available the use of features like transmission and environment in core
  14669. for ( const property in material ) {
  14670. const value = material[ property ];
  14671. if ( this[ property ] === undefined ) {
  14672. this[ property ] = value;
  14673. if ( value && value.clone ) this[ property ] = value.clone();
  14674. }
  14675. }
  14676. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  14677. for ( const key in descriptors ) {
  14678. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  14679. descriptors[ key ].get !== undefined ) {
  14680. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  14681. }
  14682. }
  14683. }
  14684. /**
  14685. * Serializes this material to JSON.
  14686. *
  14687. * @param {?(Object|string)} meta - The meta information for serialization.
  14688. * @return {Object} The serialized node.
  14689. */
  14690. toJSON( meta ) {
  14691. const isRoot = ( meta === undefined || typeof meta === 'string' );
  14692. if ( isRoot ) {
  14693. meta = {
  14694. textures: {},
  14695. images: {},
  14696. nodes: {}
  14697. };
  14698. }
  14699. const data = Material.prototype.toJSON.call( this, meta );
  14700. const nodeChildren = getNodeChildren( this );
  14701. data.inputNodes = {};
  14702. for ( const { property, childNode } of nodeChildren ) {
  14703. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  14704. }
  14705. // TODO: Copied from Object3D.toJSON
  14706. function extractFromCache( cache ) {
  14707. const values = [];
  14708. for ( const key in cache ) {
  14709. const data = cache[ key ];
  14710. delete data.metadata;
  14711. values.push( data );
  14712. }
  14713. return values;
  14714. }
  14715. if ( isRoot ) {
  14716. const textures = extractFromCache( meta.textures );
  14717. const images = extractFromCache( meta.images );
  14718. const nodes = extractFromCache( meta.nodes );
  14719. if ( textures.length > 0 ) data.textures = textures;
  14720. if ( images.length > 0 ) data.images = images;
  14721. if ( nodes.length > 0 ) data.nodes = nodes;
  14722. }
  14723. return data;
  14724. }
  14725. /**
  14726. * Copies the properties of the given node material to this instance.
  14727. *
  14728. * @param {NodeMaterial} source - The material to copy.
  14729. * @return {NodeMaterial} A reference to this node material.
  14730. */
  14731. copy( source ) {
  14732. this.lightsNode = source.lightsNode;
  14733. this.envNode = source.envNode;
  14734. this.colorNode = source.colorNode;
  14735. this.normalNode = source.normalNode;
  14736. this.opacityNode = source.opacityNode;
  14737. this.backdropNode = source.backdropNode;
  14738. this.backdropAlphaNode = source.backdropAlphaNode;
  14739. this.alphaTestNode = source.alphaTestNode;
  14740. this.maskNode = source.maskNode;
  14741. this.positionNode = source.positionNode;
  14742. this.geometryNode = source.geometryNode;
  14743. this.depthNode = source.depthNode;
  14744. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  14745. this.castShadowPositionNode = source.castShadowPositionNode;
  14746. this.receivedShadowNode = source.receivedShadowNode;
  14747. this.castShadowNode = source.castShadowNode;
  14748. this.outputNode = source.outputNode;
  14749. this.mrtNode = source.mrtNode;
  14750. this.fragmentNode = source.fragmentNode;
  14751. this.vertexNode = source.vertexNode;
  14752. return super.copy( source );
  14753. }
  14754. }
  14755. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  14756. /**
  14757. * Node material version of {@link LineBasicMaterial}.
  14758. *
  14759. * @augments NodeMaterial
  14760. */
  14761. class LineBasicNodeMaterial extends NodeMaterial {
  14762. static get type() {
  14763. return 'LineBasicNodeMaterial';
  14764. }
  14765. /**
  14766. * Constructs a new line basic node material.
  14767. *
  14768. * @param {Object} [parameters] - The configuration parameter.
  14769. */
  14770. constructor( parameters ) {
  14771. super();
  14772. /**
  14773. * This flag can be used for type testing.
  14774. *
  14775. * @type {boolean}
  14776. * @readonly
  14777. * @default true
  14778. */
  14779. this.isLineBasicNodeMaterial = true;
  14780. this.setDefaultValues( _defaultValues$d );
  14781. this.setValues( parameters );
  14782. }
  14783. }
  14784. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  14785. /**
  14786. * Node material version of {@link LineDashedMaterial}.
  14787. *
  14788. * @augments NodeMaterial
  14789. */
  14790. class LineDashedNodeMaterial extends NodeMaterial {
  14791. static get type() {
  14792. return 'LineDashedNodeMaterial';
  14793. }
  14794. /**
  14795. * Constructs a new line dashed node material.
  14796. *
  14797. * @param {Object} [parameters] - The configuration parameter.
  14798. */
  14799. constructor( parameters ) {
  14800. super();
  14801. /**
  14802. * This flag can be used for type testing.
  14803. *
  14804. * @type {boolean}
  14805. * @readonly
  14806. * @default true
  14807. */
  14808. this.isLineDashedNodeMaterial = true;
  14809. this.setDefaultValues( _defaultValues$c );
  14810. /**
  14811. * The dash offset.
  14812. *
  14813. * @type {number}
  14814. * @default 0
  14815. */
  14816. this.dashOffset = 0;
  14817. /**
  14818. * The offset of dash materials is by default inferred from the `dashOffset`
  14819. * property. This node property allows to overwrite the default
  14820. * and define the offset with a node instead.
  14821. *
  14822. * If you don't want to overwrite the offset but modify the existing
  14823. * value instead, use {@link materialLineDashOffset}.
  14824. *
  14825. * @type {?Node<float>}
  14826. * @default null
  14827. */
  14828. this.offsetNode = null;
  14829. /**
  14830. * The scale of dash materials is by default inferred from the `scale`
  14831. * property. This node property allows to overwrite the default
  14832. * and define the scale with a node instead.
  14833. *
  14834. * If you don't want to overwrite the scale but modify the existing
  14835. * value instead, use {@link materialLineScale}.
  14836. *
  14837. * @type {?Node<float>}
  14838. * @default null
  14839. */
  14840. this.dashScaleNode = null;
  14841. /**
  14842. * The dash size of dash materials is by default inferred from the `dashSize`
  14843. * property. This node property allows to overwrite the default
  14844. * and define the dash size with a node instead.
  14845. *
  14846. * If you don't want to overwrite the dash size but modify the existing
  14847. * value instead, use {@link materialLineDashSize}.
  14848. *
  14849. * @type {?Node<float>}
  14850. * @default null
  14851. */
  14852. this.dashSizeNode = null;
  14853. /**
  14854. * The gap size of dash materials is by default inferred from the `gapSize`
  14855. * property. This node property allows to overwrite the default
  14856. * and define the gap size with a node instead.
  14857. *
  14858. * If you don't want to overwrite the gap size but modify the existing
  14859. * value instead, use {@link materialLineGapSize}.
  14860. *
  14861. * @type {?Node<float>}
  14862. * @default null
  14863. */
  14864. this.gapSizeNode = null;
  14865. this.setValues( parameters );
  14866. }
  14867. /**
  14868. * Setups the dash specific node variables.
  14869. *
  14870. * @param {NodeBuilder} builder - The current node builder.
  14871. */
  14872. setupVariants( /* builder */ ) {
  14873. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14874. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14875. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14876. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14877. dashSize.assign( dashSizeNode );
  14878. gapSize.assign( gapSizeNode );
  14879. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  14880. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  14881. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  14882. }
  14883. }
  14884. let _sharedFramebuffer = null;
  14885. /**
  14886. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  14887. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  14888. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  14889. *
  14890. * @augments ViewportTextureNode
  14891. */
  14892. class ViewportSharedTextureNode extends ViewportTextureNode {
  14893. static get type() {
  14894. return 'ViewportSharedTextureNode';
  14895. }
  14896. /**
  14897. * Constructs a new viewport shared texture node.
  14898. *
  14899. * @param {Node} [uvNode=screenUV] - The uv node.
  14900. * @param {?Node} [levelNode=null] - The level node.
  14901. */
  14902. constructor( uvNode = screenUV, levelNode = null ) {
  14903. if ( _sharedFramebuffer === null ) {
  14904. _sharedFramebuffer = new FramebufferTexture();
  14905. }
  14906. super( uvNode, levelNode, _sharedFramebuffer );
  14907. }
  14908. /**
  14909. * Overwritten so the method always returns the unique shared
  14910. * framebuffer texture.
  14911. *
  14912. * @return {FramebufferTexture} The shared framebuffer texture.
  14913. */
  14914. getTextureForReference() {
  14915. return _sharedFramebuffer;
  14916. }
  14917. updateReference() {
  14918. return this;
  14919. }
  14920. }
  14921. /**
  14922. * TSL function for creating a shared viewport texture node.
  14923. *
  14924. * @tsl
  14925. * @function
  14926. * @param {?Node} [uvNode=screenUV] - The uv node.
  14927. * @param {?Node} [levelNode=null] - The level node.
  14928. * @returns {ViewportSharedTextureNode}
  14929. */
  14930. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  14931. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  14932. /**
  14933. * This node material can be used to render lines with a size larger than one
  14934. * by representing them as instanced meshes.
  14935. *
  14936. * @augments NodeMaterial
  14937. */
  14938. class Line2NodeMaterial extends NodeMaterial {
  14939. static get type() {
  14940. return 'Line2NodeMaterial';
  14941. }
  14942. /**
  14943. * Constructs a new node material for wide line rendering.
  14944. *
  14945. * @param {Object} [parameters={}] - The configuration parameter.
  14946. */
  14947. constructor( parameters = {} ) {
  14948. super();
  14949. /**
  14950. * This flag can be used for type testing.
  14951. *
  14952. * @type {boolean}
  14953. * @readonly
  14954. * @default true
  14955. */
  14956. this.isLine2NodeMaterial = true;
  14957. this.setDefaultValues( _defaultValues$b );
  14958. /**
  14959. * Whether vertex colors should be used or not.
  14960. *
  14961. * @type {boolean}
  14962. * @default false
  14963. */
  14964. this.useColor = parameters.vertexColors;
  14965. /**
  14966. * The dash offset.
  14967. *
  14968. * @type {number}
  14969. * @default 0
  14970. */
  14971. this.dashOffset = 0;
  14972. /**
  14973. * Defines the lines color.
  14974. *
  14975. * @type {?Node<vec3>}
  14976. * @default null
  14977. */
  14978. this.lineColorNode = null;
  14979. /**
  14980. * Defines the offset.
  14981. *
  14982. * @type {?Node<float>}
  14983. * @default null
  14984. */
  14985. this.offsetNode = null;
  14986. /**
  14987. * Defines the dash scale.
  14988. *
  14989. * @type {?Node<float>}
  14990. * @default null
  14991. */
  14992. this.dashScaleNode = null;
  14993. /**
  14994. * Defines the dash size.
  14995. *
  14996. * @type {?Node<float>}
  14997. * @default null
  14998. */
  14999. this.dashSizeNode = null;
  15000. /**
  15001. * Defines the gap size.
  15002. *
  15003. * @type {?Node<float>}
  15004. * @default null
  15005. */
  15006. this.gapSizeNode = null;
  15007. /**
  15008. * Blending is set to `NoBlending` since transparency
  15009. * is not supported, yet.
  15010. *
  15011. * @type {number}
  15012. * @default 0
  15013. */
  15014. this.blending = NoBlending;
  15015. this._useDash = parameters.dashed;
  15016. this._useAlphaToCoverage = true;
  15017. this._useWorldUnits = false;
  15018. this.setValues( parameters );
  15019. }
  15020. /**
  15021. * Setups the vertex and fragment stage of this node material.
  15022. *
  15023. * @param {NodeBuilder} builder - The current node builder.
  15024. */
  15025. setup( builder ) {
  15026. const { renderer } = builder;
  15027. const useAlphaToCoverage = this._useAlphaToCoverage;
  15028. const useColor = this.useColor;
  15029. const useDash = this._useDash;
  15030. const useWorldUnits = this._useWorldUnits;
  15031. const trimSegment = Fn( ( { start, end } ) => {
  15032. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15033. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15034. const nearEstimate = b.mul( -0.5 ).div( a );
  15035. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15036. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  15037. } ).setLayout( {
  15038. name: 'trimSegment',
  15039. type: 'vec4',
  15040. inputs: [
  15041. { name: 'start', type: 'vec4' },
  15042. { name: 'end', type: 'vec4' }
  15043. ]
  15044. } );
  15045. this.vertexNode = Fn( () => {
  15046. const instanceStart = attribute( 'instanceStart' );
  15047. const instanceEnd = attribute( 'instanceEnd' );
  15048. // camera space
  15049. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15050. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15051. if ( useDash ) {
  15052. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15053. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15054. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  15055. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  15056. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  15057. lineDistance = lineDistance.add( offsetNode );
  15058. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  15059. }
  15060. if ( useWorldUnits ) {
  15061. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  15062. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  15063. }
  15064. const aspect = viewport.z.div( viewport.w );
  15065. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15066. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15067. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15068. // perhaps there is a more elegant solution -- WestLangley
  15069. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15070. If( perspective, () => {
  15071. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15072. end.assign( trimSegment( { start: start, end: end } ) );
  15073. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15074. start.assign( trimSegment( { start: end, end: start } ) );
  15075. } );
  15076. } );
  15077. // clip space
  15078. const clipStart = cameraProjectionMatrix.mul( start );
  15079. const clipEnd = cameraProjectionMatrix.mul( end );
  15080. // ndc space
  15081. const ndcStart = clipStart.xyz.div( clipStart.w );
  15082. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15083. // direction
  15084. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15085. // account for clip-space aspect ratio
  15086. dir.x.assign( dir.x.mul( aspect ) );
  15087. dir.assign( dir.normalize() );
  15088. const clip = vec4().toVar();
  15089. if ( useWorldUnits ) {
  15090. // get the offset direction as perpendicular to the view vector
  15091. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15092. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15093. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15094. const worldFwd = worldDir.cross( worldUp );
  15095. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15096. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15097. // height offset
  15098. const hw = materialLineWidth.mul( 0.5 );
  15099. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15100. // don't extend the line if we're rendering dashes because we
  15101. // won't be rendering the endcaps
  15102. if ( ! useDash ) {
  15103. // cap extension
  15104. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15105. // add width to the box
  15106. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15107. // endcaps
  15108. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15109. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15110. } );
  15111. }
  15112. // project the worldpos
  15113. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15114. // shift the depth of the projected points so the line
  15115. // segments overlap neatly
  15116. const clipPose = vec3().toVar();
  15117. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15118. clip.z.assign( clipPose.z.mul( clip.w ) );
  15119. } else {
  15120. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15121. // undo aspect ratio adjustment
  15122. dir.x.assign( dir.x.div( aspect ) );
  15123. offset.x.assign( offset.x.div( aspect ) );
  15124. // sign flip
  15125. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15126. // endcaps
  15127. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15128. offset.assign( offset.sub( dir ) );
  15129. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15130. offset.assign( offset.add( dir ) );
  15131. } );
  15132. // adjust for linewidth
  15133. offset.assign( offset.mul( materialLineWidth ) );
  15134. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15135. offset.assign( offset.div( viewport.w ) );
  15136. // select end
  15137. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15138. // back to clip space
  15139. offset.assign( offset.mul( clip.w ) );
  15140. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15141. }
  15142. return clip;
  15143. } )();
  15144. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15145. const p13 = p1.sub( p3 );
  15146. const p43 = p4.sub( p3 );
  15147. const p21 = p2.sub( p1 );
  15148. const d1343 = p13.dot( p43 );
  15149. const d4321 = p43.dot( p21 );
  15150. const d1321 = p13.dot( p21 );
  15151. const d4343 = p43.dot( p43 );
  15152. const d2121 = p21.dot( p21 );
  15153. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15154. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15155. const mua = numer.div( denom ).clamp();
  15156. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15157. return vec2( mua, mub );
  15158. } );
  15159. this.colorNode = Fn( () => {
  15160. const vUv = uv$1();
  15161. if ( useDash ) {
  15162. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15163. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15164. dashSize.assign( dashSizeNode );
  15165. gapSize.assign( gapSizeNode );
  15166. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  15167. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15168. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15169. }
  15170. const alpha = float( 1 ).toVar( 'alpha' );
  15171. if ( useWorldUnits ) {
  15172. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15173. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15174. // Find the closest points on the view ray and the line segment
  15175. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15176. const lineDir = worldEnd.sub( worldStart );
  15177. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15178. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15179. const p2 = rayEnd.mul( params.y );
  15180. const delta = p1.sub( p2 );
  15181. const len = delta.length();
  15182. const norm = len.div( materialLineWidth );
  15183. if ( ! useDash ) {
  15184. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15185. const dnorm = norm.fwidth();
  15186. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15187. } else {
  15188. norm.greaterThan( 0.5 ).discard();
  15189. }
  15190. }
  15191. } else {
  15192. // round endcaps
  15193. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15194. const a = vUv.x;
  15195. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15196. const len2 = a.mul( a ).add( b.mul( b ) );
  15197. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15198. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15199. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15200. } );
  15201. } else {
  15202. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15203. const a = vUv.x;
  15204. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15205. const len2 = a.mul( a ).add( b.mul( b ) );
  15206. len2.greaterThan( 1.0 ).discard();
  15207. } );
  15208. }
  15209. }
  15210. let lineColorNode;
  15211. if ( this.lineColorNode ) {
  15212. lineColorNode = this.lineColorNode;
  15213. } else {
  15214. if ( useColor ) {
  15215. const instanceColorStart = attribute( 'instanceColorStart' );
  15216. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15217. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15218. lineColorNode = instanceColor.mul( materialColor );
  15219. } else {
  15220. lineColorNode = materialColor;
  15221. }
  15222. }
  15223. return vec4( lineColorNode, alpha );
  15224. } )();
  15225. if ( this.transparent ) {
  15226. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15227. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15228. }
  15229. super.setup( builder );
  15230. }
  15231. /**
  15232. * Whether the lines should sized in world units or not.
  15233. * When set to `false` the unit is pixel.
  15234. *
  15235. * @type {boolean}
  15236. * @default false
  15237. */
  15238. get worldUnits() {
  15239. return this._useWorldUnits;
  15240. }
  15241. set worldUnits( value ) {
  15242. if ( this._useWorldUnits !== value ) {
  15243. this._useWorldUnits = value;
  15244. this.needsUpdate = true;
  15245. }
  15246. }
  15247. /**
  15248. * Whether the lines should be dashed or not.
  15249. *
  15250. * @type {boolean}
  15251. * @default false
  15252. */
  15253. get dashed() {
  15254. return this._useDash;
  15255. }
  15256. set dashed( value ) {
  15257. if ( this._useDash !== value ) {
  15258. this._useDash = value;
  15259. this.needsUpdate = true;
  15260. }
  15261. }
  15262. /**
  15263. * Whether alpha to coverage should be used or not.
  15264. *
  15265. * @type {boolean}
  15266. * @default true
  15267. */
  15268. get alphaToCoverage() {
  15269. return this._useAlphaToCoverage;
  15270. }
  15271. set alphaToCoverage( value ) {
  15272. if ( this._useAlphaToCoverage !== value ) {
  15273. this._useAlphaToCoverage = value;
  15274. this.needsUpdate = true;
  15275. }
  15276. }
  15277. }
  15278. /**
  15279. * Packs a direction vector into a color value.
  15280. *
  15281. * @tsl
  15282. * @function
  15283. * @param {Node<vec3>} node - The direction to pack.
  15284. * @return {Node<vec3>} The color.
  15285. */
  15286. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  15287. /**
  15288. * Unpacks a color value into a direction vector.
  15289. *
  15290. * @tsl
  15291. * @function
  15292. * @param {Node<vec3>} node - The color to unpack.
  15293. * @return {Node<vec3>} The direction.
  15294. */
  15295. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  15296. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  15297. /**
  15298. * Node material version of {@link MeshNormalMaterial}.
  15299. *
  15300. * @augments NodeMaterial
  15301. */
  15302. class MeshNormalNodeMaterial extends NodeMaterial {
  15303. static get type() {
  15304. return 'MeshNormalNodeMaterial';
  15305. }
  15306. /**
  15307. * Constructs a new mesh normal node material.
  15308. *
  15309. * @param {Object} [parameters] - The configuration parameter.
  15310. */
  15311. constructor( parameters ) {
  15312. super();
  15313. /**
  15314. * This flag can be used for type testing.
  15315. *
  15316. * @type {boolean}
  15317. * @readonly
  15318. * @default true
  15319. */
  15320. this.isMeshNormalNodeMaterial = true;
  15321. this.setDefaultValues( _defaultValues$a );
  15322. this.setValues( parameters );
  15323. }
  15324. /**
  15325. * Overwrites the default implementation by computing the diffuse color
  15326. * based on the normal data.
  15327. */
  15328. setupDiffuseColor() {
  15329. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15330. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  15331. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  15332. }
  15333. }
  15334. /**
  15335. * TSL function for creating an equirect uv node.
  15336. *
  15337. * Can be used to compute texture coordinates for projecting an
  15338. * equirectangular texture onto a mesh for using it as the scene's
  15339. * background.
  15340. *
  15341. * ```js
  15342. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  15343. * ```
  15344. *
  15345. * @tsl
  15346. * @function
  15347. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15348. * @returns {Node<vec2>}
  15349. */
  15350. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15351. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15352. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15353. return vec2( u, v );
  15354. } );
  15355. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  15356. /**
  15357. * This class represents a cube render target. It is a special version
  15358. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15359. *
  15360. * @augments WebGLCubeRenderTarget
  15361. */
  15362. class CubeRenderTarget extends WebGLCubeRenderTarget {
  15363. /**
  15364. * Constructs a new cube render target.
  15365. *
  15366. * @param {number} [size=1] - The size of the render target.
  15367. * @param {RenderTarget~Options} [options] - The configuration object.
  15368. */
  15369. constructor( size = 1, options = {} ) {
  15370. super( size, options );
  15371. /**
  15372. * This flag can be used for type testing.
  15373. *
  15374. * @type {boolean}
  15375. * @readonly
  15376. * @default true
  15377. */
  15378. this.isCubeRenderTarget = true;
  15379. }
  15380. /**
  15381. * Converts the given equirectangular texture to a cube map.
  15382. *
  15383. * @param {Renderer} renderer - The renderer.
  15384. * @param {Texture} texture - The equirectangular texture.
  15385. * @return {CubeRenderTarget} A reference to this cube render target.
  15386. */
  15387. fromEquirectangularTexture( renderer, texture$1 ) {
  15388. const currentMinFilter = texture$1.minFilter;
  15389. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15390. texture$1.generateMipmaps = true;
  15391. this.texture.type = texture$1.type;
  15392. this.texture.colorSpace = texture$1.colorSpace;
  15393. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15394. this.texture.minFilter = texture$1.minFilter;
  15395. this.texture.magFilter = texture$1.magFilter;
  15396. const geometry = new BoxGeometry( 5, 5, 5 );
  15397. const uvNode = equirectUV( positionWorldDirection );
  15398. const material = new NodeMaterial();
  15399. material.colorNode = texture( texture$1, uvNode, 0 );
  15400. material.side = BackSide;
  15401. material.blending = NoBlending;
  15402. const mesh = new Mesh( geometry, material );
  15403. const scene = new Scene();
  15404. scene.add( mesh );
  15405. // Avoid blurred poles
  15406. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15407. const camera = new CubeCamera( 1, 10, this );
  15408. const currentMRT = renderer.getMRT();
  15409. renderer.setMRT( null );
  15410. camera.update( renderer, scene );
  15411. renderer.setMRT( currentMRT );
  15412. texture$1.minFilter = currentMinFilter;
  15413. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15414. mesh.geometry.dispose();
  15415. mesh.material.dispose();
  15416. return this;
  15417. }
  15418. }
  15419. const _cache$1 = new WeakMap();
  15420. /**
  15421. * This node can be used to automatically convert environment maps in the
  15422. * equirectangular format into the cube map format.
  15423. *
  15424. * @augments TempNode
  15425. */
  15426. class CubeMapNode extends TempNode {
  15427. static get type() {
  15428. return 'CubeMapNode';
  15429. }
  15430. /**
  15431. * Constructs a new cube map node.
  15432. *
  15433. * @param {Node} envNode - The node representing the environment map.
  15434. */
  15435. constructor( envNode ) {
  15436. super( 'vec3' );
  15437. /**
  15438. * The node representing the environment map.
  15439. *
  15440. * @type {Node}
  15441. */
  15442. this.envNode = envNode;
  15443. /**
  15444. * A reference to the internal cube texture.
  15445. *
  15446. * @private
  15447. * @type {?CubeTexture}
  15448. * @default null
  15449. */
  15450. this._cubeTexture = null;
  15451. /**
  15452. * A reference to the internal cube texture node.
  15453. *
  15454. * @private
  15455. * @type {CubeTextureNode}
  15456. */
  15457. this._cubeTextureNode = cubeTexture( null );
  15458. const defaultTexture = new CubeTexture();
  15459. defaultTexture.isRenderTargetTexture = true;
  15460. /**
  15461. * A default cube texture that acts as a placeholder.
  15462. * It is used when the conversion from equirectangular to cube
  15463. * map has not finished yet for a given texture.
  15464. *
  15465. * @private
  15466. * @type {CubeTexture}
  15467. */
  15468. this._defaultTexture = defaultTexture;
  15469. /**
  15470. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  15471. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15472. *
  15473. * @type {string}
  15474. * @default 'render'
  15475. */
  15476. this.updateBeforeType = NodeUpdateType.RENDER;
  15477. }
  15478. updateBefore( frame ) {
  15479. const { renderer, material } = frame;
  15480. const envNode = this.envNode;
  15481. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15482. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15483. if ( texture && texture.isTexture ) {
  15484. const mapping = texture.mapping;
  15485. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15486. // check for converted cubemap map
  15487. if ( _cache$1.has( texture ) ) {
  15488. const cubeMap = _cache$1.get( texture );
  15489. mapTextureMapping( cubeMap, texture.mapping );
  15490. this._cubeTexture = cubeMap;
  15491. } else {
  15492. // create cube map from equirectangular map
  15493. const image = texture.image;
  15494. if ( isEquirectangularMapReady$1( image ) ) {
  15495. const renderTarget = new CubeRenderTarget( image.height );
  15496. renderTarget.fromEquirectangularTexture( renderer, texture );
  15497. mapTextureMapping( renderTarget.texture, texture.mapping );
  15498. this._cubeTexture = renderTarget.texture;
  15499. _cache$1.set( texture, renderTarget.texture );
  15500. texture.addEventListener( 'dispose', onTextureDispose );
  15501. } else {
  15502. // default cube texture as fallback when equirectangular texture is not yet loaded
  15503. this._cubeTexture = this._defaultTexture;
  15504. }
  15505. }
  15506. //
  15507. this._cubeTextureNode.value = this._cubeTexture;
  15508. } else {
  15509. // envNode already refers to a cube map
  15510. this._cubeTextureNode = this.envNode;
  15511. }
  15512. }
  15513. }
  15514. }
  15515. setup( builder ) {
  15516. this.updateBefore( builder );
  15517. return this._cubeTextureNode;
  15518. }
  15519. }
  15520. /**
  15521. * Returns true if the given equirectangular image has been fully loaded
  15522. * and is ready for further processing.
  15523. *
  15524. * @private
  15525. * @param {Image} image - The equirectangular image to check.
  15526. * @return {boolean} Whether the image is ready or not.
  15527. */
  15528. function isEquirectangularMapReady$1( image ) {
  15529. if ( image === null || image === undefined ) return false;
  15530. return image.height > 0;
  15531. }
  15532. /**
  15533. * This function is executed when `dispose()` is called on the equirectangular
  15534. * texture. In this case, the generated cube map with its render target
  15535. * is deleted as well.
  15536. *
  15537. * @private
  15538. * @param {Object} event - The event object.
  15539. */
  15540. function onTextureDispose( event ) {
  15541. const texture = event.target;
  15542. texture.removeEventListener( 'dispose', onTextureDispose );
  15543. const renderTarget = _cache$1.get( texture );
  15544. if ( renderTarget !== undefined ) {
  15545. _cache$1.delete( texture );
  15546. renderTarget.dispose();
  15547. }
  15548. }
  15549. /**
  15550. * This function makes sure the generated cube map uses the correct
  15551. * texture mapping that corresponds to the equirectangular original.
  15552. *
  15553. * @private
  15554. * @param {Texture} texture - The cube texture.
  15555. * @param {number} mapping - The original texture mapping.
  15556. */
  15557. function mapTextureMapping( texture, mapping ) {
  15558. if ( mapping === EquirectangularReflectionMapping ) {
  15559. texture.mapping = CubeReflectionMapping;
  15560. } else if ( mapping === EquirectangularRefractionMapping ) {
  15561. texture.mapping = CubeRefractionMapping;
  15562. }
  15563. }
  15564. /**
  15565. * TSL function for creating a cube map node.
  15566. *
  15567. * @tsl
  15568. * @function
  15569. * @param {Node} envNode - The node representing the environment map.
  15570. * @returns {CubeMapNode}
  15571. */
  15572. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15573. /**
  15574. * Represents a basic model for Image-based lighting (IBL). The environment
  15575. * is defined via environment maps in the equirectangular or cube map format.
  15576. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15577. * or {@link MeshPhongNodeMaterial}.
  15578. *
  15579. * @augments LightingNode
  15580. */
  15581. class BasicEnvironmentNode extends LightingNode {
  15582. static get type() {
  15583. return 'BasicEnvironmentNode';
  15584. }
  15585. /**
  15586. * Constructs a new basic environment node.
  15587. *
  15588. * @param {Node} [envNode=null] - A node representing the environment.
  15589. */
  15590. constructor( envNode = null ) {
  15591. super();
  15592. /**
  15593. * A node representing the environment.
  15594. *
  15595. * @type {Node}
  15596. * @default null
  15597. */
  15598. this.envNode = envNode;
  15599. }
  15600. setup( builder ) {
  15601. // environment property is used in the finish() method of BasicLightingModel
  15602. builder.context.environment = cubeMapNode( this.envNode );
  15603. }
  15604. }
  15605. /**
  15606. * A specific version of {@link IrradianceNode} that is only relevant
  15607. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15608. * requires a special scaling factor for the light map.
  15609. *
  15610. * @augments LightingNode
  15611. */
  15612. class BasicLightMapNode extends LightingNode {
  15613. static get type() {
  15614. return 'BasicLightMapNode';
  15615. }
  15616. /**
  15617. * Constructs a new basic light map node.
  15618. *
  15619. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15620. */
  15621. constructor( lightMapNode = null ) {
  15622. super();
  15623. /**
  15624. * The light map node.
  15625. *
  15626. * @type {?Node<vec3>}
  15627. */
  15628. this.lightMapNode = lightMapNode;
  15629. }
  15630. setup( builder ) {
  15631. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15632. const RECIPROCAL_PI = float( 1 / Math.PI );
  15633. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15634. }
  15635. }
  15636. /**
  15637. * Abstract class for implementing lighting models. The module defines
  15638. * multiple methods that concrete lighting models can implement. These
  15639. * methods are executed at different points during the light evaluation
  15640. * process.
  15641. */
  15642. class LightingModel {
  15643. /**
  15644. * This method is intended for setting up lighting model and context data
  15645. * which are later used in the evaluation process.
  15646. *
  15647. * @abstract
  15648. * @param {NodeBuilder} builder - The current node builder.
  15649. */
  15650. start( builder ) {
  15651. // lights ( direct )
  15652. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15653. // indirect
  15654. this.indirect( builder );
  15655. }
  15656. /**
  15657. * This method is intended for executing final tasks like final updates
  15658. * to the outgoing light.
  15659. *
  15660. * @abstract
  15661. * @param {NodeBuilder} builder - The current node builder.
  15662. */
  15663. finish( /*builder*/ ) { }
  15664. /**
  15665. * This method is intended for implementing the direct light term and
  15666. * executed during the build process of directional, point and spot light nodes.
  15667. *
  15668. * @abstract
  15669. * @param {Object} lightData - The light data.
  15670. * @param {NodeBuilder} builder - The current node builder.
  15671. */
  15672. direct( /*lightData, builder*/ ) { }
  15673. /**
  15674. * This method is intended for implementing the direct light term for
  15675. * rect area light nodes.
  15676. *
  15677. * @abstract
  15678. * @param {Object} lightData - The light data.
  15679. * @param {NodeBuilder} builder - The current node builder.
  15680. */
  15681. directRectArea( /*lightData, builder*/ ) {}
  15682. /**
  15683. * This method is intended for implementing the indirect light term.
  15684. *
  15685. * @abstract
  15686. * @param {NodeBuilder} builder - The current node builder.
  15687. */
  15688. indirect( /*builder*/ ) { }
  15689. /**
  15690. * This method is intended for implementing the ambient occlusion term.
  15691. * Unlike other methods, this method must be called manually by the lighting
  15692. * model in its indirect term.
  15693. *
  15694. * @abstract
  15695. * @param {NodeBuilder} builder - The current node builder.
  15696. */
  15697. ambientOcclusion( /*input, stack, builder*/ ) { }
  15698. }
  15699. /**
  15700. * Represents the lighting model for unlit materials. The only light contribution
  15701. * is baked indirect lighting modulated with ambient occlusion and the material's
  15702. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  15703. *
  15704. * @augments LightingModel
  15705. */
  15706. class BasicLightingModel extends LightingModel {
  15707. /**
  15708. * Constructs a new basic lighting model.
  15709. */
  15710. constructor() {
  15711. super();
  15712. }
  15713. /**
  15714. * Implements the baked indirect lighting with its modulation.
  15715. *
  15716. * @param {NodeBuilder} builder - The current node builder.
  15717. */
  15718. indirect( { context } ) {
  15719. const ambientOcclusion = context.ambientOcclusion;
  15720. const reflectedLight = context.reflectedLight;
  15721. const irradianceLightMap = context.irradianceLightMap;
  15722. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  15723. // accumulation (baked indirect lighting only)
  15724. if ( irradianceLightMap ) {
  15725. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  15726. } else {
  15727. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  15728. }
  15729. // modulation
  15730. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15731. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  15732. }
  15733. /**
  15734. * Implements the environment mapping.
  15735. *
  15736. * @param {NodeBuilder} builder - The current node builder.
  15737. */
  15738. finish( builder ) {
  15739. const { material, context } = builder;
  15740. const outgoingLight = context.outgoingLight;
  15741. const envNode = builder.context.environment;
  15742. if ( envNode ) {
  15743. switch ( material.combine ) {
  15744. case MultiplyOperation:
  15745. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  15746. break;
  15747. case MixOperation:
  15748. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  15749. break;
  15750. case AddOperation:
  15751. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  15752. break;
  15753. default:
  15754. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  15755. break;
  15756. }
  15757. }
  15758. }
  15759. }
  15760. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  15761. /**
  15762. * Node material version of {@link MeshBasicMaterial}.
  15763. *
  15764. * @augments NodeMaterial
  15765. */
  15766. class MeshBasicNodeMaterial extends NodeMaterial {
  15767. static get type() {
  15768. return 'MeshBasicNodeMaterial';
  15769. }
  15770. /**
  15771. * Constructs a new mesh basic node material.
  15772. *
  15773. * @param {Object} [parameters] - The configuration parameter.
  15774. */
  15775. constructor( parameters ) {
  15776. super();
  15777. /**
  15778. * This flag can be used for type testing.
  15779. *
  15780. * @type {boolean}
  15781. * @readonly
  15782. * @default true
  15783. */
  15784. this.isMeshBasicNodeMaterial = true;
  15785. /**
  15786. * Although the basic material is by definition unlit, we set
  15787. * this property to `true` since we use a lighting model to compute
  15788. * the outgoing light of the fragment shader.
  15789. *
  15790. * @type {boolean}
  15791. * @default true
  15792. */
  15793. this.lights = true;
  15794. this.setDefaultValues( _defaultValues$9 );
  15795. this.setValues( parameters );
  15796. }
  15797. /**
  15798. * Basic materials are not affected by normal and bump maps so we
  15799. * return by default {@link normalViewGeometry}.
  15800. *
  15801. * @return {Node<vec3>} The normal node.
  15802. */
  15803. setupNormal() {
  15804. return directionToFaceDirection( normalViewGeometry ); // see #28839
  15805. }
  15806. /**
  15807. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15808. * to implement the default environment mapping.
  15809. *
  15810. * @param {NodeBuilder} builder - The current node builder.
  15811. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15812. */
  15813. setupEnvironment( builder ) {
  15814. const envNode = super.setupEnvironment( builder );
  15815. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15816. }
  15817. /**
  15818. * This method must be overwritten since light maps are evaluated
  15819. * with a special scaling factor for basic materials.
  15820. *
  15821. * @param {NodeBuilder} builder - The current node builder.
  15822. * @return {?BasicLightMapNode<vec3>} The light map node.
  15823. */
  15824. setupLightMap( builder ) {
  15825. let node = null;
  15826. if ( builder.material.lightMap ) {
  15827. node = new BasicLightMapNode( materialLightMap );
  15828. }
  15829. return node;
  15830. }
  15831. /**
  15832. * The material overwrites this method because `lights` is set to `true` but
  15833. * we still want to return the diffuse color as the outgoing light.
  15834. *
  15835. * @return {Node<vec3>} The outgoing light node.
  15836. */
  15837. setupOutgoingLight() {
  15838. return diffuseColor.rgb;
  15839. }
  15840. /**
  15841. * Setups the lighting model.
  15842. *
  15843. * @return {BasicLightingModel} The lighting model.
  15844. */
  15845. setupLightingModel() {
  15846. return new BasicLightingModel();
  15847. }
  15848. }
  15849. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  15850. // Original approximation by Christophe Schlick '94
  15851. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  15852. // Optimized variant (presented by Epic at SIGGRAPH '13)
  15853. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  15854. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  15855. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  15856. } ); // validated
  15857. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  15858. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  15859. } ); // validated
  15860. const G_BlinnPhong_Implicit = () => float( 0.25 );
  15861. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  15862. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  15863. } );
  15864. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15865. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15866. const dotNH = normalView.dot( halfDir ).clamp();
  15867. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15868. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  15869. const G = G_BlinnPhong_Implicit();
  15870. const D = D_BlinnPhong( { dotNH } );
  15871. return F.mul( G ).mul( D );
  15872. } );
  15873. /**
  15874. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  15875. *
  15876. * @augments BasicLightingModel
  15877. */
  15878. class PhongLightingModel extends BasicLightingModel {
  15879. /**
  15880. * Constructs a new phong lighting model.
  15881. *
  15882. * @param {boolean} [specular=true] - Whether specular is supported or not.
  15883. */
  15884. constructor( specular = true ) {
  15885. super();
  15886. /**
  15887. * Whether specular is supported or not. Set this to `false` if you are
  15888. * looking for a Lambert-like material meaning a material for non-shiny
  15889. * surfaces, without specular highlights.
  15890. *
  15891. * @type {boolean}
  15892. * @default true
  15893. */
  15894. this.specular = specular;
  15895. }
  15896. /**
  15897. * Implements the direct lighting. The specular portion is optional an can be controlled
  15898. * with the {@link PhongLightingModel#specular} flag.
  15899. *
  15900. * @param {Object} lightData - The light data.
  15901. */
  15902. direct( { lightDirection, lightColor, reflectedLight } ) {
  15903. const dotNL = normalView.dot( lightDirection ).clamp();
  15904. const irradiance = dotNL.mul( lightColor );
  15905. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15906. if ( this.specular === true ) {
  15907. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  15908. }
  15909. }
  15910. /**
  15911. * Implements the indirect lighting.
  15912. *
  15913. * @param {NodeBuilder} builder - The current node builder.
  15914. */
  15915. indirect( builder ) {
  15916. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  15917. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15918. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15919. }
  15920. }
  15921. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  15922. /**
  15923. * Node material version of {@link MeshLambertMaterial}.
  15924. *
  15925. * @augments NodeMaterial
  15926. */
  15927. class MeshLambertNodeMaterial extends NodeMaterial {
  15928. static get type() {
  15929. return 'MeshLambertNodeMaterial';
  15930. }
  15931. /**
  15932. * Constructs a new mesh lambert node material.
  15933. *
  15934. * @param {Object} [parameters] - The configuration parameter.
  15935. */
  15936. constructor( parameters ) {
  15937. super();
  15938. /**
  15939. * This flag can be used for type testing.
  15940. *
  15941. * @type {boolean}
  15942. * @readonly
  15943. * @default true
  15944. */
  15945. this.isMeshLambertNodeMaterial = true;
  15946. /**
  15947. * Set to `true` because lambert materials react on lights.
  15948. *
  15949. * @type {boolean}
  15950. * @default true
  15951. */
  15952. this.lights = true;
  15953. this.setDefaultValues( _defaultValues$8 );
  15954. this.setValues( parameters );
  15955. }
  15956. /**
  15957. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15958. * to implement the default environment mapping.
  15959. *
  15960. * @param {NodeBuilder} builder - The current node builder.
  15961. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15962. */
  15963. setupEnvironment( builder ) {
  15964. const envNode = super.setupEnvironment( builder );
  15965. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15966. }
  15967. /**
  15968. * Setups the lighting model.
  15969. *
  15970. * @return {PhongLightingModel} The lighting model.
  15971. */
  15972. setupLightingModel( /*builder*/ ) {
  15973. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  15974. }
  15975. }
  15976. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  15977. /**
  15978. * Node material version of {@link MeshPhongMaterial}.
  15979. *
  15980. * @augments NodeMaterial
  15981. */
  15982. class MeshPhongNodeMaterial extends NodeMaterial {
  15983. static get type() {
  15984. return 'MeshPhongNodeMaterial';
  15985. }
  15986. /**
  15987. * Constructs a new mesh lambert node material.
  15988. *
  15989. * @param {Object} [parameters] - The configuration parameter.
  15990. */
  15991. constructor( parameters ) {
  15992. super();
  15993. /**
  15994. * This flag can be used for type testing.
  15995. *
  15996. * @type {boolean}
  15997. * @readonly
  15998. * @default true
  15999. */
  16000. this.isMeshPhongNodeMaterial = true;
  16001. /**
  16002. * Set to `true` because phong materials react on lights.
  16003. *
  16004. * @type {boolean}
  16005. * @default true
  16006. */
  16007. this.lights = true;
  16008. /**
  16009. * The shininess of phong materials is by default inferred from the `shininess`
  16010. * property. This node property allows to overwrite the default
  16011. * and define the shininess with a node instead.
  16012. *
  16013. * If you don't want to overwrite the shininess but modify the existing
  16014. * value instead, use {@link materialShininess}.
  16015. *
  16016. * @type {?Node<float>}
  16017. * @default null
  16018. */
  16019. this.shininessNode = null;
  16020. /**
  16021. * The specular color of phong materials is by default inferred from the
  16022. * `specular` property. This node property allows to overwrite the default
  16023. * and define the specular color with a node instead.
  16024. *
  16025. * If you don't want to overwrite the specular color but modify the existing
  16026. * value instead, use {@link materialSpecular}.
  16027. *
  16028. * @type {?Node<vec3>}
  16029. * @default null
  16030. */
  16031. this.specularNode = null;
  16032. this.setDefaultValues( _defaultValues$7 );
  16033. this.setValues( parameters );
  16034. }
  16035. /**
  16036. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16037. * to implement the default environment mapping.
  16038. *
  16039. * @param {NodeBuilder} builder - The current node builder.
  16040. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16041. */
  16042. setupEnvironment( builder ) {
  16043. const envNode = super.setupEnvironment( builder );
  16044. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16045. }
  16046. /**
  16047. * Setups the lighting model.
  16048. *
  16049. * @return {PhongLightingModel} The lighting model.
  16050. */
  16051. setupLightingModel( /*builder*/ ) {
  16052. return new PhongLightingModel();
  16053. }
  16054. /**
  16055. * Setups the phong specific node variables.
  16056. *
  16057. * @param {NodeBuilder} builder - The current node builder.
  16058. */
  16059. setupVariants( /*builder*/ ) {
  16060. // SHININESS
  16061. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16062. shininess.assign( shininessNode );
  16063. // SPECULAR COLOR
  16064. const specularNode = this.specularNode || materialSpecular;
  16065. specularColor.assign( specularNode );
  16066. }
  16067. copy( source ) {
  16068. this.shininessNode = source.shininessNode;
  16069. this.specularNode = source.specularNode;
  16070. return super.copy( source );
  16071. }
  16072. }
  16073. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16074. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16075. return float( 0 );
  16076. }
  16077. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16078. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16079. return geometryRoughness;
  16080. } );
  16081. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16082. const { roughness } = inputs;
  16083. const geometryRoughness = getGeometryRoughness();
  16084. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16085. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16086. roughnessFactor = roughnessFactor.min( 1.0 );
  16087. return roughnessFactor;
  16088. } );
  16089. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16090. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16091. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16092. const a2 = alpha.pow2();
  16093. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16094. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16095. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16096. } ).setLayout( {
  16097. name: 'V_GGX_SmithCorrelated',
  16098. type: 'float',
  16099. inputs: [
  16100. { name: 'alpha', type: 'float' },
  16101. { name: 'dotNL', type: 'float' },
  16102. { name: 'dotNV', type: 'float' }
  16103. ]
  16104. } ); // validated
  16105. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16106. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16107. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16108. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16109. const v = div( 0.5, gv.add( gl ) );
  16110. return v.saturate();
  16111. } ).setLayout( {
  16112. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16113. type: 'float',
  16114. inputs: [
  16115. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16116. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16117. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16118. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16119. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16120. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16121. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16122. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16123. ]
  16124. } );
  16125. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  16126. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  16127. // alpha is "roughness squared" in Disney’s reparameterization
  16128. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  16129. const a2 = alpha.pow2();
  16130. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  16131. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  16132. } ).setLayout( {
  16133. name: 'D_GGX',
  16134. type: 'float',
  16135. inputs: [
  16136. { name: 'alpha', type: 'float' },
  16137. { name: 'dotNH', type: 'float' }
  16138. ]
  16139. } ); // validated
  16140. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  16141. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16142. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  16143. const a2 = alphaT.mul( alphaB );
  16144. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  16145. const v2 = v.dot( v );
  16146. const w2 = a2.div( v2 );
  16147. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  16148. } ).setLayout( {
  16149. name: 'D_GGX_Anisotropic',
  16150. type: 'float',
  16151. inputs: [
  16152. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16153. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16154. { name: 'dotNH', type: 'float', qualifier: 'in' },
  16155. { name: 'dotTH', type: 'float', qualifier: 'in' },
  16156. { name: 'dotBH', type: 'float', qualifier: 'in' }
  16157. ]
  16158. } );
  16159. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  16160. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16161. const alpha = roughness.pow2(); // UE4's roughness
  16162. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16163. const dotNL = normalView$1.dot( lightDirection ).clamp();
  16164. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16165. const dotNH = normalView$1.dot( halfDir ).clamp();
  16166. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16167. let F = F_Schlick( { f0, f90, dotVH } );
  16168. let V, D;
  16169. if ( defined( USE_IRIDESCENCE ) ) {
  16170. F = iridescence.mix( F, f );
  16171. }
  16172. if ( defined( USE_ANISOTROPY ) ) {
  16173. const dotTL = anisotropyT.dot( lightDirection );
  16174. const dotTV = anisotropyT.dot( positionViewDirection );
  16175. const dotTH = anisotropyT.dot( halfDir );
  16176. const dotBL = anisotropyB.dot( lightDirection );
  16177. const dotBV = anisotropyB.dot( positionViewDirection );
  16178. const dotBH = anisotropyB.dot( halfDir );
  16179. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16180. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16181. } else {
  16182. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16183. D = D_GGX( { alpha, dotNH } );
  16184. }
  16185. return F.mul( V ).mul( D );
  16186. } ); // validated
  16187. // Analytical approximation of the DFG LUT, one half of the
  16188. // split-sum approximation used in indirect specular lighting.
  16189. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  16190. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  16191. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16192. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  16193. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  16194. const r = roughness.mul( c0 ).add( c1 );
  16195. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  16196. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  16197. return fab;
  16198. } ).setLayout( {
  16199. name: 'DFGApprox',
  16200. type: 'vec2',
  16201. inputs: [
  16202. { name: 'roughness', type: 'float' },
  16203. { name: 'dotNV', type: 'vec3' }
  16204. ]
  16205. } );
  16206. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  16207. const { dotNV, specularColor, specularF90, roughness } = inputs;
  16208. const fab = DFGApprox( { dotNV, roughness } );
  16209. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16210. } );
  16211. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  16212. const x = dotVH.oneMinus().saturate();
  16213. const x2 = x.mul( x );
  16214. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  16215. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  16216. } ).setLayout( {
  16217. name: 'Schlick_to_F0',
  16218. type: 'vec3',
  16219. inputs: [
  16220. { name: 'f', type: 'vec3' },
  16221. { name: 'f90', type: 'float' },
  16222. { name: 'dotVH', type: 'float' }
  16223. ]
  16224. } );
  16225. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16226. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  16227. const alpha = roughness.pow2();
  16228. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  16229. const invAlpha = float( 1.0 ).div( alpha );
  16230. const cos2h = dotNH.pow2();
  16231. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  16232. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  16233. } ).setLayout( {
  16234. name: 'D_Charlie',
  16235. type: 'float',
  16236. inputs: [
  16237. { name: 'roughness', type: 'float' },
  16238. { name: 'dotNH', type: 'float' }
  16239. ]
  16240. } );
  16241. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16242. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  16243. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  16244. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  16245. } ).setLayout( {
  16246. name: 'V_Neubelt',
  16247. type: 'float',
  16248. inputs: [
  16249. { name: 'dotNV', type: 'float' },
  16250. { name: 'dotNL', type: 'float' }
  16251. ]
  16252. } );
  16253. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16254. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16255. const dotNL = normalView.dot( lightDirection ).clamp();
  16256. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16257. const dotNH = normalView.dot( halfDir ).clamp();
  16258. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  16259. const V = V_Neubelt( { dotNV, dotNL } );
  16260. return sheen.mul( D ).mul( V );
  16261. } );
  16262. // Rect Area Light
  16263. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  16264. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  16265. // code: https://github.com/selfshadow/ltc_code/
  16266. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  16267. const LUT_SIZE = 64.0;
  16268. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  16269. const LUT_BIAS = 0.5 / LUT_SIZE;
  16270. const dotNV = N.dot( V ).saturate();
  16271. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  16272. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  16273. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  16274. return uv;
  16275. } ).setLayout( {
  16276. name: 'LTC_Uv',
  16277. type: 'vec2',
  16278. inputs: [
  16279. { name: 'N', type: 'vec3' },
  16280. { name: 'V', type: 'vec3' },
  16281. { name: 'roughness', type: 'float' }
  16282. ]
  16283. } );
  16284. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  16285. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  16286. // An approximation of the form factor of a horizon-clipped rectangle.
  16287. const l = f.length();
  16288. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  16289. } ).setLayout( {
  16290. name: 'LTC_ClippedSphereFormFactor',
  16291. type: 'float',
  16292. inputs: [
  16293. { name: 'f', type: 'vec3' }
  16294. ]
  16295. } );
  16296. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  16297. const x = v1.dot( v2 );
  16298. const y = x.abs().toVar();
  16299. // rational polynomial approximation to theta / sin( theta ) / 2PI
  16300. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  16301. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  16302. const v = a.div( b );
  16303. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  16304. return v1.cross( v2 ).mul( theta_sintheta );
  16305. } ).setLayout( {
  16306. name: 'LTC_EdgeVectorFormFactor',
  16307. type: 'vec3',
  16308. inputs: [
  16309. { name: 'v1', type: 'vec3' },
  16310. { name: 'v2', type: 'vec3' }
  16311. ]
  16312. } );
  16313. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  16314. // bail if point is on back side of plane of light
  16315. // assumes ccw winding order of light vertices
  16316. const v1 = p1.sub( p0 ).toVar();
  16317. const v2 = p3.sub( p0 ).toVar();
  16318. const lightNormal = v1.cross( v2 );
  16319. const result = vec3().toVar();
  16320. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16321. // construct orthonormal basis around N
  16322. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  16323. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  16324. // compute transform
  16325. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  16326. // transform rect
  16327. // & project rect onto sphere
  16328. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  16329. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  16330. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  16331. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  16332. // calculate vector form factor
  16333. const vectorFormFactor = vec3( 0 ).toVar();
  16334. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16335. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16336. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16337. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16338. // adjust for horizon clipping
  16339. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  16340. } );
  16341. return result;
  16342. } ).setLayout( {
  16343. name: 'LTC_Evaluate',
  16344. type: 'vec3',
  16345. inputs: [
  16346. { name: 'N', type: 'vec3' },
  16347. { name: 'V', type: 'vec3' },
  16348. { name: 'P', type: 'vec3' },
  16349. { name: 'mInv', type: 'mat3' },
  16350. { name: 'p0', type: 'vec3' },
  16351. { name: 'p1', type: 'vec3' },
  16352. { name: 'p2', type: 'vec3' },
  16353. { name: 'p3', type: 'vec3' }
  16354. ]
  16355. } );
  16356. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16357. // bail if point is on back side of plane of light
  16358. // assumes ccw winding order of light vertices
  16359. const v1 = p1.sub( p0 ).toVar();
  16360. const v2 = p3.sub( p0 ).toVar();
  16361. const lightNormal = v1.cross( v2 );
  16362. const result = vec3().toVar();
  16363. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16364. // transform rect
  16365. // & project rect onto sphere
  16366. const coords0 = p0.sub( P ).normalize().toVar();
  16367. const coords1 = p1.sub( P ).normalize().toVar();
  16368. const coords2 = p2.sub( P ).normalize().toVar();
  16369. const coords3 = p3.sub( P ).normalize().toVar();
  16370. // calculate vector form factor
  16371. const vectorFormFactor = vec3( 0 ).toVar();
  16372. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16373. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16374. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16375. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16376. // adjust for horizon clipping
  16377. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16378. } );
  16379. return result;
  16380. } ).setLayout( {
  16381. name: 'LTC_Evaluate',
  16382. type: 'vec3',
  16383. inputs: [
  16384. { name: 'P', type: 'vec3' },
  16385. { name: 'p0', type: 'vec3' },
  16386. { name: 'p1', type: 'vec3' },
  16387. { name: 'p2', type: 'vec3' },
  16388. { name: 'p3', type: 'vec3' }
  16389. ]
  16390. } );
  16391. // Mipped Bicubic Texture Filtering by N8
  16392. // https://www.shadertoy.com/view/Dl2SDW
  16393. const bC = 1.0 / 6.0;
  16394. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  16395. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  16396. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  16397. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  16398. const g0 = ( a ) => w0( a ).add( w1( a ) );
  16399. const g1 = ( a ) => w2( a ).add( w3( a ) );
  16400. // h0 and h1 are the two offset functions
  16401. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  16402. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  16403. const bicubic = ( textureNode, texelSize, lod ) => {
  16404. const uv = textureNode.uvNode;
  16405. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  16406. const iuv = floor( uvScaled );
  16407. const fuv = fract( uvScaled );
  16408. const g0x = g0( fuv.x );
  16409. const g1x = g1( fuv.x );
  16410. const h0x = h0( fuv.x );
  16411. const h1x = h1( fuv.x );
  16412. const h0y = h0( fuv.y );
  16413. const h1y = h1( fuv.y );
  16414. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16415. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16416. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16417. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16418. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  16419. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  16420. return a.add( b );
  16421. };
  16422. /**
  16423. * Applies mipped bicubic texture filtering to the given texture node.
  16424. *
  16425. * @tsl
  16426. * @function
  16427. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16428. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  16429. * @return {Node} The filtered texture sample.
  16430. */
  16431. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  16432. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  16433. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  16434. const fLodSizeInv = div( 1.0, fLodSize );
  16435. const cLodSizeInv = div( 1.0, cLodSize );
  16436. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  16437. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  16438. return fract( lodNode ).mix( fSample, cSample );
  16439. } );
  16440. /**
  16441. * Applies mipped bicubic texture filtering to the given texture node.
  16442. *
  16443. * @tsl
  16444. * @function
  16445. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16446. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  16447. * @return {Node} The filtered texture sample.
  16448. */
  16449. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  16450. const lod = strength.mul( maxMipLevel( textureNode ) );
  16451. return textureBicubicLevel( textureNode, lod );
  16452. } );
  16453. //
  16454. // Transmission
  16455. //
  16456. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  16457. // Direction of refracted light.
  16458. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  16459. // Compute rotation-independent scaling of the model matrix.
  16460. const modelScale = vec3(
  16461. length( modelMatrix[ 0 ].xyz ),
  16462. length( modelMatrix[ 1 ].xyz ),
  16463. length( modelMatrix[ 2 ].xyz )
  16464. );
  16465. // The thickness is specified in local space.
  16466. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  16467. } ).setLayout( {
  16468. name: 'getVolumeTransmissionRay',
  16469. type: 'vec3',
  16470. inputs: [
  16471. { name: 'n', type: 'vec3' },
  16472. { name: 'v', type: 'vec3' },
  16473. { name: 'thickness', type: 'float' },
  16474. { name: 'ior', type: 'float' },
  16475. { name: 'modelMatrix', type: 'mat4' }
  16476. ]
  16477. } );
  16478. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16479. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16480. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16481. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16482. } ).setLayout( {
  16483. name: 'applyIorToRoughness',
  16484. type: 'float',
  16485. inputs: [
  16486. { name: 'roughness', type: 'float' },
  16487. { name: 'ior', type: 'float' }
  16488. ]
  16489. } );
  16490. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16491. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16492. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16493. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16494. const transmissionSample = vTexture.sample( fragCoord );
  16495. //const transmissionSample = viewportMipTexture( fragCoord );
  16496. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16497. return textureBicubicLevel( transmissionSample, lod );
  16498. } );
  16499. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16500. If( attenuationDistance.notEqual( 0 ), () => {
  16501. // Compute light attenuation using Beer's law.
  16502. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16503. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16504. return transmittance;
  16505. } );
  16506. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16507. return vec3( 1.0 );
  16508. } ).setLayout( {
  16509. name: 'volumeAttenuation',
  16510. type: 'vec3',
  16511. inputs: [
  16512. { name: 'transmissionDistance', type: 'float' },
  16513. { name: 'attenuationColor', type: 'vec3' },
  16514. { name: 'attenuationDistance', type: 'float' }
  16515. ]
  16516. } );
  16517. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16518. let transmittedLight, transmittance;
  16519. if ( dispersion ) {
  16520. transmittedLight = vec4().toVar();
  16521. transmittance = vec3().toVar();
  16522. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16523. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16524. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16525. const ior = iors.element( i );
  16526. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16527. const refractedRayExit = position.add( transmissionRay );
  16528. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16529. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16530. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16531. refractionCoords.addAssign( 1.0 );
  16532. refractionCoords.divAssign( 2.0 );
  16533. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16534. // Sample framebuffer to get pixel the refracted ray hits.
  16535. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16536. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16537. transmittedLight.a.addAssign( transmissionSample.a );
  16538. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16539. } );
  16540. transmittedLight.a.divAssign( 3.0 );
  16541. } else {
  16542. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16543. const refractedRayExit = position.add( transmissionRay );
  16544. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16545. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16546. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16547. refractionCoords.addAssign( 1.0 );
  16548. refractionCoords.divAssign( 2.0 );
  16549. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16550. // Sample framebuffer to get pixel the refracted ray hits.
  16551. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16552. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16553. }
  16554. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16555. const dotNV = n.dot( v ).clamp();
  16556. // Get the specular component.
  16557. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16558. dotNV,
  16559. specularColor,
  16560. specularF90,
  16561. roughness
  16562. } ) );
  16563. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16564. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16565. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16566. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16567. } );
  16568. //
  16569. // Iridescence
  16570. //
  16571. // XYZ to linear-sRGB color space
  16572. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16573. 3.2404542, -0.969266, 0.0556434,
  16574. -1.5371385, 1.8760108, -0.2040259,
  16575. -0.4985314, 0.0415560, 1.0572252
  16576. );
  16577. // Assume air interface for top
  16578. // Note: We don't handle the case fresnel0 == 1
  16579. const Fresnel0ToIor = ( fresnel0 ) => {
  16580. const sqrtF0 = fresnel0.sqrt();
  16581. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16582. };
  16583. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16584. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16585. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16586. };
  16587. // Fresnel equations for dielectric/dielectric interfaces.
  16588. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16589. // Evaluation XYZ sensitivity curves in Fourier space
  16590. const evalSensitivity = ( OPD, shift ) => {
  16591. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16592. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  16593. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  16594. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  16595. 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() );
  16596. 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() );
  16597. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  16598. const rgb = XYZ_TO_REC709.mul( xyz );
  16599. return rgb;
  16600. };
  16601. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  16602. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  16603. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  16604. // Evaluate the cosTheta on the base layer (Snell law)
  16605. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  16606. // Handle TIR:
  16607. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  16608. If( cosTheta2Sq.lessThan( 0 ), () => {
  16609. return vec3( 1.0 );
  16610. } );
  16611. const cosTheta2 = cosTheta2Sq.sqrt();
  16612. // First interface
  16613. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  16614. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  16615. //const R21 = R12;
  16616. const T121 = R12.oneMinus();
  16617. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  16618. const phi21 = float( Math.PI ).sub( phi12 );
  16619. // Second interface
  16620. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  16621. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  16622. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  16623. const phi23 = vec3(
  16624. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16625. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16626. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  16627. );
  16628. // Phase shift
  16629. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  16630. const phi = vec3( phi21 ).add( phi23 );
  16631. // Compound terms
  16632. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  16633. const r123 = R123.sqrt();
  16634. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  16635. // Reflectance term for m = 0 (DC term amplitude)
  16636. const C0 = R12.add( Rs );
  16637. const I = C0.toVar();
  16638. // Reflectance term for m > 0 (pairs of diracs)
  16639. const Cm = Rs.sub( T121 ).toVar();
  16640. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  16641. Cm.mulAssign( r123 );
  16642. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  16643. I.addAssign( Cm.mul( Sm ) );
  16644. } );
  16645. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  16646. return I.max( vec3( 0.0 ) );
  16647. } ).setLayout( {
  16648. name: 'evalIridescence',
  16649. type: 'vec3',
  16650. inputs: [
  16651. { name: 'outsideIOR', type: 'float' },
  16652. { name: 'eta2', type: 'float' },
  16653. { name: 'cosTheta1', type: 'float' },
  16654. { name: 'thinFilmThickness', type: 'float' },
  16655. { name: 'baseF0', type: 'vec3' }
  16656. ]
  16657. } );
  16658. //
  16659. // Sheen
  16660. //
  16661. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  16662. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  16663. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  16664. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  16665. const dotNV = normal.dot( viewDir ).saturate();
  16666. const r2 = roughness.pow2();
  16667. const a = select(
  16668. roughness.lessThan( 0.25 ),
  16669. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  16670. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  16671. );
  16672. const b = select(
  16673. roughness.lessThan( 0.25 ),
  16674. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  16675. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  16676. );
  16677. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  16678. return DG.mul( 1.0 / Math.PI ).saturate();
  16679. } );
  16680. const clearcoatF0 = vec3( 0.04 );
  16681. const clearcoatF90 = float( 1 );
  16682. /**
  16683. * Represents the lighting model for a PBR material.
  16684. *
  16685. * @augments LightingModel
  16686. */
  16687. class PhysicalLightingModel extends LightingModel {
  16688. /**
  16689. * Constructs a new physical lighting model.
  16690. *
  16691. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  16692. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  16693. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  16694. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  16695. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  16696. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  16697. */
  16698. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  16699. super();
  16700. /**
  16701. * Whether clearcoat is supported or not.
  16702. *
  16703. * @type {boolean}
  16704. * @default false
  16705. */
  16706. this.clearcoat = clearcoat;
  16707. /**
  16708. * Whether sheen is supported or not.
  16709. *
  16710. * @type {boolean}
  16711. * @default false
  16712. */
  16713. this.sheen = sheen;
  16714. /**
  16715. * Whether iridescence is supported or not.
  16716. *
  16717. * @type {boolean}
  16718. * @default false
  16719. */
  16720. this.iridescence = iridescence;
  16721. /**
  16722. * Whether anisotropy is supported or not.
  16723. *
  16724. * @type {boolean}
  16725. * @default false
  16726. */
  16727. this.anisotropy = anisotropy;
  16728. /**
  16729. * Whether transmission is supported or not.
  16730. *
  16731. * @type {boolean}
  16732. * @default false
  16733. */
  16734. this.transmission = transmission;
  16735. /**
  16736. * Whether dispersion is supported or not.
  16737. *
  16738. * @type {boolean}
  16739. * @default false
  16740. */
  16741. this.dispersion = dispersion;
  16742. /**
  16743. * The clear coat radiance.
  16744. *
  16745. * @type {?Node}
  16746. * @default null
  16747. */
  16748. this.clearcoatRadiance = null;
  16749. /**
  16750. * The clear coat specular direct.
  16751. *
  16752. * @type {?Node}
  16753. * @default null
  16754. */
  16755. this.clearcoatSpecularDirect = null;
  16756. /**
  16757. * The clear coat specular indirect.
  16758. *
  16759. * @type {?Node}
  16760. * @default null
  16761. */
  16762. this.clearcoatSpecularIndirect = null;
  16763. /**
  16764. * The sheen specular direct.
  16765. *
  16766. * @type {?Node}
  16767. * @default null
  16768. */
  16769. this.sheenSpecularDirect = null;
  16770. /**
  16771. * The sheen specular indirect.
  16772. *
  16773. * @type {?Node}
  16774. * @default null
  16775. */
  16776. this.sheenSpecularIndirect = null;
  16777. /**
  16778. * The iridescence Fresnel.
  16779. *
  16780. * @type {?Node}
  16781. * @default null
  16782. */
  16783. this.iridescenceFresnel = null;
  16784. /**
  16785. * The iridescence F0.
  16786. *
  16787. * @type {?Node}
  16788. * @default null
  16789. */
  16790. this.iridescenceF0 = null;
  16791. }
  16792. /**
  16793. * Depending on what features are requested, the method prepares certain node variables
  16794. * which are later used for lighting computations.
  16795. *
  16796. * @param {NodeBuilder} builder - The current node builder.
  16797. */
  16798. start( builder ) {
  16799. if ( this.clearcoat === true ) {
  16800. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  16801. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  16802. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  16803. }
  16804. if ( this.sheen === true ) {
  16805. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  16806. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  16807. }
  16808. if ( this.iridescence === true ) {
  16809. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  16810. this.iridescenceFresnel = evalIridescence( {
  16811. outsideIOR: float( 1.0 ),
  16812. eta2: iridescenceIOR,
  16813. cosTheta1: dotNVi,
  16814. thinFilmThickness: iridescenceThickness,
  16815. baseF0: specularColor
  16816. } );
  16817. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  16818. }
  16819. if ( this.transmission === true ) {
  16820. const position = positionWorld;
  16821. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  16822. const n = normalWorld;
  16823. const context = builder.context;
  16824. context.backdrop = getIBLVolumeRefraction(
  16825. n,
  16826. v,
  16827. roughness,
  16828. diffuseColor,
  16829. specularColor,
  16830. specularF90, // specularF90
  16831. position, // positionWorld
  16832. modelWorldMatrix, // modelMatrix
  16833. cameraViewMatrix, // viewMatrix
  16834. cameraProjectionMatrix, // projMatrix
  16835. ior,
  16836. thickness,
  16837. attenuationColor,
  16838. attenuationDistance,
  16839. this.dispersion ? dispersion : null
  16840. );
  16841. context.backdropAlpha = transmission;
  16842. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  16843. }
  16844. super.start( builder );
  16845. }
  16846. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  16847. // Approximates multi-scattering in order to preserve energy.
  16848. // http://www.jcgt.org/published/0008/01/03/
  16849. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  16850. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16851. const fab = DFGApprox( { roughness, dotNV } );
  16852. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  16853. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16854. const Ess = fab.x.add( fab.y );
  16855. const Ems = Ess.oneMinus();
  16856. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  16857. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  16858. singleScatter.addAssign( FssEss );
  16859. multiScatter.addAssign( Fms.mul( Ems ) );
  16860. }
  16861. /**
  16862. * Implements the direct light.
  16863. *
  16864. * @param {Object} lightData - The light data.
  16865. * @param {NodeBuilder} builder - The current node builder.
  16866. */
  16867. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  16868. const dotNL = normalView.dot( lightDirection ).clamp();
  16869. const irradiance = dotNL.mul( lightColor );
  16870. if ( this.sheen === true ) {
  16871. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  16872. }
  16873. if ( this.clearcoat === true ) {
  16874. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  16875. const ccIrradiance = dotNLcc.mul( lightColor );
  16876. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  16877. }
  16878. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16879. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX( { lightDirection, f0: specularColor, f90: 1, roughness, iridescence: this.iridescence, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  16880. }
  16881. /**
  16882. * This method is intended for implementing the direct light term for
  16883. * rect area light nodes.
  16884. *
  16885. * @param {Object} input - The input data.
  16886. * @param {NodeBuilder} builder - The current node builder.
  16887. */
  16888. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  16889. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  16890. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  16891. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  16892. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  16893. const N = normalView;
  16894. const V = positionViewDirection;
  16895. const P = positionView.toVar();
  16896. const uv = LTC_Uv( { N, V, roughness } );
  16897. const t1 = ltc_1.sample( uv ).toVar();
  16898. const t2 = ltc_2.sample( uv ).toVar();
  16899. const mInv = mat3(
  16900. vec3( t1.x, 0, t1.y ),
  16901. vec3( 0, 1, 0 ),
  16902. vec3( t1.z, 0, t1.w )
  16903. ).toVar();
  16904. // LTC Fresnel Approximation by Stephen Hill
  16905. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  16906. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  16907. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  16908. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseColor ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  16909. }
  16910. /**
  16911. * Implements the indirect lighting.
  16912. *
  16913. * @param {NodeBuilder} builder - The current node builder.
  16914. */
  16915. indirect( builder ) {
  16916. this.indirectDiffuse( builder );
  16917. this.indirectSpecular( builder );
  16918. this.ambientOcclusion( builder );
  16919. }
  16920. /**
  16921. * Implements the indirect diffuse term.
  16922. *
  16923. * @param {NodeBuilder} builder - The current node builder.
  16924. */
  16925. indirectDiffuse( builder ) {
  16926. const { irradiance, reflectedLight } = builder.context;
  16927. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16928. }
  16929. /**
  16930. * Implements the indirect specular term.
  16931. *
  16932. * @param {NodeBuilder} builder - The current node builder.
  16933. */
  16934. indirectSpecular( builder ) {
  16935. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  16936. if ( this.sheen === true ) {
  16937. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  16938. sheen,
  16939. IBLSheenBRDF( {
  16940. normal: normalView,
  16941. viewDir: positionViewDirection,
  16942. roughness: sheenRoughness
  16943. } )
  16944. ) );
  16945. }
  16946. if ( this.clearcoat === true ) {
  16947. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16948. const clearcoatEnv = EnvironmentBRDF( {
  16949. dotNV: dotNVcc,
  16950. specularColor: clearcoatF0,
  16951. specularF90: clearcoatF90,
  16952. roughness: clearcoatRoughness
  16953. } );
  16954. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  16955. }
  16956. // Both indirect specular and indirect diffuse light accumulate here
  16957. const singleScattering = vec3().toVar( 'singleScattering' );
  16958. const multiScattering = vec3().toVar( 'multiScattering' );
  16959. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  16960. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  16961. const totalScattering = singleScattering.add( multiScattering );
  16962. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  16963. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  16964. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  16965. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  16966. }
  16967. /**
  16968. * Implements the ambient occlusion term.
  16969. *
  16970. * @param {NodeBuilder} builder - The current node builder.
  16971. */
  16972. ambientOcclusion( builder ) {
  16973. const { ambientOcclusion, reflectedLight } = builder.context;
  16974. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16975. const aoNV = dotNV.add( ambientOcclusion );
  16976. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  16977. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  16978. if ( this.clearcoat === true ) {
  16979. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  16980. }
  16981. if ( this.sheen === true ) {
  16982. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  16983. }
  16984. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16985. reflectedLight.indirectSpecular.mulAssign( aoNode );
  16986. }
  16987. /**
  16988. * Used for final lighting accumulations depending on the requested features.
  16989. *
  16990. * @param {NodeBuilder} builder - The current node builder.
  16991. */
  16992. finish( { context } ) {
  16993. const { outgoingLight } = context;
  16994. if ( this.clearcoat === true ) {
  16995. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16996. const Fcc = F_Schlick( {
  16997. dotVH: dotNVcc,
  16998. f0: clearcoatF0,
  16999. f90: clearcoatF90
  17000. } );
  17001. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  17002. outgoingLight.assign( clearcoatLight );
  17003. }
  17004. if ( this.sheen === true ) {
  17005. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  17006. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  17007. outgoingLight.assign( sheenLight );
  17008. }
  17009. }
  17010. }
  17011. // These defines must match with PMREMGenerator
  17012. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17013. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17014. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17015. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17016. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17017. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17018. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17019. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17020. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  17021. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  17022. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  17023. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  17024. // These shader functions convert between the UV coordinates of a single face of
  17025. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  17026. // sampling a textureCube (not generally normalized ).
  17027. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  17028. const absDirection = vec3( abs( direction ) ).toVar();
  17029. const face = float( -1 ).toVar();
  17030. If( absDirection.x.greaterThan( absDirection.z ), () => {
  17031. If( absDirection.x.greaterThan( absDirection.y ), () => {
  17032. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  17033. } ).Else( () => {
  17034. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17035. } );
  17036. } ).Else( () => {
  17037. If( absDirection.z.greaterThan( absDirection.y ), () => {
  17038. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  17039. } ).Else( () => {
  17040. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17041. } );
  17042. } );
  17043. return face;
  17044. } ).setLayout( {
  17045. name: 'getFace',
  17046. type: 'float',
  17047. inputs: [
  17048. { name: 'direction', type: 'vec3' }
  17049. ]
  17050. } );
  17051. // RH coordinate system; PMREM face-indexing convention
  17052. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  17053. const uv = vec2().toVar();
  17054. If( face.equal( 0.0 ), () => {
  17055. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  17056. } ).ElseIf( face.equal( 1.0 ), () => {
  17057. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  17058. } ).ElseIf( face.equal( 2.0 ), () => {
  17059. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  17060. } ).ElseIf( face.equal( 3.0 ), () => {
  17061. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  17062. } ).ElseIf( face.equal( 4.0 ), () => {
  17063. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  17064. } ).Else( () => {
  17065. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  17066. } );
  17067. return mul( 0.5, uv.add( 1.0 ) );
  17068. } ).setLayout( {
  17069. name: 'getUV',
  17070. type: 'vec2',
  17071. inputs: [
  17072. { name: 'direction', type: 'vec3' },
  17073. { name: 'face', type: 'float' }
  17074. ]
  17075. } );
  17076. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  17077. const mip = float( 0.0 ).toVar();
  17078. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  17079. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  17080. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  17081. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  17082. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  17083. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  17084. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  17085. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  17086. } ).Else( () => {
  17087. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  17088. } );
  17089. return mip;
  17090. } ).setLayout( {
  17091. name: 'roughnessToMip',
  17092. type: 'float',
  17093. inputs: [
  17094. { name: 'roughness', type: 'float' }
  17095. ]
  17096. } );
  17097. // RH coordinate system; PMREM face-indexing convention
  17098. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  17099. const uv = uv_immutable.toVar();
  17100. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  17101. const direction = vec3( uv, 1.0 ).toVar();
  17102. If( face.equal( 0.0 ), () => {
  17103. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  17104. } ).ElseIf( face.equal( 1.0 ), () => {
  17105. direction.assign( direction.xzy );
  17106. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  17107. } ).ElseIf( face.equal( 2.0 ), () => {
  17108. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  17109. } ).ElseIf( face.equal( 3.0 ), () => {
  17110. direction.assign( direction.zyx );
  17111. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  17112. } ).ElseIf( face.equal( 4.0 ), () => {
  17113. direction.assign( direction.xzy );
  17114. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  17115. } ).ElseIf( face.equal( 5.0 ), () => {
  17116. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  17117. } );
  17118. return direction;
  17119. } ).setLayout( {
  17120. name: 'getDirection',
  17121. type: 'vec3',
  17122. inputs: [
  17123. { name: 'uv', type: 'vec2' },
  17124. { name: 'face', type: 'float' }
  17125. ]
  17126. } );
  17127. //
  17128. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17129. const roughness = float( roughness_immutable );
  17130. const sampleDir = vec3( sampleDir_immutable );
  17131. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  17132. const mipF = fract( mip );
  17133. const mipInt = floor( mip );
  17134. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17135. If( mipF.notEqual( 0.0 ), () => {
  17136. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17137. color0.assign( mix( color0, color1, mipF ) );
  17138. } );
  17139. return color0;
  17140. } );
  17141. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17142. const mipInt = float( mipInt_immutable ).toVar();
  17143. const direction = vec3( direction_immutable );
  17144. const face = float( getFace( direction ) ).toVar();
  17145. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  17146. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  17147. const faceSize = float( exp2( mipInt ) ).toVar();
  17148. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  17149. If( face.greaterThan( 2.0 ), () => {
  17150. uv.y.addAssign( faceSize );
  17151. face.subAssign( 3.0 );
  17152. } );
  17153. uv.x.addAssign( face.mul( faceSize ) );
  17154. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  17155. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  17156. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  17157. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  17158. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  17159. } );
  17160. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17161. const cosTheta = cos( theta );
  17162. // Rodrigues' axis-angle rotation
  17163. const sampleDirection = outputDirection.mul( cosTheta )
  17164. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  17165. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  17166. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17167. } );
  17168. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17169. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  17170. If( axis.equal( vec3( 0.0 ) ), () => {
  17171. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  17172. } );
  17173. axis.assign( normalize( axis ) );
  17174. const gl_FragColor = vec3().toVar();
  17175. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17176. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  17177. If( i.greaterThanEqual( samples ), () => {
  17178. Break();
  17179. } );
  17180. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  17181. 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 } ) ) );
  17182. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17183. } );
  17184. return vec4( gl_FragColor, 1 );
  17185. } );
  17186. const LOD_MIN = 4;
  17187. // The standard deviations (radians) associated with the extra mips. These are
  17188. // chosen to approximate a Trowbridge-Reitz distribution function times the
  17189. // geometric shadowing function. These sigma values squared must match the
  17190. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  17191. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  17192. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  17193. // samples and exit early, but not recompile the shader.
  17194. const MAX_SAMPLES = 20;
  17195. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  17196. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  17197. const _clearColor$2 = /*@__PURE__*/ new Color();
  17198. let _oldTarget = null;
  17199. let _oldActiveCubeFace = 0;
  17200. let _oldActiveMipmapLevel = 0;
  17201. // Golden Ratio
  17202. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  17203. const INV_PHI = 1 / PHI;
  17204. // Vertices of a dodecahedron (except the opposites, which represent the
  17205. // same axis), used as axis directions evenly spread on a sphere.
  17206. const _axisDirections = [
  17207. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  17208. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  17209. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  17210. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  17211. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  17212. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  17213. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  17214. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  17215. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  17216. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  17217. ];
  17218. const _origin = /*@__PURE__*/ new Vector3();
  17219. // maps blur materials to their uniforms dictionary
  17220. const _uniformsMap = new WeakMap();
  17221. // WebGPU Face indices
  17222. const _faceLib = [
  17223. 3, 1, 5,
  17224. 0, 4, 2
  17225. ];
  17226. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  17227. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  17228. /**
  17229. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  17230. * (PMREM) from a cubeMap environment texture. This allows different levels of
  17231. * blur to be quickly accessed based on material roughness. It is packed into a
  17232. * special CubeUV format that allows us to perform custom interpolation so that
  17233. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  17234. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  17235. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  17236. * higher roughness levels. In this way we maintain resolution to smoothly
  17237. * interpolate diffuse lighting while limiting sampling computation.
  17238. *
  17239. * Paper: Fast, Accurate Image-Based Lighting:
  17240. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  17241. */
  17242. class PMREMGenerator {
  17243. /**
  17244. * Constructs a new PMREM generator.
  17245. *
  17246. * @param {Renderer} renderer - The renderer.
  17247. */
  17248. constructor( renderer ) {
  17249. this._renderer = renderer;
  17250. this._pingPongRenderTarget = null;
  17251. this._lodMax = 0;
  17252. this._cubeSize = 0;
  17253. this._lodPlanes = [];
  17254. this._sizeLods = [];
  17255. this._sigmas = [];
  17256. this._lodMeshes = [];
  17257. this._blurMaterial = null;
  17258. this._cubemapMaterial = null;
  17259. this._equirectMaterial = null;
  17260. this._backgroundBox = null;
  17261. }
  17262. get _hasInitialized() {
  17263. return this._renderer.hasInitialized();
  17264. }
  17265. /**
  17266. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17267. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17268. * in radians to be applied to the scene before PMREM generation. Optional near
  17269. * and far planes ensure the scene is rendered in its entirety.
  17270. *
  17271. * @param {Scene} scene - The scene to be captured.
  17272. * @param {number} [sigma=0] - The blur radius in radians.
  17273. * @param {number} [near=0.1] - The near plane distance.
  17274. * @param {number} [far=100] - The far plane distance.
  17275. * @param {Object} [options={}] - The configuration options.
  17276. * @param {number} [options.size=256] - The texture size of the PMREM.
  17277. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  17278. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17279. * @return {RenderTarget} The resulting PMREM.
  17280. * @see {@link PMREMGenerator#fromSceneAsync}
  17281. */
  17282. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17283. const {
  17284. size = 256,
  17285. position = _origin,
  17286. renderTarget = null,
  17287. } = options;
  17288. this._setSize( size );
  17289. if ( this._hasInitialized === false ) {
  17290. warn( 'PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  17291. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17292. options.renderTarget = cubeUVRenderTarget;
  17293. this.fromSceneAsync( scene, sigma, near, far, options );
  17294. return cubeUVRenderTarget;
  17295. }
  17296. _oldTarget = this._renderer.getRenderTarget();
  17297. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17298. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17299. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17300. cubeUVRenderTarget.depthBuffer = true;
  17301. this._init( cubeUVRenderTarget );
  17302. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  17303. if ( sigma > 0 ) {
  17304. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  17305. }
  17306. this._applyPMREM( cubeUVRenderTarget );
  17307. this._cleanup( cubeUVRenderTarget );
  17308. return cubeUVRenderTarget;
  17309. }
  17310. /**
  17311. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17312. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17313. * in radians to be applied to the scene before PMREM generation. Optional near
  17314. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  17315. * is placed at the origin).
  17316. *
  17317. * @param {Scene} scene - The scene to be captured.
  17318. * @param {number} [sigma=0] - The blur radius in radians.
  17319. * @param {number} [near=0.1] - The near plane distance.
  17320. * @param {number} [far=100] - The far plane distance.
  17321. * @param {Object} [options={}] - The configuration options.
  17322. * @param {number} [options.size=256] - The texture size of the PMREM.
  17323. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  17324. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17325. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  17326. * @see {@link PMREMGenerator#fromScene}
  17327. */
  17328. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17329. if ( this._hasInitialized === false ) await this._renderer.init();
  17330. return this.fromScene( scene, sigma, near, far, options );
  17331. }
  17332. /**
  17333. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17334. * or HDR. The ideal input image size is 1k (1024 x 512),
  17335. * as this matches best with the 256 x 256 cubemap output.
  17336. *
  17337. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17338. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17339. * @return {RenderTarget} The resulting PMREM.
  17340. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  17341. */
  17342. fromEquirectangular( equirectangular, renderTarget = null ) {
  17343. if ( this._hasInitialized === false ) {
  17344. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  17345. this._setSizeFromTexture( equirectangular );
  17346. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17347. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  17348. return cubeUVRenderTarget;
  17349. }
  17350. return this._fromTexture( equirectangular, renderTarget );
  17351. }
  17352. /**
  17353. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17354. * or HDR. The ideal input image size is 1k (1024 x 512),
  17355. * as this matches best with the 256 x 256 cubemap output.
  17356. *
  17357. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17358. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17359. * @return {Promise<RenderTarget>} The resulting PMREM.
  17360. * @see {@link PMREMGenerator#fromEquirectangular}
  17361. */
  17362. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  17363. if ( this._hasInitialized === false ) await this._renderer.init();
  17364. return this._fromTexture( equirectangular, renderTarget );
  17365. }
  17366. /**
  17367. * Generates a PMREM from an cubemap texture, which can be either LDR
  17368. * or HDR. The ideal input cube size is 256 x 256,
  17369. * as this matches best with the 256 x 256 cubemap output.
  17370. *
  17371. * @param {Texture} cubemap - The cubemap texture to be converted.
  17372. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17373. * @return {RenderTarget} The resulting PMREM.
  17374. * @see {@link PMREMGenerator#fromCubemapAsync}
  17375. */
  17376. fromCubemap( cubemap, renderTarget = null ) {
  17377. if ( this._hasInitialized === false ) {
  17378. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  17379. this._setSizeFromTexture( cubemap );
  17380. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17381. this.fromCubemapAsync( cubemap, renderTarget );
  17382. return cubeUVRenderTarget;
  17383. }
  17384. return this._fromTexture( cubemap, renderTarget );
  17385. }
  17386. /**
  17387. * Generates a PMREM from an cubemap texture, which can be either LDR
  17388. * or HDR. The ideal input cube size is 256 x 256,
  17389. * with the 256 x 256 cubemap output.
  17390. *
  17391. * @param {Texture} cubemap - The cubemap texture to be converted.
  17392. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17393. * @return {Promise<RenderTarget>} The resulting PMREM.
  17394. * @see {@link PMREMGenerator#fromCubemap}
  17395. */
  17396. async fromCubemapAsync( cubemap, renderTarget = null ) {
  17397. if ( this._hasInitialized === false ) await this._renderer.init();
  17398. return this._fromTexture( cubemap, renderTarget );
  17399. }
  17400. /**
  17401. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  17402. * your texture's network fetch for increased concurrency.
  17403. *
  17404. * @returns {Promise}
  17405. */
  17406. async compileCubemapShader() {
  17407. if ( this._cubemapMaterial === null ) {
  17408. this._cubemapMaterial = _getCubemapMaterial();
  17409. await this._compileMaterial( this._cubemapMaterial );
  17410. }
  17411. }
  17412. /**
  17413. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  17414. * your texture's network fetch for increased concurrency.
  17415. *
  17416. * @returns {Promise}
  17417. */
  17418. async compileEquirectangularShader() {
  17419. if ( this._equirectMaterial === null ) {
  17420. this._equirectMaterial = _getEquirectMaterial();
  17421. await this._compileMaterial( this._equirectMaterial );
  17422. }
  17423. }
  17424. /**
  17425. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  17426. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  17427. * one of them will cause any others to also become unusable.
  17428. */
  17429. dispose() {
  17430. this._dispose();
  17431. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  17432. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  17433. if ( this._backgroundBox !== null ) {
  17434. this._backgroundBox.geometry.dispose();
  17435. this._backgroundBox.material.dispose();
  17436. }
  17437. }
  17438. // private interface
  17439. _setSizeFromTexture( texture ) {
  17440. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  17441. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  17442. } else { // Equirectangular
  17443. this._setSize( texture.image.width / 4 );
  17444. }
  17445. }
  17446. _setSize( cubeSize ) {
  17447. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  17448. this._cubeSize = Math.pow( 2, this._lodMax );
  17449. }
  17450. _dispose() {
  17451. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  17452. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  17453. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  17454. this._lodPlanes[ i ].dispose();
  17455. }
  17456. }
  17457. _cleanup( outputTarget ) {
  17458. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  17459. outputTarget.scissorTest = false;
  17460. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  17461. }
  17462. _fromTexture( texture, renderTarget ) {
  17463. this._setSizeFromTexture( texture );
  17464. _oldTarget = this._renderer.getRenderTarget();
  17465. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17466. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17467. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17468. this._init( cubeUVRenderTarget );
  17469. this._textureToCubeUV( texture, cubeUVRenderTarget );
  17470. this._applyPMREM( cubeUVRenderTarget );
  17471. this._cleanup( cubeUVRenderTarget );
  17472. return cubeUVRenderTarget;
  17473. }
  17474. _allocateTarget() {
  17475. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  17476. const height = 4 * this._cubeSize;
  17477. const cubeUVRenderTarget = _createRenderTarget( width, height );
  17478. return cubeUVRenderTarget;
  17479. }
  17480. _init( renderTarget ) {
  17481. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17482. if ( this._pingPongRenderTarget !== null ) {
  17483. this._dispose();
  17484. }
  17485. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  17486. const { _lodMax } = this;
  17487. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  17488. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  17489. }
  17490. }
  17491. async _compileMaterial( material ) {
  17492. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  17493. await this._renderer.compile( tmpMesh, _flatCamera );
  17494. }
  17495. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  17496. const cubeCamera = _cubeCamera;
  17497. cubeCamera.near = near;
  17498. cubeCamera.far = far;
  17499. // px, py, pz, nx, ny, nz
  17500. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  17501. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  17502. const renderer = this._renderer;
  17503. const originalAutoClear = renderer.autoClear;
  17504. renderer.getClearColor( _clearColor$2 );
  17505. renderer.autoClear = false;
  17506. let backgroundBox = this._backgroundBox;
  17507. if ( backgroundBox === null ) {
  17508. const backgroundMaterial = new MeshBasicMaterial( {
  17509. name: 'PMREM.Background',
  17510. side: BackSide,
  17511. depthWrite: false,
  17512. depthTest: false
  17513. } );
  17514. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  17515. }
  17516. let useSolidColor = false;
  17517. const background = scene.background;
  17518. if ( background ) {
  17519. if ( background.isColor ) {
  17520. backgroundBox.material.color.copy( background );
  17521. scene.background = null;
  17522. useSolidColor = true;
  17523. }
  17524. } else {
  17525. backgroundBox.material.color.copy( _clearColor$2 );
  17526. useSolidColor = true;
  17527. }
  17528. renderer.setRenderTarget( cubeUVRenderTarget );
  17529. renderer.clear();
  17530. if ( useSolidColor ) {
  17531. renderer.render( backgroundBox, cubeCamera );
  17532. }
  17533. for ( let i = 0; i < 6; i ++ ) {
  17534. const col = i % 3;
  17535. if ( col === 0 ) {
  17536. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17537. cubeCamera.position.set( position.x, position.y, position.z );
  17538. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  17539. } else if ( col === 1 ) {
  17540. cubeCamera.up.set( 0, 0, upSign[ i ] );
  17541. cubeCamera.position.set( position.x, position.y, position.z );
  17542. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  17543. } else {
  17544. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17545. cubeCamera.position.set( position.x, position.y, position.z );
  17546. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  17547. }
  17548. const size = this._cubeSize;
  17549. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  17550. renderer.render( scene, cubeCamera );
  17551. }
  17552. renderer.autoClear = originalAutoClear;
  17553. scene.background = background;
  17554. }
  17555. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  17556. const renderer = this._renderer;
  17557. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  17558. if ( isCubeTexture ) {
  17559. if ( this._cubemapMaterial === null ) {
  17560. this._cubemapMaterial = _getCubemapMaterial( texture );
  17561. }
  17562. } else {
  17563. if ( this._equirectMaterial === null ) {
  17564. this._equirectMaterial = _getEquirectMaterial( texture );
  17565. }
  17566. }
  17567. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  17568. material.fragmentNode.value = texture;
  17569. const mesh = this._lodMeshes[ 0 ];
  17570. mesh.material = material;
  17571. const size = this._cubeSize;
  17572. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  17573. renderer.setRenderTarget( cubeUVRenderTarget );
  17574. renderer.render( mesh, _flatCamera );
  17575. }
  17576. _applyPMREM( cubeUVRenderTarget ) {
  17577. const renderer = this._renderer;
  17578. const autoClear = renderer.autoClear;
  17579. renderer.autoClear = false;
  17580. const n = this._lodPlanes.length;
  17581. for ( let i = 1; i < n; i ++ ) {
  17582. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  17583. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  17584. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  17585. }
  17586. renderer.autoClear = autoClear;
  17587. }
  17588. /**
  17589. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  17590. * vertically and horizontally, but this breaks down on a cube. Here we apply
  17591. * the blur latitudinally (around the poles), and then longitudinally (towards
  17592. * the poles) to approximate the orthogonally-separable blur. It is least
  17593. * accurate at the poles, but still does a decent job.
  17594. *
  17595. * @private
  17596. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  17597. * @param {number} lodIn - The input level-of-detail.
  17598. * @param {number} lodOut - The output level-of-detail.
  17599. * @param {number} sigma - The blur radius in radians.
  17600. * @param {Vector3} [poleAxis] - The pole axis.
  17601. */
  17602. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  17603. const pingPongRenderTarget = this._pingPongRenderTarget;
  17604. this._halfBlur(
  17605. cubeUVRenderTarget,
  17606. pingPongRenderTarget,
  17607. lodIn,
  17608. lodOut,
  17609. sigma,
  17610. 'latitudinal',
  17611. poleAxis );
  17612. this._halfBlur(
  17613. pingPongRenderTarget,
  17614. cubeUVRenderTarget,
  17615. lodOut,
  17616. lodOut,
  17617. sigma,
  17618. 'longitudinal',
  17619. poleAxis );
  17620. }
  17621. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  17622. const renderer = this._renderer;
  17623. const blurMaterial = this._blurMaterial;
  17624. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  17625. error( 'blur direction must be either latitudinal or longitudinal!' );
  17626. }
  17627. // Number of standard deviations at which to cut off the discrete approximation.
  17628. const STANDARD_DEVIATIONS = 3;
  17629. const blurMesh = this._lodMeshes[ lodOut ];
  17630. blurMesh.material = blurMaterial;
  17631. const blurUniforms = _uniformsMap.get( blurMaterial );
  17632. const pixels = this._sizeLods[ lodIn ] - 1;
  17633. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  17634. const sigmaPixels = sigmaRadians / radiansPerPixel;
  17635. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  17636. if ( samples > MAX_SAMPLES ) {
  17637. warn( `sigmaRadians, ${
  17638. sigmaRadians}, is too large and will clip, as it requested ${
  17639. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  17640. }
  17641. const weights = [];
  17642. let sum = 0;
  17643. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  17644. const x = i / sigmaPixels;
  17645. const weight = Math.exp( - x * x / 2 );
  17646. weights.push( weight );
  17647. if ( i === 0 ) {
  17648. sum += weight;
  17649. } else if ( i < samples ) {
  17650. sum += 2 * weight;
  17651. }
  17652. }
  17653. for ( let i = 0; i < weights.length; i ++ ) {
  17654. weights[ i ] = weights[ i ] / sum;
  17655. }
  17656. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  17657. blurUniforms.envMap.value = targetIn.texture;
  17658. blurUniforms.samples.value = samples;
  17659. blurUniforms.weights.array = weights;
  17660. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  17661. if ( poleAxis ) {
  17662. blurUniforms.poleAxis.value = poleAxis;
  17663. }
  17664. const { _lodMax } = this;
  17665. blurUniforms.dTheta.value = radiansPerPixel;
  17666. blurUniforms.mipInt.value = _lodMax - lodIn;
  17667. const outputSize = this._sizeLods[ lodOut ];
  17668. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  17669. const y = 4 * ( this._cubeSize - outputSize );
  17670. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  17671. renderer.setRenderTarget( targetOut );
  17672. renderer.render( blurMesh, _flatCamera );
  17673. }
  17674. }
  17675. function _createPlanes( lodMax ) {
  17676. const lodPlanes = [];
  17677. const sizeLods = [];
  17678. const sigmas = [];
  17679. const lodMeshes = [];
  17680. let lod = lodMax;
  17681. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  17682. for ( let i = 0; i < totalLods; i ++ ) {
  17683. const sizeLod = Math.pow( 2, lod );
  17684. sizeLods.push( sizeLod );
  17685. let sigma = 1.0 / sizeLod;
  17686. if ( i > lodMax - LOD_MIN ) {
  17687. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  17688. } else if ( i === 0 ) {
  17689. sigma = 0;
  17690. }
  17691. sigmas.push( sigma );
  17692. const texelSize = 1.0 / ( sizeLod - 2 );
  17693. const min = - texelSize;
  17694. const max = 1 + texelSize;
  17695. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  17696. const cubeFaces = 6;
  17697. const vertices = 6;
  17698. const positionSize = 3;
  17699. const uvSize = 2;
  17700. const faceIndexSize = 1;
  17701. const position = new Float32Array( positionSize * vertices * cubeFaces );
  17702. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  17703. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  17704. for ( let face = 0; face < cubeFaces; face ++ ) {
  17705. const x = ( face % 3 ) * 2 / 3 - 1;
  17706. const y = face > 2 ? 0 : -1;
  17707. const coordinates = [
  17708. x, y, 0,
  17709. x + 2 / 3, y, 0,
  17710. x + 2 / 3, y + 1, 0,
  17711. x, y, 0,
  17712. x + 2 / 3, y + 1, 0,
  17713. x, y + 1, 0
  17714. ];
  17715. const faceIdx = _faceLib[ face ];
  17716. position.set( coordinates, positionSize * vertices * faceIdx );
  17717. uv.set( uv1, uvSize * vertices * faceIdx );
  17718. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  17719. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  17720. }
  17721. const planes = new BufferGeometry();
  17722. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  17723. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  17724. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  17725. lodPlanes.push( planes );
  17726. lodMeshes.push( new Mesh( planes, null ) );
  17727. if ( lod > LOD_MIN ) {
  17728. lod --;
  17729. }
  17730. }
  17731. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  17732. }
  17733. function _createRenderTarget( width, height ) {
  17734. const params = {
  17735. magFilter: LinearFilter,
  17736. minFilter: LinearFilter,
  17737. generateMipmaps: false,
  17738. type: HalfFloatType,
  17739. format: RGBAFormat,
  17740. colorSpace: LinearSRGBColorSpace,
  17741. //depthBuffer: false
  17742. };
  17743. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  17744. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  17745. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  17746. cubeUVRenderTarget.texture.isPMREMTexture = true;
  17747. cubeUVRenderTarget.scissorTest = true;
  17748. return cubeUVRenderTarget;
  17749. }
  17750. function _setViewport( target, x, y, width, height ) {
  17751. target.viewport.set( x, y, width, height );
  17752. target.scissor.set( x, y, width, height );
  17753. }
  17754. function _getMaterial( type ) {
  17755. const material = new NodeMaterial();
  17756. material.depthTest = false;
  17757. material.depthWrite = false;
  17758. material.blending = NoBlending;
  17759. material.name = `PMREM_${ type }`;
  17760. return material;
  17761. }
  17762. function _getBlurShader( lodMax, width, height ) {
  17763. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  17764. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  17765. const dTheta = uniform( 0 );
  17766. const n = float( MAX_SAMPLES );
  17767. const latitudinal = uniform( 0 ); // false, bool
  17768. const samples = uniform( 1 ); // int
  17769. const envMap = texture( null );
  17770. const mipInt = uniform( 0 ); // int
  17771. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  17772. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  17773. const CUBEUV_MAX_MIP = float( lodMax );
  17774. const materialUniforms = {
  17775. n,
  17776. latitudinal,
  17777. weights,
  17778. poleAxis,
  17779. outputDirection: _outputDirection,
  17780. dTheta,
  17781. samples,
  17782. envMap,
  17783. mipInt,
  17784. CUBEUV_TEXEL_WIDTH,
  17785. CUBEUV_TEXEL_HEIGHT,
  17786. CUBEUV_MAX_MIP
  17787. };
  17788. const material = _getMaterial( 'blur' );
  17789. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  17790. _uniformsMap.set( material, materialUniforms );
  17791. return material;
  17792. }
  17793. function _getCubemapMaterial( envTexture ) {
  17794. const material = _getMaterial( 'cubemap' );
  17795. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  17796. return material;
  17797. }
  17798. function _getEquirectMaterial( envTexture ) {
  17799. const material = _getMaterial( 'equirect' );
  17800. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  17801. return material;
  17802. }
  17803. const _cache = new WeakMap();
  17804. /**
  17805. * Generates the cubeUV size based on the given image height.
  17806. *
  17807. * @private
  17808. * @param {number} imageHeight - The image height.
  17809. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  17810. */
  17811. function _generateCubeUVSize( imageHeight ) {
  17812. const maxMip = Math.log2( imageHeight ) - 2;
  17813. const texelHeight = 1.0 / imageHeight;
  17814. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  17815. return { texelWidth, texelHeight, maxMip };
  17816. }
  17817. /**
  17818. * Generates a PMREM from the given texture.
  17819. *
  17820. * @private
  17821. * @param {Texture} texture - The texture to create the PMREM for.
  17822. * @param {Renderer} renderer - The renderer.
  17823. * @param {PMREMGenerator} generator - The PMREM generator.
  17824. * @return {?Texture} The PMREM.
  17825. */
  17826. function _getPMREMFromTexture( texture, renderer, generator ) {
  17827. const cache = _getCache( renderer );
  17828. let cacheTexture = cache.get( texture );
  17829. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  17830. if ( pmremVersion !== texture.pmremVersion ) {
  17831. const image = texture.image;
  17832. if ( texture.isCubeTexture ) {
  17833. if ( isCubeMapReady( image ) ) {
  17834. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  17835. } else {
  17836. return null;
  17837. }
  17838. } else {
  17839. if ( isEquirectangularMapReady( image ) ) {
  17840. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  17841. } else {
  17842. return null;
  17843. }
  17844. }
  17845. cacheTexture.pmremVersion = texture.pmremVersion;
  17846. cache.set( texture, cacheTexture );
  17847. }
  17848. return cacheTexture.texture;
  17849. }
  17850. /**
  17851. * Returns a cache that stores generated PMREMs for the respective textures.
  17852. * A cache must be maintained per renderer since PMREMs are render target textures
  17853. * which can't be shared across render contexts.
  17854. *
  17855. * @private
  17856. * @param {Renderer} renderer - The renderer.
  17857. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  17858. */
  17859. function _getCache( renderer ) {
  17860. let rendererCache = _cache.get( renderer );
  17861. if ( rendererCache === undefined ) {
  17862. rendererCache = new WeakMap();
  17863. _cache.set( renderer, rendererCache );
  17864. }
  17865. return rendererCache;
  17866. }
  17867. /**
  17868. * This node represents a PMREM which is a special type of preprocessed
  17869. * environment map intended for PBR materials.
  17870. *
  17871. * ```js
  17872. * const material = new MeshStandardNodeMaterial();
  17873. * material.envNode = pmremTexture( envMap );
  17874. * ```
  17875. *
  17876. * @augments TempNode
  17877. */
  17878. class PMREMNode extends TempNode {
  17879. static get type() {
  17880. return 'PMREMNode';
  17881. }
  17882. /**
  17883. * Constructs a new function overloading node.
  17884. *
  17885. * @param {Texture} value - The input texture.
  17886. * @param {Node<vec2>} [uvNode=null] - The uv node.
  17887. * @param {Node<float>} [levelNode=null] - The level node.
  17888. */
  17889. constructor( value, uvNode = null, levelNode = null ) {
  17890. super( 'vec3' );
  17891. /**
  17892. * Reference to the input texture.
  17893. *
  17894. * @private
  17895. * @type {Texture}
  17896. */
  17897. this._value = value;
  17898. /**
  17899. * Reference to the generated PMREM.
  17900. *
  17901. * @private
  17902. * @type {Texture | null}
  17903. * @default null
  17904. */
  17905. this._pmrem = null;
  17906. /**
  17907. * The uv node.
  17908. *
  17909. * @type {Node<vec2>}
  17910. */
  17911. this.uvNode = uvNode;
  17912. /**
  17913. * The level node.
  17914. *
  17915. * @type {Node<float>}
  17916. */
  17917. this.levelNode = levelNode;
  17918. /**
  17919. * Reference to a PMREM generator.
  17920. *
  17921. * @private
  17922. * @type {?PMREMGenerator}
  17923. * @default null
  17924. */
  17925. this._generator = null;
  17926. const defaultTexture = new Texture();
  17927. defaultTexture.isRenderTargetTexture = true;
  17928. /**
  17929. * The texture node holding the generated PMREM.
  17930. *
  17931. * @private
  17932. * @type {TextureNode}
  17933. */
  17934. this._texture = texture( defaultTexture );
  17935. /**
  17936. * A uniform representing the PMREM's width.
  17937. *
  17938. * @private
  17939. * @type {UniformNode<float>}
  17940. */
  17941. this._width = uniform( 0 );
  17942. /**
  17943. * A uniform representing the PMREM's height.
  17944. *
  17945. * @private
  17946. * @type {UniformNode<float>}
  17947. */
  17948. this._height = uniform( 0 );
  17949. /**
  17950. * A uniform representing the PMREM's max Mip.
  17951. *
  17952. * @private
  17953. * @type {UniformNode<float>}
  17954. */
  17955. this._maxMip = uniform( 0 );
  17956. /**
  17957. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  17958. *
  17959. * @type {string}
  17960. * @default 'render'
  17961. */
  17962. this.updateBeforeType = NodeUpdateType.RENDER;
  17963. }
  17964. set value( value ) {
  17965. this._value = value;
  17966. this._pmrem = null;
  17967. }
  17968. /**
  17969. * The node's texture value.
  17970. *
  17971. * @type {Texture}
  17972. */
  17973. get value() {
  17974. return this._value;
  17975. }
  17976. /**
  17977. * Uses the given PMREM texture to update internal values.
  17978. *
  17979. * @param {Texture} texture - The PMREM texture.
  17980. */
  17981. updateFromTexture( texture ) {
  17982. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  17983. this._texture.value = texture;
  17984. this._width.value = cubeUVSize.texelWidth;
  17985. this._height.value = cubeUVSize.texelHeight;
  17986. this._maxMip.value = cubeUVSize.maxMip;
  17987. }
  17988. updateBefore( frame ) {
  17989. let pmrem = this._pmrem;
  17990. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  17991. const texture = this._value;
  17992. if ( pmremVersion !== texture.pmremVersion ) {
  17993. if ( texture.isPMREMTexture === true ) {
  17994. pmrem = texture;
  17995. } else {
  17996. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  17997. }
  17998. if ( pmrem !== null ) {
  17999. this._pmrem = pmrem;
  18000. this.updateFromTexture( pmrem );
  18001. }
  18002. }
  18003. }
  18004. setup( builder ) {
  18005. if ( this._generator === null ) {
  18006. this._generator = new PMREMGenerator( builder.renderer );
  18007. }
  18008. this.updateBefore( builder );
  18009. //
  18010. let uvNode = this.uvNode;
  18011. if ( uvNode === null && builder.context.getUV ) {
  18012. uvNode = builder.context.getUV( this );
  18013. }
  18014. //
  18015. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  18016. //
  18017. let levelNode = this.levelNode;
  18018. if ( levelNode === null && builder.context.getTextureLevel ) {
  18019. levelNode = builder.context.getTextureLevel( this );
  18020. }
  18021. //
  18022. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  18023. }
  18024. dispose() {
  18025. super.dispose();
  18026. if ( this._generator !== null ) this._generator.dispose();
  18027. }
  18028. }
  18029. /**
  18030. * Returns `true` if the given cube map image has been fully loaded.
  18031. *
  18032. * @private
  18033. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  18034. * @return {boolean} Whether the given cube map is ready or not.
  18035. */
  18036. function isCubeMapReady( image ) {
  18037. if ( image === null || image === undefined ) return false;
  18038. let count = 0;
  18039. const length = 6;
  18040. for ( let i = 0; i < length; i ++ ) {
  18041. if ( image[ i ] !== undefined ) count ++;
  18042. }
  18043. return count === length;
  18044. }
  18045. /**
  18046. * Returns `true` if the given equirectangular image has been fully loaded.
  18047. *
  18048. * @private
  18049. * @param {(Image|Object)} image - The equirectangular image.
  18050. * @return {boolean} Whether the given cube map is ready or not.
  18051. */
  18052. function isEquirectangularMapReady( image ) {
  18053. if ( image === null || image === undefined ) return false;
  18054. return image.height > 0;
  18055. }
  18056. /**
  18057. * TSL function for creating a PMREM node.
  18058. *
  18059. * @tsl
  18060. * @function
  18061. * @param {Texture} value - The input texture.
  18062. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  18063. * @param {?Node<float>} [levelNode=null] - The level node.
  18064. * @returns {PMREMNode}
  18065. */
  18066. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  18067. const _envNodeCache = new WeakMap();
  18068. /**
  18069. * Represents a physical model for Image-based lighting (IBL). The environment
  18070. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  18071. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  18072. *
  18073. * @augments LightingNode
  18074. */
  18075. class EnvironmentNode extends LightingNode {
  18076. static get type() {
  18077. return 'EnvironmentNode';
  18078. }
  18079. /**
  18080. * Constructs a new environment node.
  18081. *
  18082. * @param {Node} [envNode=null] - A node representing the environment.
  18083. */
  18084. constructor( envNode = null ) {
  18085. super();
  18086. /**
  18087. * A node representing the environment.
  18088. *
  18089. * @type {?Node}
  18090. * @default null
  18091. */
  18092. this.envNode = envNode;
  18093. }
  18094. setup( builder ) {
  18095. const { material } = builder;
  18096. let envNode = this.envNode;
  18097. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  18098. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  18099. let cacheEnvNode = _envNodeCache.get( value );
  18100. if ( cacheEnvNode === undefined ) {
  18101. cacheEnvNode = pmremTexture( value );
  18102. _envNodeCache.set( value, cacheEnvNode );
  18103. }
  18104. envNode = cacheEnvNode;
  18105. }
  18106. //
  18107. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  18108. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  18109. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  18110. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  18111. const isolateRadiance = isolate( radiance );
  18112. const isolateIrradiance = isolate( irradiance );
  18113. //
  18114. builder.context.radiance.addAssign( isolateRadiance );
  18115. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  18116. //
  18117. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  18118. if ( clearcoatRadiance ) {
  18119. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  18120. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  18121. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  18122. }
  18123. }
  18124. }
  18125. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  18126. let reflectVec = null;
  18127. return {
  18128. getUV: () => {
  18129. if ( reflectVec === null ) {
  18130. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  18131. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  18132. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  18133. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  18134. }
  18135. return reflectVec;
  18136. },
  18137. getTextureLevel: () => {
  18138. return roughnessNode;
  18139. }
  18140. };
  18141. };
  18142. const createIrradianceContext = ( normalWorldNode ) => {
  18143. return {
  18144. getUV: () => {
  18145. return normalWorldNode;
  18146. },
  18147. getTextureLevel: () => {
  18148. return float( 1.0 );
  18149. }
  18150. };
  18151. };
  18152. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  18153. /**
  18154. * Node material version of {@link MeshStandardMaterial}.
  18155. *
  18156. * @augments NodeMaterial
  18157. */
  18158. class MeshStandardNodeMaterial extends NodeMaterial {
  18159. static get type() {
  18160. return 'MeshStandardNodeMaterial';
  18161. }
  18162. /**
  18163. * Constructs a new mesh standard node material.
  18164. *
  18165. * @param {Object} [parameters] - The configuration parameter.
  18166. */
  18167. constructor( parameters ) {
  18168. super();
  18169. /**
  18170. * This flag can be used for type testing.
  18171. *
  18172. * @type {boolean}
  18173. * @readonly
  18174. * @default true
  18175. */
  18176. this.isMeshStandardNodeMaterial = true;
  18177. /**
  18178. * Set to `true` because standard materials react on lights.
  18179. *
  18180. * @type {boolean}
  18181. * @default true
  18182. */
  18183. this.lights = true;
  18184. /**
  18185. * The emissive color of standard materials is by default inferred from the `emissive`,
  18186. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  18187. * overwrite the default and define the emissive color with a node instead.
  18188. *
  18189. * If you don't want to overwrite the emissive color but modify the existing
  18190. * value instead, use {@link materialEmissive}.
  18191. *
  18192. * @type {?Node<vec3>}
  18193. * @default null
  18194. */
  18195. this.emissiveNode = null;
  18196. /**
  18197. * The metalness of standard materials is by default inferred from the `metalness`,
  18198. * and `metalnessMap` properties. This node property allows to
  18199. * overwrite the default and define the metalness with a node instead.
  18200. *
  18201. * If you don't want to overwrite the metalness but modify the existing
  18202. * value instead, use {@link materialMetalness}.
  18203. *
  18204. * @type {?Node<float>}
  18205. * @default null
  18206. */
  18207. this.metalnessNode = null;
  18208. /**
  18209. * The roughness of standard materials is by default inferred from the `roughness`,
  18210. * and `roughnessMap` properties. This node property allows to
  18211. * overwrite the default and define the roughness with a node instead.
  18212. *
  18213. * If you don't want to overwrite the roughness but modify the existing
  18214. * value instead, use {@link materialRoughness}.
  18215. *
  18216. * @type {?Node<float>}
  18217. * @default null
  18218. */
  18219. this.roughnessNode = null;
  18220. this.setDefaultValues( _defaultValues$6 );
  18221. this.setValues( parameters );
  18222. }
  18223. /**
  18224. * Overwritten since this type of material uses {@link EnvironmentNode}
  18225. * to implement the PBR (PMREM based) environment mapping. Besides, the
  18226. * method honors `Scene.environment`.
  18227. *
  18228. * @param {NodeBuilder} builder - The current node builder.
  18229. * @return {?EnvironmentNode<vec3>} The environment node.
  18230. */
  18231. setupEnvironment( builder ) {
  18232. let envNode = super.setupEnvironment( builder );
  18233. if ( envNode === null && builder.environmentNode ) {
  18234. envNode = builder.environmentNode;
  18235. }
  18236. return envNode ? new EnvironmentNode( envNode ) : null;
  18237. }
  18238. /**
  18239. * Setups the lighting model.
  18240. *
  18241. * @return {PhysicalLightingModel} The lighting model.
  18242. */
  18243. setupLightingModel( /*builder*/ ) {
  18244. return new PhysicalLightingModel();
  18245. }
  18246. /**
  18247. * Setups the specular related node variables.
  18248. */
  18249. setupSpecular() {
  18250. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  18251. specularColor.assign( specularColorNode );
  18252. specularF90.assign( 1.0 );
  18253. }
  18254. /**
  18255. * Setups the standard specific node variables.
  18256. *
  18257. * @param {NodeBuilder} builder - The current node builder.
  18258. */
  18259. setupVariants() {
  18260. // METALNESS
  18261. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  18262. metalness.assign( metalnessNode );
  18263. // ROUGHNESS
  18264. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  18265. roughnessNode = getRoughness( { roughness: roughnessNode } );
  18266. roughness.assign( roughnessNode );
  18267. // SPECULAR COLOR
  18268. this.setupSpecular();
  18269. // DIFFUSE COLOR
  18270. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  18271. }
  18272. copy( source ) {
  18273. this.emissiveNode = source.emissiveNode;
  18274. this.metalnessNode = source.metalnessNode;
  18275. this.roughnessNode = source.roughnessNode;
  18276. return super.copy( source );
  18277. }
  18278. }
  18279. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  18280. /**
  18281. * Node material version of {@link MeshPhysicalMaterial}.
  18282. *
  18283. * @augments MeshStandardNodeMaterial
  18284. */
  18285. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  18286. static get type() {
  18287. return 'MeshPhysicalNodeMaterial';
  18288. }
  18289. /**
  18290. * Constructs a new mesh physical node material.
  18291. *
  18292. * @param {Object} [parameters] - The configuration parameter.
  18293. */
  18294. constructor( parameters ) {
  18295. super();
  18296. /**
  18297. * This flag can be used for type testing.
  18298. *
  18299. * @type {boolean}
  18300. * @readonly
  18301. * @default true
  18302. */
  18303. this.isMeshPhysicalNodeMaterial = true;
  18304. /**
  18305. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  18306. * and `clearcoatMap` properties. This node property allows to overwrite the default
  18307. * and define the clearcoat with a node instead.
  18308. *
  18309. * If you don't want to overwrite the clearcoat but modify the existing
  18310. * value instead, use {@link materialClearcoat}.
  18311. *
  18312. * @type {?Node<float>}
  18313. * @default null
  18314. */
  18315. this.clearcoatNode = null;
  18316. /**
  18317. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  18318. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  18319. * and define the clearcoat roughness with a node instead.
  18320. *
  18321. * If you don't want to overwrite the clearcoat roughness but modify the existing
  18322. * value instead, use {@link materialClearcoatRoughness}.
  18323. *
  18324. * @type {?Node<float>}
  18325. * @default null
  18326. */
  18327. this.clearcoatRoughnessNode = null;
  18328. /**
  18329. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  18330. * property. This node property allows to overwrite the default
  18331. * and define the clearcoat normal with a node instead.
  18332. *
  18333. * If you don't want to overwrite the clearcoat normal but modify the existing
  18334. * value instead, use {@link materialClearcoatNormal}.
  18335. *
  18336. * @type {?Node<vec3>}
  18337. * @default null
  18338. */
  18339. this.clearcoatNormalNode = null;
  18340. /**
  18341. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  18342. * and `sheenColorMap` properties. This node property allows to overwrite the default
  18343. * and define the sheen with a node instead.
  18344. *
  18345. * If you don't want to overwrite the sheen but modify the existing
  18346. * value instead, use {@link materialSheen}.
  18347. *
  18348. * @type {?Node<vec3>}
  18349. * @default null
  18350. */
  18351. this.sheenNode = null;
  18352. /**
  18353. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  18354. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  18355. * and define the sheen roughness with a node instead.
  18356. *
  18357. * If you don't want to overwrite the sheen roughness but modify the existing
  18358. * value instead, use {@link materialSheenRoughness}.
  18359. *
  18360. * @type {?Node<float>}
  18361. * @default null
  18362. */
  18363. this.sheenRoughnessNode = null;
  18364. /**
  18365. * The iridescence of physical materials is by default inferred from the `iridescence`
  18366. * property. This node property allows to overwrite the default
  18367. * and define the iridescence with a node instead.
  18368. *
  18369. * If you don't want to overwrite the iridescence but modify the existing
  18370. * value instead, use {@link materialIridescence}.
  18371. *
  18372. * @type {?Node<float>}
  18373. * @default null
  18374. */
  18375. this.iridescenceNode = null;
  18376. /**
  18377. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  18378. * property. This node property allows to overwrite the default
  18379. * and define the iridescence IOR with a node instead.
  18380. *
  18381. * If you don't want to overwrite the iridescence IOR but modify the existing
  18382. * value instead, use {@link materialIridescenceIOR}.
  18383. *
  18384. * @type {?Node<float>}
  18385. * @default null
  18386. */
  18387. this.iridescenceIORNode = null;
  18388. /**
  18389. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  18390. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  18391. * and define the iridescence thickness with a node instead.
  18392. *
  18393. * If you don't want to overwrite the iridescence thickness but modify the existing
  18394. * value instead, use {@link materialIridescenceThickness}.
  18395. *
  18396. * @type {?Node<float>}
  18397. * @default null
  18398. */
  18399. this.iridescenceThicknessNode = null;
  18400. /**
  18401. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  18402. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  18403. * and define the specular intensity with a node instead.
  18404. *
  18405. * If you don't want to overwrite the specular intensity but modify the existing
  18406. * value instead, use {@link materialSpecularIntensity}.
  18407. *
  18408. * @type {?Node<float>}
  18409. * @default null
  18410. */
  18411. this.specularIntensityNode = null;
  18412. /**
  18413. * The specular color of physical materials is by default inferred from the `specularColor`
  18414. * and `specularColorMap` properties. This node property allows to overwrite the default
  18415. * and define the specular color with a node instead.
  18416. *
  18417. * If you don't want to overwrite the specular color but modify the existing
  18418. * value instead, use {@link materialSpecularColor}.
  18419. *
  18420. * @type {?Node<vec3>}
  18421. * @default null
  18422. */
  18423. this.specularColorNode = null;
  18424. /**
  18425. * The ior of physical materials is by default inferred from the `ior`
  18426. * property. This node property allows to overwrite the default
  18427. * and define the ior with a node instead.
  18428. *
  18429. * If you don't want to overwrite the ior but modify the existing
  18430. * value instead, use {@link materialIOR}.
  18431. *
  18432. * @type {?Node<float>}
  18433. * @default null
  18434. */
  18435. this.iorNode = null;
  18436. /**
  18437. * The transmission of physical materials is by default inferred from the `transmission` and
  18438. * `transmissionMap` properties. This node property allows to overwrite the default
  18439. * and define the transmission with a node instead.
  18440. *
  18441. * If you don't want to overwrite the transmission but modify the existing
  18442. * value instead, use {@link materialTransmission}.
  18443. *
  18444. * @type {?Node<float>}
  18445. * @default null
  18446. */
  18447. this.transmissionNode = null;
  18448. /**
  18449. * The thickness of physical materials is by default inferred from the `thickness` and
  18450. * `thicknessMap` properties. This node property allows to overwrite the default
  18451. * and define the thickness with a node instead.
  18452. *
  18453. * If you don't want to overwrite the thickness but modify the existing
  18454. * value instead, use {@link materialThickness}.
  18455. *
  18456. * @type {?Node<float>}
  18457. * @default null
  18458. */
  18459. this.thicknessNode = null;
  18460. /**
  18461. * The attenuation distance of physical materials is by default inferred from the
  18462. * `attenuationDistance` property. This node property allows to overwrite the default
  18463. * and define the attenuation distance with a node instead.
  18464. *
  18465. * If you don't want to overwrite the attenuation distance but modify the existing
  18466. * value instead, use {@link materialAttenuationDistance}.
  18467. *
  18468. * @type {?Node<float>}
  18469. * @default null
  18470. */
  18471. this.attenuationDistanceNode = null;
  18472. /**
  18473. * The attenuation color of physical materials is by default inferred from the
  18474. * `attenuationColor` property. This node property allows to overwrite the default
  18475. * and define the attenuation color with a node instead.
  18476. *
  18477. * If you don't want to overwrite the attenuation color but modify the existing
  18478. * value instead, use {@link materialAttenuationColor}.
  18479. *
  18480. * @type {?Node<vec3>}
  18481. * @default null
  18482. */
  18483. this.attenuationColorNode = null;
  18484. /**
  18485. * The dispersion of physical materials is by default inferred from the
  18486. * `dispersion` property. This node property allows to overwrite the default
  18487. * and define the dispersion with a node instead.
  18488. *
  18489. * If you don't want to overwrite the dispersion but modify the existing
  18490. * value instead, use {@link materialDispersion}.
  18491. *
  18492. * @type {?Node<float>}
  18493. * @default null
  18494. */
  18495. this.dispersionNode = null;
  18496. /**
  18497. * The anisotropy of physical materials is by default inferred from the
  18498. * `anisotropy` property. This node property allows to overwrite the default
  18499. * and define the anisotropy with a node instead.
  18500. *
  18501. * If you don't want to overwrite the anisotropy but modify the existing
  18502. * value instead, use {@link materialAnisotropy}.
  18503. *
  18504. * @type {?Node<float>}
  18505. * @default null
  18506. */
  18507. this.anisotropyNode = null;
  18508. this.setDefaultValues( _defaultValues$5 );
  18509. this.setValues( parameters );
  18510. }
  18511. /**
  18512. * Whether the lighting model should use clearcoat or not.
  18513. *
  18514. * @type {boolean}
  18515. * @default true
  18516. */
  18517. get useClearcoat() {
  18518. return this.clearcoat > 0 || this.clearcoatNode !== null;
  18519. }
  18520. /**
  18521. * Whether the lighting model should use iridescence or not.
  18522. *
  18523. * @type {boolean}
  18524. * @default true
  18525. */
  18526. get useIridescence() {
  18527. return this.iridescence > 0 || this.iridescenceNode !== null;
  18528. }
  18529. /**
  18530. * Whether the lighting model should use sheen or not.
  18531. *
  18532. * @type {boolean}
  18533. * @default true
  18534. */
  18535. get useSheen() {
  18536. return this.sheen > 0 || this.sheenNode !== null;
  18537. }
  18538. /**
  18539. * Whether the lighting model should use anisotropy or not.
  18540. *
  18541. * @type {boolean}
  18542. * @default true
  18543. */
  18544. get useAnisotropy() {
  18545. return this.anisotropy > 0 || this.anisotropyNode !== null;
  18546. }
  18547. /**
  18548. * Whether the lighting model should use transmission or not.
  18549. *
  18550. * @type {boolean}
  18551. * @default true
  18552. */
  18553. get useTransmission() {
  18554. return this.transmission > 0 || this.transmissionNode !== null;
  18555. }
  18556. /**
  18557. * Whether the lighting model should use dispersion or not.
  18558. *
  18559. * @type {boolean}
  18560. * @default true
  18561. */
  18562. get useDispersion() {
  18563. return this.dispersion > 0 || this.dispersionNode !== null;
  18564. }
  18565. /**
  18566. * Setups the specular related node variables.
  18567. */
  18568. setupSpecular() {
  18569. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  18570. ior.assign( iorNode );
  18571. specularColor.assign( mix( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ), diffuseColor.rgb, metalness ) );
  18572. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  18573. }
  18574. /**
  18575. * Setups the lighting model.
  18576. *
  18577. * @return {PhysicalLightingModel} The lighting model.
  18578. */
  18579. setupLightingModel( /*builder*/ ) {
  18580. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  18581. }
  18582. /**
  18583. * Setups the physical specific node variables.
  18584. *
  18585. * @param {NodeBuilder} builder - The current node builder.
  18586. */
  18587. setupVariants( builder ) {
  18588. super.setupVariants( builder );
  18589. // CLEARCOAT
  18590. if ( this.useClearcoat ) {
  18591. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  18592. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  18593. clearcoat.assign( clearcoatNode );
  18594. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  18595. }
  18596. // SHEEN
  18597. if ( this.useSheen ) {
  18598. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  18599. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  18600. sheen.assign( sheenNode );
  18601. sheenRoughness.assign( sheenRoughnessNode );
  18602. }
  18603. // IRIDESCENCE
  18604. if ( this.useIridescence ) {
  18605. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  18606. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  18607. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  18608. iridescence.assign( iridescenceNode );
  18609. iridescenceIOR.assign( iridescenceIORNode );
  18610. iridescenceThickness.assign( iridescenceThicknessNode );
  18611. }
  18612. // ANISOTROPY
  18613. if ( this.useAnisotropy ) {
  18614. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  18615. anisotropy.assign( anisotropyV.length() );
  18616. If( anisotropy.equal( 0.0 ), () => {
  18617. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  18618. } ).Else( () => {
  18619. anisotropyV.divAssign( vec2( anisotropy ) );
  18620. anisotropy.assign( anisotropy.saturate() );
  18621. } );
  18622. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  18623. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  18624. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  18625. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  18626. }
  18627. // TRANSMISSION
  18628. if ( this.useTransmission ) {
  18629. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  18630. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  18631. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  18632. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  18633. transmission.assign( transmissionNode );
  18634. thickness.assign( thicknessNode );
  18635. attenuationDistance.assign( attenuationDistanceNode );
  18636. attenuationColor.assign( attenuationColorNode );
  18637. if ( this.useDispersion ) {
  18638. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  18639. dispersion.assign( dispersionNode );
  18640. }
  18641. }
  18642. }
  18643. /**
  18644. * Setups the clearcoat normal node.
  18645. *
  18646. * @return {Node<vec3>} The clearcoat normal.
  18647. */
  18648. setupClearcoatNormal() {
  18649. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  18650. }
  18651. setup( builder ) {
  18652. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  18653. super.setup( builder );
  18654. }
  18655. copy( source ) {
  18656. this.clearcoatNode = source.clearcoatNode;
  18657. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  18658. this.clearcoatNormalNode = source.clearcoatNormalNode;
  18659. this.sheenNode = source.sheenNode;
  18660. this.sheenRoughnessNode = source.sheenRoughnessNode;
  18661. this.iridescenceNode = source.iridescenceNode;
  18662. this.iridescenceIORNode = source.iridescenceIORNode;
  18663. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  18664. this.specularIntensityNode = source.specularIntensityNode;
  18665. this.specularColorNode = source.specularColorNode;
  18666. this.transmissionNode = source.transmissionNode;
  18667. this.thicknessNode = source.thicknessNode;
  18668. this.attenuationDistanceNode = source.attenuationDistanceNode;
  18669. this.attenuationColorNode = source.attenuationColorNode;
  18670. this.dispersionNode = source.dispersionNode;
  18671. this.anisotropyNode = source.anisotropyNode;
  18672. return super.copy( source );
  18673. }
  18674. }
  18675. /**
  18676. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  18677. *
  18678. * @augments PhysicalLightingModel
  18679. */
  18680. class SSSLightingModel extends PhysicalLightingModel {
  18681. /**
  18682. * Constructs a new physical lighting model.
  18683. *
  18684. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  18685. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  18686. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  18687. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  18688. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  18689. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  18690. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  18691. */
  18692. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  18693. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  18694. /**
  18695. * Whether the lighting model should use SSS or not.
  18696. *
  18697. * @type {boolean}
  18698. * @default false
  18699. */
  18700. this.useSSS = sss;
  18701. }
  18702. /**
  18703. * Extends the default implementation with a SSS term.
  18704. *
  18705. * Reference: [Approximating Translucency for a Fast, Cheap and Convincing Subsurface Scattering Look]{@link https://colinbarrebrisebois.com/2011/03/07/gdc-2011-approximating-translucency-for-a-fast-cheap-and-convincing-subsurface-scattering-look/}
  18706. *
  18707. * @param {Object} input - The input data.
  18708. * @param {NodeBuilder} builder - The current node builder.
  18709. */
  18710. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18711. if ( this.useSSS === true ) {
  18712. const material = builder.material;
  18713. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  18714. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  18715. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  18716. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  18717. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  18718. }
  18719. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  18720. }
  18721. }
  18722. /**
  18723. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  18724. * that implements a Subsurface scattering (SSS) term.
  18725. *
  18726. * @augments MeshPhysicalNodeMaterial
  18727. */
  18728. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  18729. static get type() {
  18730. return 'MeshSSSNodeMaterial';
  18731. }
  18732. /**
  18733. * Constructs a new mesh SSS node material.
  18734. *
  18735. * @param {Object} [parameters] - The configuration parameter.
  18736. */
  18737. constructor( parameters ) {
  18738. super( parameters );
  18739. /**
  18740. * Represents the thickness color.
  18741. *
  18742. * @type {?Node<vec3>}
  18743. * @default null
  18744. */
  18745. this.thicknessColorNode = null;
  18746. /**
  18747. * Represents the distortion factor.
  18748. *
  18749. * @type {?Node<float>}
  18750. */
  18751. this.thicknessDistortionNode = float( 0.1 );
  18752. /**
  18753. * Represents the thickness ambient factor.
  18754. *
  18755. * @type {?Node<float>}
  18756. */
  18757. this.thicknessAmbientNode = float( 0.0 );
  18758. /**
  18759. * Represents the thickness attenuation.
  18760. *
  18761. * @type {?Node<float>}
  18762. */
  18763. this.thicknessAttenuationNode = float( .1 );
  18764. /**
  18765. * Represents the thickness power.
  18766. *
  18767. * @type {?Node<float>}
  18768. */
  18769. this.thicknessPowerNode = float( 2.0 );
  18770. /**
  18771. * Represents the thickness scale.
  18772. *
  18773. * @type {?Node<float>}
  18774. */
  18775. this.thicknessScaleNode = float( 10.0 );
  18776. }
  18777. /**
  18778. * Whether the lighting model should use SSS or not.
  18779. *
  18780. * @type {boolean}
  18781. * @default true
  18782. */
  18783. get useSSS() {
  18784. return this.thicknessColorNode !== null;
  18785. }
  18786. /**
  18787. * Setups the lighting model.
  18788. *
  18789. * @return {SSSLightingModel} The lighting model.
  18790. */
  18791. setupLightingModel( /*builder*/ ) {
  18792. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  18793. }
  18794. copy( source ) {
  18795. this.thicknessColorNode = source.thicknessColorNode;
  18796. this.thicknessDistortionNode = source.thicknessDistortionNode;
  18797. this.thicknessAmbientNode = source.thicknessAmbientNode;
  18798. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  18799. this.thicknessPowerNode = source.thicknessPowerNode;
  18800. this.thicknessScaleNode = source.thicknessScaleNode;
  18801. return super.copy( source );
  18802. }
  18803. }
  18804. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  18805. // dotNL will be from -1.0 to 1.0
  18806. const dotNL = normal.dot( lightDirection );
  18807. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  18808. if ( builder.material.gradientMap ) {
  18809. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  18810. return vec3( gradientMap.r );
  18811. } else {
  18812. const fw = coord.fwidth().mul( 0.5 );
  18813. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  18814. }
  18815. } );
  18816. /**
  18817. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  18818. *
  18819. * @augments LightingModel
  18820. */
  18821. class ToonLightingModel extends LightingModel {
  18822. /**
  18823. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  18824. * reduced to a small number of discrete shades to create a comic-like, flat look.
  18825. *
  18826. * @param {Object} lightData - The light data.
  18827. * @param {NodeBuilder} builder - The current node builder.
  18828. */
  18829. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18830. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  18831. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  18832. }
  18833. /**
  18834. * Implements the indirect lighting.
  18835. *
  18836. * @param {NodeBuilder} builder - The current node builder.
  18837. */
  18838. indirect( builder ) {
  18839. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  18840. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  18841. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  18842. }
  18843. }
  18844. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  18845. /**
  18846. * Node material version of {@link MeshToonMaterial}.
  18847. *
  18848. * @augments NodeMaterial
  18849. */
  18850. class MeshToonNodeMaterial extends NodeMaterial {
  18851. static get type() {
  18852. return 'MeshToonNodeMaterial';
  18853. }
  18854. /**
  18855. * Constructs a new mesh toon node material.
  18856. *
  18857. * @param {Object} [parameters] - The configuration parameter.
  18858. */
  18859. constructor( parameters ) {
  18860. super();
  18861. /**
  18862. * This flag can be used for type testing.
  18863. *
  18864. * @type {boolean}
  18865. * @readonly
  18866. * @default true
  18867. */
  18868. this.isMeshToonNodeMaterial = true;
  18869. /**
  18870. * Set to `true` because toon materials react on lights.
  18871. *
  18872. * @type {boolean}
  18873. * @default true
  18874. */
  18875. this.lights = true;
  18876. this.setDefaultValues( _defaultValues$4 );
  18877. this.setValues( parameters );
  18878. }
  18879. /**
  18880. * Setups the lighting model.
  18881. *
  18882. * @return {ToonLightingModel} The lighting model.
  18883. */
  18884. setupLightingModel( /*builder*/ ) {
  18885. return new ToonLightingModel();
  18886. }
  18887. }
  18888. /**
  18889. * TSL function for creating a matcap uv node.
  18890. *
  18891. * Can be used to compute texture coordinates for projecting a
  18892. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  18893. *
  18894. * @tsl
  18895. * @function
  18896. * @returns {Node<vec2>} The matcap UV coordinates.
  18897. */
  18898. const matcapUV = /*@__PURE__*/ Fn( () => {
  18899. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  18900. const y = positionViewDirection.cross( x );
  18901. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  18902. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  18903. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  18904. /**
  18905. * Node material version of {@link MeshMatcapMaterial}.
  18906. *
  18907. * @augments NodeMaterial
  18908. */
  18909. class MeshMatcapNodeMaterial extends NodeMaterial {
  18910. static get type() {
  18911. return 'MeshMatcapNodeMaterial';
  18912. }
  18913. /**
  18914. * Constructs a new mesh normal node material.
  18915. *
  18916. * @param {Object} [parameters] - The configuration parameter.
  18917. */
  18918. constructor( parameters ) {
  18919. super();
  18920. /**
  18921. * This flag can be used for type testing.
  18922. *
  18923. * @type {boolean}
  18924. * @readonly
  18925. * @default true
  18926. */
  18927. this.isMeshMatcapNodeMaterial = true;
  18928. this.setDefaultValues( _defaultValues$3 );
  18929. this.setValues( parameters );
  18930. }
  18931. /**
  18932. * Setups the matcap specific node variables.
  18933. *
  18934. * @param {NodeBuilder} builder - The current node builder.
  18935. */
  18936. setupVariants( builder ) {
  18937. const uv = matcapUV;
  18938. let matcapColor;
  18939. if ( builder.material.matcap ) {
  18940. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  18941. } else {
  18942. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  18943. }
  18944. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  18945. }
  18946. }
  18947. /**
  18948. * Applies a rotation to the given position node.
  18949. *
  18950. * @augments TempNode
  18951. */
  18952. class RotateNode extends TempNode {
  18953. static get type() {
  18954. return 'RotateNode';
  18955. }
  18956. /**
  18957. * Constructs a new rotate node.
  18958. *
  18959. * @param {Node} positionNode - The position node.
  18960. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18961. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18962. */
  18963. constructor( positionNode, rotationNode ) {
  18964. super();
  18965. /**
  18966. * The position node.
  18967. *
  18968. * @type {Node}
  18969. */
  18970. this.positionNode = positionNode;
  18971. /**
  18972. * Represents the rotation that is applied to the position node.
  18973. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18974. *
  18975. * @type {Node}
  18976. */
  18977. this.rotationNode = rotationNode;
  18978. }
  18979. /**
  18980. * The type of the {@link RotateNode#positionNode} defines the node's type.
  18981. *
  18982. * @param {NodeBuilder} builder - The current node builder.
  18983. * @return {string} The node's type.
  18984. */
  18985. getNodeType( builder ) {
  18986. return this.positionNode.getNodeType( builder );
  18987. }
  18988. setup( builder ) {
  18989. const { rotationNode, positionNode } = this;
  18990. const nodeType = this.getNodeType( builder );
  18991. if ( nodeType === 'vec2' ) {
  18992. const cosAngle = rotationNode.cos();
  18993. const sinAngle = rotationNode.sin();
  18994. const rotationMatrix = mat2(
  18995. cosAngle, sinAngle,
  18996. sinAngle.negate(), cosAngle
  18997. );
  18998. return rotationMatrix.mul( positionNode );
  18999. } else {
  19000. const rotation = rotationNode;
  19001. 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 ) );
  19002. 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 ) );
  19003. 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 ) );
  19004. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  19005. }
  19006. }
  19007. }
  19008. /**
  19009. * TSL function for creating a rotate node.
  19010. *
  19011. * @tsl
  19012. * @function
  19013. * @param {Node} positionNode - The position node.
  19014. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19015. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19016. * @returns {RotateNode}
  19017. */
  19018. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  19019. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  19020. /**
  19021. * Node material version of {@link SpriteMaterial}.
  19022. *
  19023. * @augments NodeMaterial
  19024. */
  19025. class SpriteNodeMaterial extends NodeMaterial {
  19026. static get type() {
  19027. return 'SpriteNodeMaterial';
  19028. }
  19029. /**
  19030. * Constructs a new sprite node material.
  19031. *
  19032. * @param {Object} [parameters] - The configuration parameter.
  19033. */
  19034. constructor( parameters ) {
  19035. super();
  19036. /**
  19037. * This flag can be used for type testing.
  19038. *
  19039. * @type {boolean}
  19040. * @readonly
  19041. * @default true
  19042. */
  19043. this.isSpriteNodeMaterial = true;
  19044. this._useSizeAttenuation = true;
  19045. /**
  19046. * This property makes it possible to define the position of the sprite with a
  19047. * node. That can be useful when the material is used with instanced rendering
  19048. * and node data are defined with an instanced attribute node:
  19049. * ```js
  19050. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  19051. * material.positionNode = instancedBufferAttribute( positionAttribute );
  19052. * ```
  19053. * Another possibility is to compute the instanced data with a compute shader:
  19054. * ```js
  19055. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  19056. * particleMaterial.positionNode = positionBuffer.toAttribute();
  19057. * ```
  19058. *
  19059. * @type {?Node<vec2>}
  19060. * @default null
  19061. */
  19062. this.positionNode = null;
  19063. /**
  19064. * The rotation of sprite materials is by default inferred from the `rotation`,
  19065. * property. This node property allows to overwrite the default and define
  19066. * the rotation with a node instead.
  19067. *
  19068. * If you don't want to overwrite the rotation but modify the existing
  19069. * value instead, use {@link materialRotation}.
  19070. *
  19071. * @type {?Node<float>}
  19072. * @default null
  19073. */
  19074. this.rotationNode = null;
  19075. /**
  19076. * This node property provides an additional way to scale sprites next to
  19077. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  19078. * is multiplied with the scale value of this node in the vertex shader.
  19079. *
  19080. * @type {?Node<vec2>}
  19081. * @default null
  19082. */
  19083. this.scaleNode = null;
  19084. /**
  19085. * In Sprites, the transparent property is enabled by default.
  19086. *
  19087. * @type {boolean}
  19088. * @default true
  19089. */
  19090. this.transparent = true;
  19091. this.setDefaultValues( _defaultValues$2 );
  19092. this.setValues( parameters );
  19093. }
  19094. /**
  19095. * Setups the position node in view space. This method implements
  19096. * the sprite specific vertex shader.
  19097. *
  19098. * @param {NodeBuilder} builder - The current node builder.
  19099. * @return {Node<vec3>} The position in view space.
  19100. */
  19101. setupPositionView( builder ) {
  19102. const { object, camera } = builder;
  19103. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  19104. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  19105. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  19106. if ( scaleNode !== null ) {
  19107. scale = scale.mul( vec2( scaleNode ) );
  19108. }
  19109. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  19110. scale = scale.mul( mvPosition.z.negate() );
  19111. }
  19112. let alignedPosition = positionGeometry.xy;
  19113. if ( object.center && object.center.isVector2 === true ) {
  19114. const center = reference$1( 'center', 'vec2', object );
  19115. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  19116. }
  19117. alignedPosition = alignedPosition.mul( scale );
  19118. const rotation = float( rotationNode || materialRotation );
  19119. const rotatedPosition = rotate( alignedPosition, rotation );
  19120. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  19121. }
  19122. copy( source ) {
  19123. this.positionNode = source.positionNode;
  19124. this.rotationNode = source.rotationNode;
  19125. this.scaleNode = source.scaleNode;
  19126. return super.copy( source );
  19127. }
  19128. /**
  19129. * Whether to use size attenuation or not.
  19130. *
  19131. * @type {boolean}
  19132. * @default true
  19133. */
  19134. get sizeAttenuation() {
  19135. return this._useSizeAttenuation;
  19136. }
  19137. set sizeAttenuation( value ) {
  19138. if ( this._useSizeAttenuation !== value ) {
  19139. this._useSizeAttenuation = value;
  19140. this.needsUpdate = true;
  19141. }
  19142. }
  19143. }
  19144. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  19145. const _size$4 = /*@__PURE__*/ new Vector2();
  19146. /**
  19147. * Node material version of {@link PointsMaterial}.
  19148. *
  19149. * This material can be used in two ways:
  19150. *
  19151. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  19152. * with a pixel size of `1`, it's not possible to define a size.
  19153. *
  19154. * ```js
  19155. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  19156. * ```
  19157. *
  19158. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  19159. * see {@link PointsNodeMaterial#sizeNode}.
  19160. *
  19161. * ```js
  19162. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  19163. * ```
  19164. *
  19165. * @augments SpriteNodeMaterial
  19166. */
  19167. class PointsNodeMaterial extends SpriteNodeMaterial {
  19168. static get type() {
  19169. return 'PointsNodeMaterial';
  19170. }
  19171. /**
  19172. * Constructs a new points node material.
  19173. *
  19174. * @param {Object} [parameters] - The configuration parameter.
  19175. */
  19176. constructor( parameters ) {
  19177. super();
  19178. /**
  19179. * This node property provides an additional way to set the point size.
  19180. *
  19181. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  19182. * this node has no effect when the material is used with {@link Points} and a WebGPU
  19183. * backend. If an application wants to render points with a size larger than 1 pixel,
  19184. * the material should be used with {@link Sprite} and instancing.
  19185. *
  19186. * @type {?Node<vec2>}
  19187. * @default null
  19188. */
  19189. this.sizeNode = null;
  19190. /**
  19191. * This flag can be used for type testing.
  19192. *
  19193. * @type {boolean}
  19194. * @readonly
  19195. * @default true
  19196. */
  19197. this.isPointsNodeMaterial = true;
  19198. this.setDefaultValues( _defaultValues$1 );
  19199. this.setValues( parameters );
  19200. }
  19201. setupPositionView() {
  19202. const { positionNode } = this;
  19203. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  19204. }
  19205. setupVertexSprite( builder ) {
  19206. const { material, camera } = builder;
  19207. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  19208. let mvp = super.setupVertex( builder );
  19209. // skip further processing if the material is not a node material
  19210. if ( material.isNodeMaterial !== true ) {
  19211. return mvp;
  19212. }
  19213. // point size
  19214. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  19215. pointSize = pointSize.mul( screenDPR );
  19216. // size attenuation
  19217. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  19218. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  19219. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  19220. }
  19221. // scale
  19222. if ( scaleNode && scaleNode.isNode ) {
  19223. pointSize = pointSize.mul( vec2( scaleNode ) );
  19224. }
  19225. // compute offset
  19226. let offset = positionGeometry.xy;
  19227. // apply rotation
  19228. if ( rotationNode && rotationNode.isNode ) {
  19229. const rotation = float( rotationNode );
  19230. offset = rotate( offset, rotation );
  19231. }
  19232. // account for point size
  19233. offset = offset.mul( pointSize );
  19234. // scale by viewport size
  19235. offset = offset.div( viewportSize.div( 2 ) );
  19236. // compensate for the perspective divide
  19237. offset = offset.mul( mvp.w );
  19238. // add offset
  19239. mvp = mvp.add( vec4( offset, 0, 0 ) );
  19240. return mvp;
  19241. }
  19242. setupVertex( builder ) {
  19243. if ( builder.object.isPoints ) {
  19244. return super.setupVertex( builder );
  19245. } else {
  19246. return this.setupVertexSprite( builder );
  19247. }
  19248. }
  19249. /**
  19250. * Whether alpha to coverage should be used or not.
  19251. *
  19252. * @type {boolean}
  19253. * @default true
  19254. */
  19255. get alphaToCoverage() {
  19256. return this._useAlphaToCoverage;
  19257. }
  19258. set alphaToCoverage( value ) {
  19259. if ( this._useAlphaToCoverage !== value ) {
  19260. this._useAlphaToCoverage = value;
  19261. this.needsUpdate = true;
  19262. }
  19263. }
  19264. }
  19265. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  19266. const size = renderer.getSize( _size$4 ); // logical units
  19267. this.value = 0.5 * size.y;
  19268. } );
  19269. /**
  19270. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  19271. *
  19272. * @augments LightingModel
  19273. */
  19274. class ShadowMaskModel extends LightingModel {
  19275. /**
  19276. * Constructs a new shadow mask model.
  19277. */
  19278. constructor() {
  19279. super();
  19280. /**
  19281. * The shadow mask node.
  19282. *
  19283. * @type {Node}
  19284. */
  19285. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  19286. }
  19287. /**
  19288. * Only used to save the shadow mask.
  19289. *
  19290. * @param {Object} input - The input data.
  19291. */
  19292. direct( { lightNode } ) {
  19293. if ( lightNode.shadowNode !== null ) {
  19294. this.shadowNode.mulAssign( lightNode.shadowNode );
  19295. }
  19296. }
  19297. /**
  19298. * Uses the shadow mask to produce the final color.
  19299. *
  19300. * @param {NodeBuilder} builder - The current node builder.
  19301. */
  19302. finish( { context } ) {
  19303. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  19304. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  19305. }
  19306. }
  19307. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  19308. /**
  19309. * Node material version of {@link ShadowMaterial}.
  19310. *
  19311. * @augments NodeMaterial
  19312. */
  19313. class ShadowNodeMaterial extends NodeMaterial {
  19314. static get type() {
  19315. return 'ShadowNodeMaterial';
  19316. }
  19317. /**
  19318. * Constructs a new shadow node material.
  19319. *
  19320. * @param {Object} [parameters] - The configuration parameter.
  19321. */
  19322. constructor( parameters ) {
  19323. super();
  19324. /**
  19325. * This flag can be used for type testing.
  19326. *
  19327. * @type {boolean}
  19328. * @readonly
  19329. * @default true
  19330. */
  19331. this.isShadowNodeMaterial = true;
  19332. /**
  19333. * Set to `true` because so it's possible to implement
  19334. * the shadow mask effect.
  19335. *
  19336. * @type {boolean}
  19337. * @default true
  19338. */
  19339. this.lights = true;
  19340. /**
  19341. * Overwritten since shadow materials are transparent
  19342. * by default.
  19343. *
  19344. * @type {boolean}
  19345. * @default true
  19346. */
  19347. this.transparent = true;
  19348. this.setDefaultValues( _defaultValues );
  19349. this.setValues( parameters );
  19350. }
  19351. /**
  19352. * Setups the lighting model.
  19353. *
  19354. * @return {ShadowMaskModel} The lighting model.
  19355. */
  19356. setupLightingModel( /*builder*/ ) {
  19357. return new ShadowMaskModel();
  19358. }
  19359. }
  19360. const scatteringDensity = property( 'vec3' );
  19361. const linearDepthRay = property( 'vec3' );
  19362. const outgoingRayLight = property( 'vec3' );
  19363. /**
  19364. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  19365. * This model calculates the scattering and transmittance of light through a volumetric medium.
  19366. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  19367. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  19368. *
  19369. * @augments LightingModel
  19370. */
  19371. class VolumetricLightingModel extends LightingModel {
  19372. constructor() {
  19373. super();
  19374. }
  19375. start( builder ) {
  19376. const { material, context } = builder;
  19377. const startPos = property( 'vec3' );
  19378. const endPos = property( 'vec3' );
  19379. // This approach dynamically changes the direction of the ray,
  19380. // 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.
  19381. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  19382. startPos.assign( cameraPosition );
  19383. endPos.assign( positionWorld );
  19384. } ).Else( () => {
  19385. startPos.assign( positionWorld );
  19386. endPos.assign( cameraPosition );
  19387. } );
  19388. //
  19389. const viewVector = endPos.sub( startPos );
  19390. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  19391. const stepSize = viewVector.length().div( steps ).toVar();
  19392. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  19393. const distTravelled = float( 0.0 ).toVar();
  19394. const transmittance = vec3( 1 ).toVar();
  19395. if ( material.offsetNode ) {
  19396. // reduce banding
  19397. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  19398. }
  19399. Loop( steps, () => {
  19400. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  19401. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  19402. if ( material.depthNode !== null ) {
  19403. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  19404. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  19405. }
  19406. context.positionWorld = positionRay;
  19407. context.shadowPositionWorld = positionRay;
  19408. context.positionView = positionViewRay;
  19409. scatteringDensity.assign( 0 );
  19410. let scatteringNode;
  19411. if ( material.scatteringNode ) {
  19412. scatteringNode = material.scatteringNode( {
  19413. positionRay
  19414. } );
  19415. }
  19416. super.start( builder );
  19417. if ( scatteringNode ) {
  19418. scatteringDensity.mulAssign( scatteringNode );
  19419. }
  19420. // beer's law
  19421. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  19422. transmittance.mulAssign( falloff );
  19423. // move along the ray
  19424. distTravelled.addAssign( stepSize );
  19425. } );
  19426. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  19427. }
  19428. scatteringLight( lightColor, builder ) {
  19429. const sceneDepthNode = builder.context.sceneDepthNode;
  19430. if ( sceneDepthNode ) {
  19431. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  19432. scatteringDensity.addAssign( lightColor );
  19433. } );
  19434. } else {
  19435. scatteringDensity.addAssign( lightColor );
  19436. }
  19437. }
  19438. direct( { lightNode, lightColor }, builder ) {
  19439. // Ignore lights with infinite distance
  19440. if ( lightNode.light.distance === undefined ) return;
  19441. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  19442. const directLight = lightColor.xyz.toVar();
  19443. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  19444. this.scatteringLight( directLight, builder );
  19445. }
  19446. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  19447. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  19448. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  19449. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  19450. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  19451. const P = builder.context.positionView;
  19452. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  19453. this.scatteringLight( directLight, builder );
  19454. }
  19455. finish( builder ) {
  19456. builder.context.outgoingLight.assign( outgoingRayLight );
  19457. }
  19458. }
  19459. /**
  19460. * Volume node material.
  19461. *
  19462. * @augments NodeMaterial
  19463. */
  19464. class VolumeNodeMaterial extends NodeMaterial {
  19465. static get type() {
  19466. return 'VolumeNodeMaterial';
  19467. }
  19468. /**
  19469. * Constructs a new volume node material.
  19470. *
  19471. * @param {Object} [parameters] - The configuration parameter.
  19472. */
  19473. constructor( parameters ) {
  19474. super();
  19475. /**
  19476. * This flag can be used for type testing.
  19477. *
  19478. * @type {boolean}
  19479. * @readonly
  19480. * @default true
  19481. */
  19482. this.isVolumeNodeMaterial = true;
  19483. /**
  19484. * Number of steps used for raymarching.
  19485. *
  19486. * @type {number}
  19487. * @default 25
  19488. */
  19489. this.steps = 25;
  19490. /**
  19491. * Offsets the distance a ray has been traveled through a volume.
  19492. * Can be used to implement dithering to reduce banding.
  19493. *
  19494. * @type {Node<float>}
  19495. * @default null
  19496. */
  19497. this.offsetNode = null;
  19498. /**
  19499. * Node used for scattering calculations.
  19500. *
  19501. * @type {Function|FunctionNode<vec4>}
  19502. * @default null
  19503. */
  19504. this.scatteringNode = null;
  19505. this.lights = true;
  19506. this.transparent = true;
  19507. this.side = BackSide;
  19508. this.depthTest = false;
  19509. this.depthWrite = false;
  19510. this.setValues( parameters );
  19511. }
  19512. setupLightingModel() {
  19513. return new VolumetricLightingModel();
  19514. }
  19515. }
  19516. /**
  19517. * This module manages the internal animation loop of the renderer.
  19518. *
  19519. * @private
  19520. */
  19521. class Animation {
  19522. /**
  19523. * Constructs a new animation loop management component.
  19524. *
  19525. * @param {Renderer} renderer - A reference to the main renderer.
  19526. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19527. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19528. */
  19529. constructor( renderer, nodes, info ) {
  19530. /**
  19531. * A reference to the main renderer.
  19532. *
  19533. * @type {Renderer}
  19534. */
  19535. this.renderer = renderer;
  19536. /**
  19537. * Renderer component for managing nodes related logic.
  19538. *
  19539. * @type {Nodes}
  19540. */
  19541. this.nodes = nodes;
  19542. /**
  19543. * Renderer component for managing metrics and monitoring data.
  19544. *
  19545. * @type {Info}
  19546. */
  19547. this.info = info;
  19548. /**
  19549. * A reference to the context from `requestAnimationFrame()` can
  19550. * be called (usually `window`).
  19551. *
  19552. * @type {?(Window|XRSession)}
  19553. */
  19554. this._context = typeof self !== 'undefined' ? self : null;
  19555. /**
  19556. * The user-defined animation loop.
  19557. *
  19558. * @type {?Function}
  19559. * @default null
  19560. */
  19561. this._animationLoop = null;
  19562. /**
  19563. * The requestId which is returned from the `requestAnimationFrame()` call.
  19564. * Can be used to cancel the stop the animation loop.
  19565. *
  19566. * @type {?number}
  19567. * @default null
  19568. */
  19569. this._requestId = null;
  19570. }
  19571. /**
  19572. * Starts the internal animation loop.
  19573. */
  19574. start() {
  19575. const update = ( time, xrFrame ) => {
  19576. this._requestId = this._context.requestAnimationFrame( update );
  19577. if ( this.info.autoReset === true ) this.info.reset();
  19578. this.nodes.nodeFrame.update();
  19579. this.info.frame = this.nodes.nodeFrame.frameId;
  19580. this.renderer._inspector.begin();
  19581. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  19582. this.renderer._inspector.finish();
  19583. };
  19584. update();
  19585. }
  19586. /**
  19587. * Stops the internal animation loop.
  19588. */
  19589. stop() {
  19590. this._context.cancelAnimationFrame( this._requestId );
  19591. this._requestId = null;
  19592. }
  19593. /**
  19594. * Returns the user-level animation loop.
  19595. *
  19596. * @return {?Function} The animation loop.
  19597. */
  19598. getAnimationLoop() {
  19599. return this._animationLoop;
  19600. }
  19601. /**
  19602. * Defines the user-level animation loop.
  19603. *
  19604. * @param {?Function} callback - The animation loop.
  19605. */
  19606. setAnimationLoop( callback ) {
  19607. this._animationLoop = callback;
  19608. }
  19609. /**
  19610. * Returns the animation context.
  19611. *
  19612. * @return {Window|XRSession} The animation context.
  19613. */
  19614. getContext() {
  19615. return this._context;
  19616. }
  19617. /**
  19618. * Defines the context in which `requestAnimationFrame()` is executed.
  19619. *
  19620. * @param {Window|XRSession} context - The context to set.
  19621. */
  19622. setContext( context ) {
  19623. this._context = context;
  19624. }
  19625. /**
  19626. * Frees all internal resources and stops the animation loop.
  19627. */
  19628. dispose() {
  19629. this.stop();
  19630. }
  19631. }
  19632. /**
  19633. * Data structure for the renderer. It allows defining values
  19634. * with chained, hierarchical keys. Keys are meant to be
  19635. * objects since the module internally works with Weak Maps
  19636. * for performance reasons.
  19637. *
  19638. * @private
  19639. */
  19640. class ChainMap {
  19641. /**
  19642. * Constructs a new Chain Map.
  19643. */
  19644. constructor() {
  19645. /**
  19646. * The root Weak Map.
  19647. *
  19648. * @type {WeakMap<Object, WeakMap>}
  19649. */
  19650. this.weakMap = new WeakMap();
  19651. }
  19652. /**
  19653. * Returns the value for the given array of keys.
  19654. *
  19655. * @param {Array<Object>} keys - List of keys.
  19656. * @return {any} The value. Returns `undefined` if no value was found.
  19657. */
  19658. get( keys ) {
  19659. let map = this.weakMap;
  19660. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19661. map = map.get( keys[ i ] );
  19662. if ( map === undefined ) return undefined;
  19663. }
  19664. return map.get( keys[ keys.length - 1 ] );
  19665. }
  19666. /**
  19667. * Sets the value for the given keys.
  19668. *
  19669. * @param {Array<Object>} keys - List of keys.
  19670. * @param {any} value - The value to set.
  19671. * @return {ChainMap} A reference to this Chain Map.
  19672. */
  19673. set( keys, value ) {
  19674. let map = this.weakMap;
  19675. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19676. const key = keys[ i ];
  19677. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  19678. map = map.get( key );
  19679. }
  19680. map.set( keys[ keys.length - 1 ], value );
  19681. return this;
  19682. }
  19683. /**
  19684. * Deletes a value for the given keys.
  19685. *
  19686. * @param {Array<Object>} keys - The keys.
  19687. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  19688. */
  19689. delete( keys ) {
  19690. let map = this.weakMap;
  19691. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19692. map = map.get( keys[ i ] );
  19693. if ( map === undefined ) return false;
  19694. }
  19695. return map.delete( keys[ keys.length - 1 ] );
  19696. }
  19697. }
  19698. let _id$9 = 0;
  19699. function getKeys( obj ) {
  19700. const keys = Object.keys( obj );
  19701. let proto = Object.getPrototypeOf( obj );
  19702. while ( proto ) {
  19703. const descriptors = Object.getOwnPropertyDescriptors( proto );
  19704. for ( const key in descriptors ) {
  19705. if ( descriptors[ key ] !== undefined ) {
  19706. const descriptor = descriptors[ key ];
  19707. if ( descriptor && typeof descriptor.get === 'function' ) {
  19708. keys.push( key );
  19709. }
  19710. }
  19711. }
  19712. proto = Object.getPrototypeOf( proto );
  19713. }
  19714. return keys;
  19715. }
  19716. /**
  19717. * A render object is the renderer's representation of single entity that gets drawn
  19718. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  19719. * scene since render objects also depend from the used material, the current render context
  19720. * and the current scene's lighting.
  19721. *
  19722. * In general, the basic process of the renderer is:
  19723. *
  19724. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  19725. * - Process the render lists by calling one or more render commands for each render item.
  19726. * - For each render command, request a render object and perform the draw.
  19727. *
  19728. * The module provides an interface to get data required for the draw command like the actual
  19729. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  19730. * creating render objects should only be done when necessary.
  19731. *
  19732. * @private
  19733. */
  19734. class RenderObject {
  19735. /**
  19736. * Constructs a new render object.
  19737. *
  19738. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19739. * @param {Geometries} geometries - Renderer component for managing geometries.
  19740. * @param {Renderer} renderer - The renderer.
  19741. * @param {Object3D} object - The 3D object.
  19742. * @param {Material} material - The 3D object's material.
  19743. * @param {Scene} scene - The scene the 3D object belongs to.
  19744. * @param {Camera} camera - The camera the object should be rendered with.
  19745. * @param {LightsNode} lightsNode - The lights node.
  19746. * @param {RenderContext} renderContext - The render context.
  19747. * @param {ClippingContext} clippingContext - The clipping context.
  19748. */
  19749. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  19750. this.id = _id$9 ++;
  19751. /**
  19752. * Renderer component for managing nodes related logic.
  19753. *
  19754. * @type {Nodes}
  19755. * @private
  19756. */
  19757. this._nodes = nodes;
  19758. /**
  19759. * Renderer component for managing geometries.
  19760. *
  19761. * @type {Geometries}
  19762. * @private
  19763. */
  19764. this._geometries = geometries;
  19765. /**
  19766. * The renderer.
  19767. *
  19768. * @type {Renderer}
  19769. */
  19770. this.renderer = renderer;
  19771. /**
  19772. * The 3D object.
  19773. *
  19774. * @type {Object3D}
  19775. */
  19776. this.object = object;
  19777. /**
  19778. * The 3D object's material.
  19779. *
  19780. * @type {Material}
  19781. */
  19782. this.material = material;
  19783. /**
  19784. * The scene the 3D object belongs to.
  19785. *
  19786. * @type {Scene}
  19787. */
  19788. this.scene = scene;
  19789. /**
  19790. * The camera the 3D object should be rendered with.
  19791. *
  19792. * @type {Camera}
  19793. */
  19794. this.camera = camera;
  19795. /**
  19796. * The lights node.
  19797. *
  19798. * @type {LightsNode}
  19799. */
  19800. this.lightsNode = lightsNode;
  19801. /**
  19802. * The render context.
  19803. *
  19804. * @type {RenderContext}
  19805. */
  19806. this.context = renderContext;
  19807. /**
  19808. * The 3D object's geometry.
  19809. *
  19810. * @type {BufferGeometry}
  19811. */
  19812. this.geometry = object.geometry;
  19813. /**
  19814. * The render object's version.
  19815. *
  19816. * @type {number}
  19817. */
  19818. this.version = material.version;
  19819. /**
  19820. * The draw range of the geometry.
  19821. *
  19822. * @type {?Object}
  19823. * @default null
  19824. */
  19825. this.drawRange = null;
  19826. /**
  19827. * An array holding the buffer attributes
  19828. * of the render object. This entails attribute
  19829. * definitions on geometry and node level.
  19830. *
  19831. * @type {?Array<BufferAttribute>}
  19832. * @default null
  19833. */
  19834. this.attributes = null;
  19835. /**
  19836. * An object holding the version of the
  19837. * attributes. The keys are the attribute names
  19838. * and the values are the attribute versions.
  19839. *
  19840. * @type {?Object<string, number>}
  19841. * @default null
  19842. */
  19843. this.attributesId = null;
  19844. /**
  19845. * A reference to a render pipeline the render
  19846. * object is processed with.
  19847. *
  19848. * @type {RenderPipeline}
  19849. * @default null
  19850. */
  19851. this.pipeline = null;
  19852. /**
  19853. * Only relevant for objects using
  19854. * multiple materials. This represents a group entry
  19855. * from the respective `BufferGeometry`.
  19856. *
  19857. * @type {?{start: number, count: number}}
  19858. * @default null
  19859. */
  19860. this.group = null;
  19861. /**
  19862. * An array holding the vertex buffers which can
  19863. * be buffer attributes but also interleaved buffers.
  19864. *
  19865. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  19866. * @default null
  19867. */
  19868. this.vertexBuffers = null;
  19869. /**
  19870. * The parameters for the draw command.
  19871. *
  19872. * @type {?Object}
  19873. * @default null
  19874. */
  19875. this.drawParams = null;
  19876. /**
  19877. * If this render object is used inside a render bundle,
  19878. * this property points to the respective bundle group.
  19879. *
  19880. * @type {?BundleGroup}
  19881. * @default null
  19882. */
  19883. this.bundle = null;
  19884. /**
  19885. * The clipping context.
  19886. *
  19887. * @type {ClippingContext}
  19888. */
  19889. this.clippingContext = clippingContext;
  19890. /**
  19891. * The clipping context's cache key.
  19892. *
  19893. * @type {string}
  19894. */
  19895. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  19896. /**
  19897. * The initial node cache key.
  19898. *
  19899. * @type {number}
  19900. */
  19901. this.initialNodesCacheKey = this.getDynamicCacheKey();
  19902. /**
  19903. * The initial cache key.
  19904. *
  19905. * @type {number}
  19906. */
  19907. this.initialCacheKey = this.getCacheKey();
  19908. /**
  19909. * The node builder state.
  19910. *
  19911. * @type {?NodeBuilderState}
  19912. * @private
  19913. * @default null
  19914. */
  19915. this._nodeBuilderState = null;
  19916. /**
  19917. * An array of bindings.
  19918. *
  19919. * @type {?Array<BindGroup>}
  19920. * @private
  19921. * @default null
  19922. */
  19923. this._bindings = null;
  19924. /**
  19925. * Reference to the node material observer.
  19926. *
  19927. * @type {?NodeMaterialObserver}
  19928. * @private
  19929. * @default null
  19930. */
  19931. this._monitor = null;
  19932. /**
  19933. * An event listener which is defined by `RenderObjects`. It performs
  19934. * clean up tasks when `dispose()` on this render object.
  19935. *
  19936. * @method
  19937. */
  19938. this.onDispose = null;
  19939. /**
  19940. * This flag can be used for type testing.
  19941. *
  19942. * @type {boolean}
  19943. * @readonly
  19944. * @default true
  19945. */
  19946. this.isRenderObject = true;
  19947. /**
  19948. * An event listener which is executed when `dispose()` is called on
  19949. * the material of this render object.
  19950. *
  19951. * @method
  19952. */
  19953. this.onMaterialDispose = () => {
  19954. this.dispose();
  19955. };
  19956. /**
  19957. * An event listener which is executed when `dispose()` is called on
  19958. * the geometry of this render object.
  19959. *
  19960. * @method
  19961. */
  19962. this.onGeometryDispose = () => {
  19963. // clear geometry cache attributes
  19964. this.attributes = null;
  19965. this.attributesId = null;
  19966. };
  19967. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  19968. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  19969. }
  19970. /**
  19971. * Updates the clipping context.
  19972. *
  19973. * @param {ClippingContext} context - The clipping context to set.
  19974. */
  19975. updateClipping( context ) {
  19976. this.clippingContext = context;
  19977. }
  19978. /**
  19979. * Whether the clipping requires an update or not.
  19980. *
  19981. * @type {boolean}
  19982. * @readonly
  19983. */
  19984. get clippingNeedsUpdate() {
  19985. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  19986. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  19987. return true;
  19988. }
  19989. /**
  19990. * The number of clipping planes defined in context of hardware clipping.
  19991. *
  19992. * @type {number}
  19993. * @readonly
  19994. */
  19995. get hardwareClippingPlanes() {
  19996. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  19997. }
  19998. /**
  19999. * Returns the node builder state of this render object.
  20000. *
  20001. * @return {NodeBuilderState} The node builder state.
  20002. */
  20003. getNodeBuilderState() {
  20004. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  20005. }
  20006. /**
  20007. * Returns the node material observer of this render object.
  20008. *
  20009. * @return {NodeMaterialObserver} The node material observer.
  20010. */
  20011. getMonitor() {
  20012. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  20013. }
  20014. /**
  20015. * Returns an array of bind groups of this render object.
  20016. *
  20017. * @return {Array<BindGroup>} The bindings.
  20018. */
  20019. getBindings() {
  20020. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  20021. }
  20022. /**
  20023. * Returns a binding group by group name of this render object.
  20024. *
  20025. * @param {string} name - The name of the binding group.
  20026. * @return {?BindGroup} The bindings.
  20027. */
  20028. getBindingGroup( name ) {
  20029. for ( const bindingGroup of this.getBindings() ) {
  20030. if ( bindingGroup.name === name ) {
  20031. return bindingGroup;
  20032. }
  20033. }
  20034. }
  20035. /**
  20036. * Returns the index of the render object's geometry.
  20037. *
  20038. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20039. */
  20040. getIndex() {
  20041. return this._geometries.getIndex( this );
  20042. }
  20043. /**
  20044. * Returns the indirect buffer attribute.
  20045. *
  20046. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20047. */
  20048. getIndirect() {
  20049. return this._geometries.getIndirect( this );
  20050. }
  20051. /**
  20052. * Returns an array that acts as a key for identifying the render object in a chain map.
  20053. *
  20054. * @return {Array<Object>} An array with object references.
  20055. */
  20056. getChainArray() {
  20057. return [ this.object, this.material, this.context, this.lightsNode ];
  20058. }
  20059. /**
  20060. * This method is used when the geometry of a 3D object has been exchanged and the
  20061. * respective render object now requires an update.
  20062. *
  20063. * @param {BufferGeometry} geometry - The geometry to set.
  20064. */
  20065. setGeometry( geometry ) {
  20066. this.geometry = geometry;
  20067. this.attributes = null;
  20068. this.attributesId = null;
  20069. }
  20070. /**
  20071. * Returns the buffer attributes of the render object. The returned array holds
  20072. * attribute definitions on geometry and node level.
  20073. *
  20074. * @return {Array<BufferAttribute>} An array with buffer attributes.
  20075. */
  20076. getAttributes() {
  20077. if ( this.attributes !== null ) return this.attributes;
  20078. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  20079. const geometry = this.geometry;
  20080. const attributes = [];
  20081. const vertexBuffers = new Set();
  20082. const attributesId = {};
  20083. for ( const nodeAttribute of nodeAttributes ) {
  20084. let attribute;
  20085. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  20086. // node attribute
  20087. attribute = nodeAttribute.node.attribute;
  20088. } else {
  20089. // geometry attribute
  20090. attribute = geometry.getAttribute( nodeAttribute.name );
  20091. attributesId[ nodeAttribute.name ] = attribute.version;
  20092. }
  20093. if ( attribute === undefined ) continue;
  20094. attributes.push( attribute );
  20095. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20096. vertexBuffers.add( bufferAttribute );
  20097. }
  20098. this.attributes = attributes;
  20099. this.attributesId = attributesId;
  20100. this.vertexBuffers = Array.from( vertexBuffers.values() );
  20101. return attributes;
  20102. }
  20103. /**
  20104. * Returns the vertex buffers of the render object.
  20105. *
  20106. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  20107. */
  20108. getVertexBuffers() {
  20109. if ( this.vertexBuffers === null ) this.getAttributes();
  20110. return this.vertexBuffers;
  20111. }
  20112. /**
  20113. * Returns the draw parameters for the render object.
  20114. *
  20115. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  20116. */
  20117. getDrawParameters() {
  20118. const { object, material, geometry, group, drawRange } = this;
  20119. const drawParams = this.drawParams || ( this.drawParams = {
  20120. vertexCount: 0,
  20121. firstVertex: 0,
  20122. instanceCount: 0,
  20123. firstInstance: 0
  20124. } );
  20125. const index = this.getIndex();
  20126. const hasIndex = ( index !== null );
  20127. let instanceCount = 1;
  20128. if ( geometry.isInstancedBufferGeometry === true ) {
  20129. instanceCount = geometry.instanceCount;
  20130. } else if ( object.count !== undefined ) {
  20131. instanceCount = Math.max( 0, object.count );
  20132. }
  20133. if ( instanceCount === 0 ) return null;
  20134. drawParams.instanceCount = instanceCount;
  20135. if ( object.isBatchedMesh === true ) return drawParams;
  20136. let rangeFactor = 1;
  20137. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  20138. rangeFactor = 2;
  20139. }
  20140. let firstVertex = drawRange.start * rangeFactor;
  20141. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  20142. if ( group !== null ) {
  20143. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  20144. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  20145. }
  20146. const position = geometry.attributes.position;
  20147. let itemCount = Infinity;
  20148. if ( hasIndex ) {
  20149. itemCount = index.count;
  20150. } else if ( position !== undefined && position !== null ) {
  20151. itemCount = position.count;
  20152. }
  20153. firstVertex = Math.max( firstVertex, 0 );
  20154. lastVertex = Math.min( lastVertex, itemCount );
  20155. const count = lastVertex - firstVertex;
  20156. if ( count < 0 || count === Infinity ) return null;
  20157. drawParams.vertexCount = count;
  20158. drawParams.firstVertex = firstVertex;
  20159. return drawParams;
  20160. }
  20161. /**
  20162. * Returns the render object's geometry cache key.
  20163. *
  20164. * The geometry cache key is part of the material cache key.
  20165. *
  20166. * @return {string} The geometry cache key.
  20167. */
  20168. getGeometryCacheKey() {
  20169. const { geometry } = this;
  20170. let cacheKey = '';
  20171. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  20172. const attribute = geometry.attributes[ name ];
  20173. cacheKey += name + ',';
  20174. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  20175. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  20176. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  20177. if ( attribute.normalized ) cacheKey += 'n,';
  20178. }
  20179. // structural equality isn't sufficient for morph targets since the
  20180. // data are maintained in textures. only if the targets are all equal
  20181. // the texture and thus the instance of `MorphNode` can be shared.
  20182. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  20183. const targets = geometry.morphAttributes[ name ];
  20184. cacheKey += 'morph-' + name + ',';
  20185. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  20186. const attribute = targets[ i ];
  20187. cacheKey += attribute.id + ',';
  20188. }
  20189. }
  20190. if ( geometry.index ) {
  20191. cacheKey += 'index,';
  20192. }
  20193. return cacheKey;
  20194. }
  20195. /**
  20196. * Returns the render object's material cache key.
  20197. *
  20198. * The material cache key is part of the render object cache key.
  20199. *
  20200. * @return {number} The material cache key.
  20201. */
  20202. getMaterialCacheKey() {
  20203. const { object, material, renderer } = this;
  20204. let cacheKey = material.customProgramCacheKey();
  20205. for ( const property of getKeys( material ) ) {
  20206. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  20207. const value = material[ property ];
  20208. let valueKey;
  20209. if ( value !== null ) {
  20210. // some material values require a formatting
  20211. const type = typeof value;
  20212. if ( type === 'number' ) {
  20213. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  20214. } else if ( type === 'object' ) {
  20215. valueKey = '{';
  20216. if ( value.isTexture ) {
  20217. valueKey += value.mapping;
  20218. // WebGPU must honor the sampler data because they are part of the bindings
  20219. if ( renderer.backend.isWebGPUBackend === true ) {
  20220. valueKey += value.magFilter;
  20221. valueKey += value.minFilter;
  20222. valueKey += value.wrapS;
  20223. valueKey += value.wrapT;
  20224. valueKey += value.wrapR;
  20225. }
  20226. }
  20227. valueKey += '}';
  20228. } else {
  20229. valueKey = String( value );
  20230. }
  20231. } else {
  20232. valueKey = String( value );
  20233. }
  20234. cacheKey += /*property + ':' +*/ valueKey + ',';
  20235. }
  20236. cacheKey += this.clippingContextCacheKey + ',';
  20237. if ( object.geometry ) {
  20238. cacheKey += this.getGeometryCacheKey();
  20239. }
  20240. if ( object.skeleton ) {
  20241. cacheKey += object.skeleton.bones.length + ',';
  20242. }
  20243. if ( object.isBatchedMesh ) {
  20244. cacheKey += object._matricesTexture.uuid + ',';
  20245. if ( object._colorsTexture !== null ) {
  20246. cacheKey += object._colorsTexture.uuid + ',';
  20247. }
  20248. }
  20249. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  20250. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  20251. cacheKey += object.uuid + ',';
  20252. }
  20253. cacheKey += object.receiveShadow + ',';
  20254. return hashString( cacheKey );
  20255. }
  20256. /**
  20257. * Whether the geometry requires an update or not.
  20258. *
  20259. * @type {boolean}
  20260. * @readonly
  20261. */
  20262. get needsGeometryUpdate() {
  20263. if ( this.geometry.id !== this.object.geometry.id ) return true;
  20264. if ( this.attributes !== null ) {
  20265. const attributesId = this.attributesId;
  20266. for ( const name in attributesId ) {
  20267. const attribute = this.geometry.getAttribute( name );
  20268. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  20269. return true;
  20270. }
  20271. }
  20272. }
  20273. return false;
  20274. }
  20275. /**
  20276. * Whether the render object requires an update or not.
  20277. *
  20278. * Note: There are two distinct places where render objects are checked for an update.
  20279. *
  20280. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  20281. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  20282. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  20283. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  20284. * a need for a refresh due to material, geometry or object related value changes.
  20285. *
  20286. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  20287. * that performs the 'needsUpdate' check.
  20288. *
  20289. * @type {boolean}
  20290. * @readonly
  20291. */
  20292. get needsUpdate() {
  20293. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  20294. }
  20295. /**
  20296. * Returns the dynamic cache key which represents a key that is computed per draw command.
  20297. *
  20298. * @return {number} The cache key.
  20299. */
  20300. getDynamicCacheKey() {
  20301. let cacheKey = 0;
  20302. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  20303. // the renderer is inside a shadow pass.
  20304. if ( this.material.isShadowPassMaterial !== true ) {
  20305. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  20306. }
  20307. if ( this.camera.isArrayCamera ) {
  20308. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  20309. }
  20310. if ( this.object.receiveShadow ) {
  20311. cacheKey = hash$1( cacheKey, 1 );
  20312. }
  20313. return cacheKey;
  20314. }
  20315. /**
  20316. * Returns the render object's cache key.
  20317. *
  20318. * @return {number} The cache key.
  20319. */
  20320. getCacheKey() {
  20321. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  20322. }
  20323. /**
  20324. * Frees internal resources.
  20325. */
  20326. dispose() {
  20327. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  20328. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  20329. this.onDispose();
  20330. }
  20331. }
  20332. const _chainKeys$5 = [];
  20333. /**
  20334. * This module manages the render objects of the renderer.
  20335. *
  20336. * @private
  20337. */
  20338. class RenderObjects {
  20339. /**
  20340. * Constructs a new render object management component.
  20341. *
  20342. * @param {Renderer} renderer - The renderer.
  20343. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20344. * @param {Geometries} geometries - Renderer component for managing geometries.
  20345. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20346. * @param {Bindings} bindings - Renderer component for managing bindings.
  20347. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20348. */
  20349. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  20350. /**
  20351. * The renderer.
  20352. *
  20353. * @type {Renderer}
  20354. */
  20355. this.renderer = renderer;
  20356. /**
  20357. * Renderer component for managing nodes related logic.
  20358. *
  20359. * @type {Nodes}
  20360. */
  20361. this.nodes = nodes;
  20362. /**
  20363. * Renderer component for managing geometries.
  20364. *
  20365. * @type {Geometries}
  20366. */
  20367. this.geometries = geometries;
  20368. /**
  20369. * Renderer component for managing pipelines.
  20370. *
  20371. * @type {Pipelines}
  20372. */
  20373. this.pipelines = pipelines;
  20374. /**
  20375. * Renderer component for managing bindings.
  20376. *
  20377. * @type {Bindings}
  20378. */
  20379. this.bindings = bindings;
  20380. /**
  20381. * Renderer component for managing metrics and monitoring data.
  20382. *
  20383. * @type {Info}
  20384. */
  20385. this.info = info;
  20386. /**
  20387. * A dictionary that manages render contexts in chain maps
  20388. * for each pass ID.
  20389. *
  20390. * @type {Object<string,ChainMap>}
  20391. */
  20392. this.chainMaps = {};
  20393. }
  20394. /**
  20395. * Returns a render object for the given object and state data.
  20396. *
  20397. * @param {Object3D} object - The 3D object.
  20398. * @param {Material} material - The 3D object's material.
  20399. * @param {Scene} scene - The scene the 3D object belongs to.
  20400. * @param {Camera} camera - The camera the 3D object should be rendered with.
  20401. * @param {LightsNode} lightsNode - The lights node.
  20402. * @param {RenderContext} renderContext - The render context.
  20403. * @param {ClippingContext} clippingContext - The clipping context.
  20404. * @param {string} [passId] - An optional ID for identifying the pass.
  20405. * @return {RenderObject} The render object.
  20406. */
  20407. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20408. const chainMap = this.getChainMap( passId );
  20409. // reuse chainArray
  20410. _chainKeys$5[ 0 ] = object;
  20411. _chainKeys$5[ 1 ] = material;
  20412. _chainKeys$5[ 2 ] = renderContext;
  20413. _chainKeys$5[ 3 ] = lightsNode;
  20414. let renderObject = chainMap.get( _chainKeys$5 );
  20415. if ( renderObject === undefined ) {
  20416. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20417. chainMap.set( _chainKeys$5, renderObject );
  20418. } else {
  20419. renderObject.updateClipping( clippingContext );
  20420. if ( renderObject.needsGeometryUpdate ) {
  20421. renderObject.setGeometry( object.geometry );
  20422. }
  20423. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  20424. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  20425. renderObject.dispose();
  20426. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20427. } else {
  20428. renderObject.version = material.version;
  20429. }
  20430. }
  20431. }
  20432. _chainKeys$5.length = 0;
  20433. return renderObject;
  20434. }
  20435. /**
  20436. * Returns a chain map for the given pass ID.
  20437. *
  20438. * @param {string} [passId='default'] - The pass ID.
  20439. * @return {ChainMap} The chain map.
  20440. */
  20441. getChainMap( passId = 'default' ) {
  20442. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  20443. }
  20444. /**
  20445. * Frees internal resources.
  20446. */
  20447. dispose() {
  20448. this.chainMaps = {};
  20449. }
  20450. /**
  20451. * Factory method for creating render objects with the given list of parameters.
  20452. *
  20453. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20454. * @param {Geometries} geometries - Renderer component for managing geometries.
  20455. * @param {Renderer} renderer - The renderer.
  20456. * @param {Object3D} object - The 3D object.
  20457. * @param {Material} material - The object's material.
  20458. * @param {Scene} scene - The scene the 3D object belongs to.
  20459. * @param {Camera} camera - The camera the object should be rendered with.
  20460. * @param {LightsNode} lightsNode - The lights node.
  20461. * @param {RenderContext} renderContext - The render context.
  20462. * @param {ClippingContext} clippingContext - The clipping context.
  20463. * @param {string} [passId] - An optional ID for identifying the pass.
  20464. * @return {RenderObject} The render object.
  20465. */
  20466. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20467. const chainMap = this.getChainMap( passId );
  20468. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  20469. renderObject.onDispose = () => {
  20470. this.pipelines.delete( renderObject );
  20471. this.bindings.deleteForRender( renderObject );
  20472. this.nodes.delete( renderObject );
  20473. chainMap.delete( renderObject.getChainArray() );
  20474. };
  20475. return renderObject;
  20476. }
  20477. }
  20478. /**
  20479. * Data structure for the renderer. It is intended to manage
  20480. * data of objects in dictionaries.
  20481. *
  20482. * @private
  20483. */
  20484. class DataMap {
  20485. /**
  20486. * Constructs a new data map.
  20487. */
  20488. constructor() {
  20489. /**
  20490. * `DataMap` internally uses a weak map
  20491. * to manage its data.
  20492. *
  20493. * @type {WeakMap<Object, Object>}
  20494. */
  20495. this.data = new WeakMap();
  20496. }
  20497. /**
  20498. * Returns the dictionary for the given object.
  20499. *
  20500. * @param {Object} object - The object.
  20501. * @return {Object} The dictionary.
  20502. */
  20503. get( object ) {
  20504. let map = this.data.get( object );
  20505. if ( map === undefined ) {
  20506. map = {};
  20507. this.data.set( object, map );
  20508. }
  20509. return map;
  20510. }
  20511. /**
  20512. * Deletes the dictionary for the given object.
  20513. *
  20514. * @param {Object} object - The object.
  20515. * @return {?Object} The deleted dictionary.
  20516. */
  20517. delete( object ) {
  20518. let map = null;
  20519. if ( this.data.has( object ) ) {
  20520. map = this.data.get( object );
  20521. this.data.delete( object );
  20522. }
  20523. return map;
  20524. }
  20525. /**
  20526. * Returns `true` if the given object has a dictionary defined.
  20527. *
  20528. * @param {Object} object - The object to test.
  20529. * @return {boolean} Whether a dictionary is defined or not.
  20530. */
  20531. has( object ) {
  20532. return this.data.has( object );
  20533. }
  20534. /**
  20535. * Frees internal resources.
  20536. */
  20537. dispose() {
  20538. this.data = new WeakMap();
  20539. }
  20540. }
  20541. const AttributeType = {
  20542. VERTEX: 1,
  20543. INDEX: 2,
  20544. STORAGE: 3,
  20545. INDIRECT: 4
  20546. };
  20547. // size of a chunk in bytes (STD140 layout)
  20548. const GPU_CHUNK_BYTES = 16;
  20549. // @TODO: Move to src/constants.js
  20550. const BlendColorFactor = 211;
  20551. const OneMinusBlendColorFactor = 212;
  20552. /**
  20553. * This renderer module manages geometry attributes.
  20554. *
  20555. * @private
  20556. * @augments DataMap
  20557. */
  20558. class Attributes extends DataMap {
  20559. /**
  20560. * Constructs a new attribute management component.
  20561. *
  20562. * @param {Backend} backend - The renderer's backend.
  20563. */
  20564. constructor( backend ) {
  20565. super();
  20566. /**
  20567. * The renderer's backend.
  20568. *
  20569. * @type {Backend}
  20570. */
  20571. this.backend = backend;
  20572. }
  20573. /**
  20574. * Deletes the data for the given attribute.
  20575. *
  20576. * @param {BufferAttribute} attribute - The attribute.
  20577. * @return {?Object} The deleted attribute data.
  20578. */
  20579. delete( attribute ) {
  20580. const attributeData = super.delete( attribute );
  20581. if ( attributeData !== null ) {
  20582. this.backend.destroyAttribute( attribute );
  20583. }
  20584. return attributeData;
  20585. }
  20586. /**
  20587. * Updates the given attribute. This method creates attribute buffers
  20588. * for new attributes and updates data for existing ones.
  20589. *
  20590. * @param {BufferAttribute} attribute - The attribute to update.
  20591. * @param {number} type - The attribute type.
  20592. */
  20593. update( attribute, type ) {
  20594. const data = this.get( attribute );
  20595. if ( data.version === undefined ) {
  20596. if ( type === AttributeType.VERTEX ) {
  20597. this.backend.createAttribute( attribute );
  20598. } else if ( type === AttributeType.INDEX ) {
  20599. this.backend.createIndexAttribute( attribute );
  20600. } else if ( type === AttributeType.STORAGE ) {
  20601. this.backend.createStorageAttribute( attribute );
  20602. } else if ( type === AttributeType.INDIRECT ) {
  20603. this.backend.createIndirectStorageAttribute( attribute );
  20604. }
  20605. data.version = this._getBufferAttribute( attribute ).version;
  20606. } else {
  20607. const bufferAttribute = this._getBufferAttribute( attribute );
  20608. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  20609. this.backend.updateAttribute( attribute );
  20610. data.version = bufferAttribute.version;
  20611. }
  20612. }
  20613. }
  20614. /**
  20615. * Utility method for handling interleaved buffer attributes correctly.
  20616. * To process them, their `InterleavedBuffer` is returned.
  20617. *
  20618. * @param {BufferAttribute} attribute - The attribute.
  20619. * @return {BufferAttribute|InterleavedBuffer}
  20620. */
  20621. _getBufferAttribute( attribute ) {
  20622. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  20623. return attribute;
  20624. }
  20625. }
  20626. /**
  20627. * Returns the wireframe version for the given geometry.
  20628. *
  20629. * @private
  20630. * @function
  20631. * @param {BufferGeometry} geometry - The geometry.
  20632. * @return {number} The version.
  20633. */
  20634. function getWireframeVersion( geometry ) {
  20635. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  20636. }
  20637. /**
  20638. * Returns a wireframe index attribute for the given geometry.
  20639. *
  20640. * @private
  20641. * @function
  20642. * @param {BufferGeometry} geometry - The geometry.
  20643. * @return {BufferAttribute} The wireframe index attribute.
  20644. */
  20645. function getWireframeIndex( geometry ) {
  20646. const indices = [];
  20647. const geometryIndex = geometry.index;
  20648. const geometryPosition = geometry.attributes.position;
  20649. if ( geometryIndex !== null ) {
  20650. const array = geometryIndex.array;
  20651. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  20652. const a = array[ i + 0 ];
  20653. const b = array[ i + 1 ];
  20654. const c = array[ i + 2 ];
  20655. indices.push( a, b, b, c, c, a );
  20656. }
  20657. } else {
  20658. const array = geometryPosition.array;
  20659. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  20660. const a = i + 0;
  20661. const b = i + 1;
  20662. const c = i + 2;
  20663. indices.push( a, b, b, c, c, a );
  20664. }
  20665. }
  20666. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  20667. attribute.version = getWireframeVersion( geometry );
  20668. return attribute;
  20669. }
  20670. /**
  20671. * This renderer module manages geometries.
  20672. *
  20673. * @private
  20674. * @augments DataMap
  20675. */
  20676. class Geometries extends DataMap {
  20677. /**
  20678. * Constructs a new geometry management component.
  20679. *
  20680. * @param {Attributes} attributes - Renderer component for managing attributes.
  20681. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20682. */
  20683. constructor( attributes, info ) {
  20684. super();
  20685. /**
  20686. * Renderer component for managing attributes.
  20687. *
  20688. * @type {Attributes}
  20689. */
  20690. this.attributes = attributes;
  20691. /**
  20692. * Renderer component for managing metrics and monitoring data.
  20693. *
  20694. * @type {Info}
  20695. */
  20696. this.info = info;
  20697. /**
  20698. * Weak Map for managing attributes for wireframe rendering.
  20699. *
  20700. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  20701. */
  20702. this.wireframes = new WeakMap();
  20703. /**
  20704. * This Weak Map is used to make sure buffer attributes are
  20705. * updated only once per render call.
  20706. *
  20707. * @type {WeakMap<BufferAttribute,number>}
  20708. */
  20709. this.attributeCall = new WeakMap();
  20710. /**
  20711. * Stores the event listeners attached to geometries.
  20712. *
  20713. * @private
  20714. * @type {Map<BufferGeometry,Function>}
  20715. */
  20716. this._geometryDisposeListeners = new Map();
  20717. }
  20718. /**
  20719. * Returns `true` if the given render object has an initialized geometry.
  20720. *
  20721. * @param {RenderObject} renderObject - The render object.
  20722. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  20723. */
  20724. has( renderObject ) {
  20725. const geometry = renderObject.geometry;
  20726. return super.has( geometry ) && this.get( geometry ).initialized === true;
  20727. }
  20728. /**
  20729. * Prepares the geometry of the given render object for rendering.
  20730. *
  20731. * @param {RenderObject} renderObject - The render object.
  20732. */
  20733. updateForRender( renderObject ) {
  20734. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  20735. this.updateAttributes( renderObject );
  20736. }
  20737. /**
  20738. * Initializes the geometry of the given render object.
  20739. *
  20740. * @param {RenderObject} renderObject - The render object.
  20741. */
  20742. initGeometry( renderObject ) {
  20743. const geometry = renderObject.geometry;
  20744. const geometryData = this.get( geometry );
  20745. geometryData.initialized = true;
  20746. this.info.memory.geometries ++;
  20747. const onDispose = () => {
  20748. this.info.memory.geometries --;
  20749. const index = geometry.index;
  20750. const geometryAttributes = renderObject.getAttributes();
  20751. if ( index !== null ) {
  20752. this.attributes.delete( index );
  20753. }
  20754. for ( const geometryAttribute of geometryAttributes ) {
  20755. this.attributes.delete( geometryAttribute );
  20756. }
  20757. const wireframeAttribute = this.wireframes.get( geometry );
  20758. if ( wireframeAttribute !== undefined ) {
  20759. this.attributes.delete( wireframeAttribute );
  20760. }
  20761. geometry.removeEventListener( 'dispose', onDispose );
  20762. this._geometryDisposeListeners.delete( geometry );
  20763. };
  20764. geometry.addEventListener( 'dispose', onDispose );
  20765. // see #31798 why tracking separate remove listeners is required right now
  20766. // TODO: Re-evaluate how onDispose() is managed in this component
  20767. this._geometryDisposeListeners.set( geometry, onDispose );
  20768. }
  20769. /**
  20770. * Updates the geometry attributes of the given render object.
  20771. *
  20772. * @param {RenderObject} renderObject - The render object.
  20773. */
  20774. updateAttributes( renderObject ) {
  20775. // attributes
  20776. const attributes = renderObject.getAttributes();
  20777. for ( const attribute of attributes ) {
  20778. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  20779. this.updateAttribute( attribute, AttributeType.STORAGE );
  20780. } else {
  20781. this.updateAttribute( attribute, AttributeType.VERTEX );
  20782. }
  20783. }
  20784. // indexes
  20785. const index = this.getIndex( renderObject );
  20786. if ( index !== null ) {
  20787. this.updateAttribute( index, AttributeType.INDEX );
  20788. }
  20789. // indirect
  20790. const indirect = renderObject.geometry.indirect;
  20791. if ( indirect !== null ) {
  20792. this.updateAttribute( indirect, AttributeType.INDIRECT );
  20793. }
  20794. }
  20795. /**
  20796. * Updates the given attribute.
  20797. *
  20798. * @param {BufferAttribute} attribute - The attribute to update.
  20799. * @param {number} type - The attribute type.
  20800. */
  20801. updateAttribute( attribute, type ) {
  20802. const callId = this.info.render.calls;
  20803. if ( ! attribute.isInterleavedBufferAttribute ) {
  20804. if ( this.attributeCall.get( attribute ) !== callId ) {
  20805. this.attributes.update( attribute, type );
  20806. this.attributeCall.set( attribute, callId );
  20807. }
  20808. } else {
  20809. if ( this.attributeCall.get( attribute ) === undefined ) {
  20810. this.attributes.update( attribute, type );
  20811. this.attributeCall.set( attribute, callId );
  20812. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  20813. this.attributes.update( attribute, type );
  20814. this.attributeCall.set( attribute.data, callId );
  20815. this.attributeCall.set( attribute, callId );
  20816. }
  20817. }
  20818. }
  20819. /**
  20820. * Returns the indirect buffer attribute of the given render object.
  20821. *
  20822. * @param {RenderObject} renderObject - The render object.
  20823. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20824. */
  20825. getIndirect( renderObject ) {
  20826. return renderObject.geometry.indirect;
  20827. }
  20828. /**
  20829. * Returns the index of the given render object's geometry. This is implemented
  20830. * in a method to return a wireframe index if necessary.
  20831. *
  20832. * @param {RenderObject} renderObject - The render object.
  20833. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20834. */
  20835. getIndex( renderObject ) {
  20836. const { geometry, material } = renderObject;
  20837. let index = geometry.index;
  20838. if ( material.wireframe === true ) {
  20839. const wireframes = this.wireframes;
  20840. let wireframeAttribute = wireframes.get( geometry );
  20841. if ( wireframeAttribute === undefined ) {
  20842. wireframeAttribute = getWireframeIndex( geometry );
  20843. wireframes.set( geometry, wireframeAttribute );
  20844. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  20845. this.attributes.delete( wireframeAttribute );
  20846. wireframeAttribute = getWireframeIndex( geometry );
  20847. wireframes.set( geometry, wireframeAttribute );
  20848. }
  20849. index = wireframeAttribute;
  20850. }
  20851. return index;
  20852. }
  20853. dispose() {
  20854. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  20855. geometry.removeEventListener( 'dispose', onDispose );
  20856. }
  20857. this._geometryDisposeListeners.clear();
  20858. }
  20859. }
  20860. /**
  20861. * This renderer module provides a series of statistical information
  20862. * about the GPU memory and the rendering process. Useful for debugging
  20863. * and monitoring.
  20864. */
  20865. class Info {
  20866. /**
  20867. * Constructs a new info component.
  20868. */
  20869. constructor() {
  20870. /**
  20871. * Whether frame related metrics should automatically
  20872. * be resetted or not. This property should be set to `false`
  20873. * by apps which manage their own animation loop. They must
  20874. * then call `renderer.info.reset()` once per frame manually.
  20875. *
  20876. * @type {boolean}
  20877. * @default true
  20878. */
  20879. this.autoReset = true;
  20880. /**
  20881. * The current frame ID. This ID is managed
  20882. * by `NodeFrame`.
  20883. *
  20884. * @type {number}
  20885. * @readonly
  20886. * @default 0
  20887. */
  20888. this.frame = 0;
  20889. /**
  20890. * The number of render calls since the
  20891. * app has been started.
  20892. *
  20893. * @type {number}
  20894. * @readonly
  20895. * @default 0
  20896. */
  20897. this.calls = 0;
  20898. /**
  20899. * Render related metrics.
  20900. *
  20901. * @type {Object}
  20902. * @readonly
  20903. * @property {number} calls - The number of render calls since the app has been started.
  20904. * @property {number} frameCalls - The number of render calls of the current frame.
  20905. * @property {number} drawCalls - The number of draw calls of the current frame.
  20906. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  20907. * @property {number} points - The number of rendered point primitives of the current frame.
  20908. * @property {number} lines - The number of rendered line primitives of the current frame.
  20909. * @property {number} timestamp - The timestamp of the frame.
  20910. */
  20911. this.render = {
  20912. calls: 0,
  20913. frameCalls: 0,
  20914. drawCalls: 0,
  20915. triangles: 0,
  20916. points: 0,
  20917. lines: 0,
  20918. timestamp: 0,
  20919. };
  20920. /**
  20921. * Compute related metrics.
  20922. *
  20923. * @type {Object}
  20924. * @readonly
  20925. * @property {number} calls - The number of compute calls since the app has been started.
  20926. * @property {number} frameCalls - The number of compute calls of the current frame.
  20927. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  20928. */
  20929. this.compute = {
  20930. calls: 0,
  20931. frameCalls: 0,
  20932. timestamp: 0
  20933. };
  20934. /**
  20935. * Memory related metrics.
  20936. *
  20937. * @type {Object}
  20938. * @readonly
  20939. * @property {number} geometries - The number of active geometries.
  20940. * @property {number} frameCalls - The number of active textures.
  20941. */
  20942. this.memory = {
  20943. geometries: 0,
  20944. textures: 0
  20945. };
  20946. }
  20947. /**
  20948. * This method should be executed per draw call and updates the corresponding metrics.
  20949. *
  20950. * @param {Object3D} object - The 3D object that is going to be rendered.
  20951. * @param {number} count - The vertex or index count.
  20952. * @param {number} instanceCount - The instance count.
  20953. */
  20954. update( object, count, instanceCount ) {
  20955. this.render.drawCalls ++;
  20956. if ( object.isMesh || object.isSprite ) {
  20957. this.render.triangles += instanceCount * ( count / 3 );
  20958. } else if ( object.isPoints ) {
  20959. this.render.points += instanceCount * count;
  20960. } else if ( object.isLineSegments ) {
  20961. this.render.lines += instanceCount * ( count / 2 );
  20962. } else if ( object.isLine ) {
  20963. this.render.lines += instanceCount * ( count - 1 );
  20964. } else {
  20965. error( 'WebGPUInfo: Unknown object type.' );
  20966. }
  20967. }
  20968. /**
  20969. * Resets frame related metrics.
  20970. */
  20971. reset() {
  20972. this.render.drawCalls = 0;
  20973. this.render.frameCalls = 0;
  20974. this.compute.frameCalls = 0;
  20975. this.render.triangles = 0;
  20976. this.render.points = 0;
  20977. this.render.lines = 0;
  20978. }
  20979. /**
  20980. * Performs a complete reset of the object.
  20981. */
  20982. dispose() {
  20983. this.reset();
  20984. this.calls = 0;
  20985. this.render.calls = 0;
  20986. this.compute.calls = 0;
  20987. this.render.timestamp = 0;
  20988. this.compute.timestamp = 0;
  20989. this.memory.geometries = 0;
  20990. this.memory.textures = 0;
  20991. }
  20992. }
  20993. /**
  20994. * Abstract class for representing pipelines.
  20995. *
  20996. * @private
  20997. * @abstract
  20998. */
  20999. class Pipeline {
  21000. /**
  21001. * Constructs a new pipeline.
  21002. *
  21003. * @param {string} cacheKey - The pipeline's cache key.
  21004. */
  21005. constructor( cacheKey ) {
  21006. /**
  21007. * The pipeline's cache key.
  21008. *
  21009. * @type {string}
  21010. */
  21011. this.cacheKey = cacheKey;
  21012. /**
  21013. * How often the pipeline is currently in use.
  21014. *
  21015. * @type {number}
  21016. * @default 0
  21017. */
  21018. this.usedTimes = 0;
  21019. }
  21020. }
  21021. /**
  21022. * Class for representing render pipelines.
  21023. *
  21024. * @private
  21025. * @augments Pipeline
  21026. */
  21027. class RenderPipeline extends Pipeline {
  21028. /**
  21029. * Constructs a new render pipeline.
  21030. *
  21031. * @param {string} cacheKey - The pipeline's cache key.
  21032. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  21033. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  21034. */
  21035. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21036. super( cacheKey );
  21037. /**
  21038. * The pipeline's vertex shader.
  21039. *
  21040. * @type {ProgrammableStage}
  21041. */
  21042. this.vertexProgram = vertexProgram;
  21043. /**
  21044. * The pipeline's fragment shader.
  21045. *
  21046. * @type {ProgrammableStage}
  21047. */
  21048. this.fragmentProgram = fragmentProgram;
  21049. }
  21050. }
  21051. /**
  21052. * Class for representing compute pipelines.
  21053. *
  21054. * @private
  21055. * @augments Pipeline
  21056. */
  21057. class ComputePipeline extends Pipeline {
  21058. /**
  21059. * Constructs a new render pipeline.
  21060. *
  21061. * @param {string} cacheKey - The pipeline's cache key.
  21062. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  21063. */
  21064. constructor( cacheKey, computeProgram ) {
  21065. super( cacheKey );
  21066. /**
  21067. * The pipeline's compute shader.
  21068. *
  21069. * @type {ProgrammableStage}
  21070. */
  21071. this.computeProgram = computeProgram;
  21072. /**
  21073. * This flag can be used for type testing.
  21074. *
  21075. * @type {boolean}
  21076. * @readonly
  21077. * @default true
  21078. */
  21079. this.isComputePipeline = true;
  21080. }
  21081. }
  21082. let _id$8 = 0;
  21083. /**
  21084. * Class for representing programmable stages which are vertex,
  21085. * fragment or compute shaders. Unlike fixed-function states (like blending),
  21086. * they represent the programmable part of a pipeline.
  21087. *
  21088. * @private
  21089. */
  21090. class ProgrammableStage {
  21091. /**
  21092. * Constructs a new programmable stage.
  21093. *
  21094. * @param {string} code - The shader code.
  21095. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  21096. * @param {string} name - The name of the shader.
  21097. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21098. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21099. */
  21100. constructor( code, stage, name, transforms = null, attributes = null ) {
  21101. /**
  21102. * The id of the programmable stage.
  21103. *
  21104. * @type {number}
  21105. */
  21106. this.id = _id$8 ++;
  21107. /**
  21108. * The shader code.
  21109. *
  21110. * @type {string}
  21111. */
  21112. this.code = code;
  21113. /**
  21114. * The type of stage.
  21115. *
  21116. * @type {string}
  21117. */
  21118. this.stage = stage;
  21119. /**
  21120. * The name of the stage.
  21121. * This is used for debugging purposes.
  21122. *
  21123. * @type {string}
  21124. */
  21125. this.name = name;
  21126. /**
  21127. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21128. *
  21129. * @type {?Array<Object>}
  21130. */
  21131. this.transforms = transforms;
  21132. /**
  21133. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21134. *
  21135. * @type {?Array<Object>}
  21136. */
  21137. this.attributes = attributes;
  21138. /**
  21139. * How often the programmable stage is currently in use.
  21140. *
  21141. * @type {number}
  21142. * @default 0
  21143. */
  21144. this.usedTimes = 0;
  21145. }
  21146. }
  21147. /**
  21148. * This renderer module manages the pipelines of the renderer.
  21149. *
  21150. * @private
  21151. * @augments DataMap
  21152. */
  21153. class Pipelines extends DataMap {
  21154. /**
  21155. * Constructs a new pipeline management component.
  21156. *
  21157. * @param {Backend} backend - The renderer's backend.
  21158. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21159. */
  21160. constructor( backend, nodes ) {
  21161. super();
  21162. /**
  21163. * The renderer's backend.
  21164. *
  21165. * @type {Backend}
  21166. */
  21167. this.backend = backend;
  21168. /**
  21169. * Renderer component for managing nodes related logic.
  21170. *
  21171. * @type {Nodes}
  21172. */
  21173. this.nodes = nodes;
  21174. /**
  21175. * A references to the bindings management component.
  21176. * This reference will be set inside the `Bindings`
  21177. * constructor.
  21178. *
  21179. * @type {?Bindings}
  21180. * @default null
  21181. */
  21182. this.bindings = null;
  21183. /**
  21184. * Internal cache for maintaining pipelines.
  21185. * The key of the map is a cache key, the value the pipeline.
  21186. *
  21187. * @type {Map<string,Pipeline>}
  21188. */
  21189. this.caches = new Map();
  21190. /**
  21191. * This dictionary maintains for each shader stage type (vertex,
  21192. * fragment and compute) the programmable stage objects which
  21193. * represent the actual shader code.
  21194. *
  21195. * @type {Object<string,Map<string, ProgrammableStage>>}
  21196. */
  21197. this.programs = {
  21198. vertex: new Map(),
  21199. fragment: new Map(),
  21200. compute: new Map()
  21201. };
  21202. }
  21203. /**
  21204. * Returns a compute pipeline for the given compute node.
  21205. *
  21206. * @param {Node} computeNode - The compute node.
  21207. * @param {Array<BindGroup>} bindings - The bindings.
  21208. * @return {ComputePipeline} The compute pipeline.
  21209. */
  21210. getForCompute( computeNode, bindings ) {
  21211. const { backend } = this;
  21212. const data = this.get( computeNode );
  21213. if ( this._needsComputeUpdate( computeNode ) ) {
  21214. const previousPipeline = data.pipeline;
  21215. if ( previousPipeline ) {
  21216. previousPipeline.usedTimes --;
  21217. previousPipeline.computeProgram.usedTimes --;
  21218. }
  21219. // get shader
  21220. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21221. // programmable stage
  21222. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21223. if ( stageCompute === undefined ) {
  21224. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21225. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21226. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21227. backend.createProgram( stageCompute );
  21228. }
  21229. // determine compute pipeline
  21230. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21231. let pipeline = this.caches.get( cacheKey );
  21232. if ( pipeline === undefined ) {
  21233. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21234. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  21235. }
  21236. // keep track of all used times
  21237. pipeline.usedTimes ++;
  21238. stageCompute.usedTimes ++;
  21239. //
  21240. data.version = computeNode.version;
  21241. data.pipeline = pipeline;
  21242. }
  21243. return data.pipeline;
  21244. }
  21245. /**
  21246. * Returns a render pipeline for the given render object.
  21247. *
  21248. * @param {RenderObject} renderObject - The render object.
  21249. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21250. * @return {RenderPipeline} The render pipeline.
  21251. */
  21252. getForRender( renderObject, promises = null ) {
  21253. const { backend } = this;
  21254. const data = this.get( renderObject );
  21255. if ( this._needsRenderUpdate( renderObject ) ) {
  21256. const previousPipeline = data.pipeline;
  21257. if ( previousPipeline ) {
  21258. previousPipeline.usedTimes --;
  21259. previousPipeline.vertexProgram.usedTimes --;
  21260. previousPipeline.fragmentProgram.usedTimes --;
  21261. }
  21262. // get shader
  21263. const nodeBuilderState = renderObject.getNodeBuilderState();
  21264. const name = renderObject.material ? renderObject.material.name : '';
  21265. // programmable stages
  21266. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  21267. if ( stageVertex === undefined ) {
  21268. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  21269. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  21270. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  21271. backend.createProgram( stageVertex );
  21272. }
  21273. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  21274. if ( stageFragment === undefined ) {
  21275. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  21276. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  21277. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  21278. backend.createProgram( stageFragment );
  21279. }
  21280. // determine render pipeline
  21281. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21282. let pipeline = this.caches.get( cacheKey );
  21283. if ( pipeline === undefined ) {
  21284. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21285. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  21286. } else {
  21287. renderObject.pipeline = pipeline;
  21288. }
  21289. // keep track of all used times
  21290. pipeline.usedTimes ++;
  21291. stageVertex.usedTimes ++;
  21292. stageFragment.usedTimes ++;
  21293. //
  21294. data.pipeline = pipeline;
  21295. }
  21296. return data.pipeline;
  21297. }
  21298. /**
  21299. * Deletes the pipeline for the given render object.
  21300. *
  21301. * @param {RenderObject} object - The render object.
  21302. * @return {?Object} The deleted dictionary.
  21303. */
  21304. delete( object ) {
  21305. const pipeline = this.get( object ).pipeline;
  21306. if ( pipeline ) {
  21307. // pipeline
  21308. pipeline.usedTimes --;
  21309. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  21310. // programs
  21311. if ( pipeline.isComputePipeline ) {
  21312. pipeline.computeProgram.usedTimes --;
  21313. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  21314. } else {
  21315. pipeline.fragmentProgram.usedTimes --;
  21316. pipeline.vertexProgram.usedTimes --;
  21317. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  21318. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  21319. }
  21320. }
  21321. return super.delete( object );
  21322. }
  21323. /**
  21324. * Frees internal resources.
  21325. */
  21326. dispose() {
  21327. super.dispose();
  21328. this.caches = new Map();
  21329. this.programs = {
  21330. vertex: new Map(),
  21331. fragment: new Map(),
  21332. compute: new Map()
  21333. };
  21334. }
  21335. /**
  21336. * Updates the pipeline for the given render object.
  21337. *
  21338. * @param {RenderObject} renderObject - The render object.
  21339. */
  21340. updateForRender( renderObject ) {
  21341. this.getForRender( renderObject );
  21342. }
  21343. /**
  21344. * Returns a compute pipeline for the given parameters.
  21345. *
  21346. * @private
  21347. * @param {Node} computeNode - The compute node.
  21348. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21349. * @param {string} cacheKey - The cache key.
  21350. * @param {Array<BindGroup>} bindings - The bindings.
  21351. * @return {ComputePipeline} The compute pipeline.
  21352. */
  21353. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  21354. // check for existing pipeline
  21355. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  21356. let pipeline = this.caches.get( cacheKey );
  21357. if ( pipeline === undefined ) {
  21358. pipeline = new ComputePipeline( cacheKey, stageCompute );
  21359. this.caches.set( cacheKey, pipeline );
  21360. this.backend.createComputePipeline( pipeline, bindings );
  21361. }
  21362. return pipeline;
  21363. }
  21364. /**
  21365. * Returns a render pipeline for the given parameters.
  21366. *
  21367. * @private
  21368. * @param {RenderObject} renderObject - The render object.
  21369. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21370. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21371. * @param {string} cacheKey - The cache key.
  21372. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21373. * @return {ComputePipeline} The compute pipeline.
  21374. */
  21375. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  21376. // check for existing pipeline
  21377. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21378. let pipeline = this.caches.get( cacheKey );
  21379. if ( pipeline === undefined ) {
  21380. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  21381. this.caches.set( cacheKey, pipeline );
  21382. renderObject.pipeline = pipeline;
  21383. // The `promises` array is `null` by default and only set to an empty array when
  21384. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  21385. // pending promises that resolve when the render pipelines are ready for rendering.
  21386. this.backend.createRenderPipeline( renderObject, promises );
  21387. }
  21388. return pipeline;
  21389. }
  21390. /**
  21391. * Computes a cache key representing a compute pipeline.
  21392. *
  21393. * @private
  21394. * @param {Node} computeNode - The compute node.
  21395. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21396. * @return {string} The cache key.
  21397. */
  21398. _getComputeCacheKey( computeNode, stageCompute ) {
  21399. return computeNode.id + ',' + stageCompute.id;
  21400. }
  21401. /**
  21402. * Computes a cache key representing a render pipeline.
  21403. *
  21404. * @private
  21405. * @param {RenderObject} renderObject - The render object.
  21406. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21407. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21408. * @return {string} The cache key.
  21409. */
  21410. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  21411. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  21412. }
  21413. /**
  21414. * Releases the given pipeline.
  21415. *
  21416. * @private
  21417. * @param {Pipeline} pipeline - The pipeline to release.
  21418. */
  21419. _releasePipeline( pipeline ) {
  21420. this.caches.delete( pipeline.cacheKey );
  21421. }
  21422. /**
  21423. * Releases the shader program.
  21424. *
  21425. * @private
  21426. * @param {Object} program - The shader program to release.
  21427. */
  21428. _releaseProgram( program ) {
  21429. const code = program.code;
  21430. const stage = program.stage;
  21431. this.programs[ stage ].delete( code );
  21432. }
  21433. /**
  21434. * Returns `true` if the compute pipeline for the given compute node requires an update.
  21435. *
  21436. * @private
  21437. * @param {Node} computeNode - The compute node.
  21438. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  21439. */
  21440. _needsComputeUpdate( computeNode ) {
  21441. const data = this.get( computeNode );
  21442. return data.pipeline === undefined || data.version !== computeNode.version;
  21443. }
  21444. /**
  21445. * Returns `true` if the render pipeline for the given render object requires an update.
  21446. *
  21447. * @private
  21448. * @param {RenderObject} renderObject - The render object.
  21449. * @return {boolean} Whether the render object for the given render object requires an update or not.
  21450. */
  21451. _needsRenderUpdate( renderObject ) {
  21452. const data = this.get( renderObject );
  21453. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  21454. }
  21455. }
  21456. /**
  21457. * This renderer module manages the bindings of the renderer.
  21458. *
  21459. * @private
  21460. * @augments DataMap
  21461. */
  21462. class Bindings extends DataMap {
  21463. /**
  21464. * Constructs a new bindings management component.
  21465. *
  21466. * @param {Backend} backend - The renderer's backend.
  21467. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21468. * @param {Textures} textures - Renderer component for managing textures.
  21469. * @param {Attributes} attributes - Renderer component for managing attributes.
  21470. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  21471. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21472. */
  21473. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  21474. super();
  21475. /**
  21476. * The renderer's backend.
  21477. *
  21478. * @type {Backend}
  21479. */
  21480. this.backend = backend;
  21481. /**
  21482. * Renderer component for managing textures.
  21483. *
  21484. * @type {Textures}
  21485. */
  21486. this.textures = textures;
  21487. /**
  21488. * Renderer component for managing pipelines.
  21489. *
  21490. * @type {Pipelines}
  21491. */
  21492. this.pipelines = pipelines;
  21493. /**
  21494. * Renderer component for managing attributes.
  21495. *
  21496. * @type {Attributes}
  21497. */
  21498. this.attributes = attributes;
  21499. /**
  21500. * Renderer component for managing nodes related logic.
  21501. *
  21502. * @type {Nodes}
  21503. */
  21504. this.nodes = nodes;
  21505. /**
  21506. * Renderer component for managing metrics and monitoring data.
  21507. *
  21508. * @type {Info}
  21509. */
  21510. this.info = info;
  21511. this.pipelines.bindings = this; // assign bindings to pipelines
  21512. }
  21513. /**
  21514. * Returns the bind groups for the given render object.
  21515. *
  21516. * @param {RenderObject} renderObject - The render object.
  21517. * @return {Array<BindGroup>} The bind groups.
  21518. */
  21519. getForRender( renderObject ) {
  21520. const bindings = renderObject.getBindings();
  21521. for ( const bindGroup of bindings ) {
  21522. const groupData = this.get( bindGroup );
  21523. if ( groupData.bindGroup === undefined ) {
  21524. // each object defines an array of bindings (ubos, textures, samplers etc.)
  21525. this._init( bindGroup );
  21526. this.backend.createBindings( bindGroup, bindings, 0 );
  21527. groupData.bindGroup = bindGroup;
  21528. }
  21529. }
  21530. return bindings;
  21531. }
  21532. /**
  21533. * Returns the bind groups for the given compute node.
  21534. *
  21535. * @param {Node} computeNode - The compute node.
  21536. * @return {Array<BindGroup>} The bind groups.
  21537. */
  21538. getForCompute( computeNode ) {
  21539. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21540. for ( const bindGroup of bindings ) {
  21541. const groupData = this.get( bindGroup );
  21542. if ( groupData.bindGroup === undefined ) {
  21543. this._init( bindGroup );
  21544. this.backend.createBindings( bindGroup, bindings, 0 );
  21545. groupData.bindGroup = bindGroup;
  21546. }
  21547. }
  21548. return bindings;
  21549. }
  21550. /**
  21551. * Updates the bindings for the given compute node.
  21552. *
  21553. * @param {Node} computeNode - The compute node.
  21554. */
  21555. updateForCompute( computeNode ) {
  21556. this._updateBindings( this.getForCompute( computeNode ) );
  21557. }
  21558. /**
  21559. * Updates the bindings for the given render object.
  21560. *
  21561. * @param {RenderObject} renderObject - The render object.
  21562. */
  21563. updateForRender( renderObject ) {
  21564. this._updateBindings( this.getForRender( renderObject ) );
  21565. }
  21566. /**
  21567. * Deletes the bindings for the given compute node.
  21568. *
  21569. * @param {Node} computeNode - The compute node.
  21570. */
  21571. deleteForCompute( computeNode ) {
  21572. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21573. for ( const bindGroup of bindings ) {
  21574. this.delete( bindGroup );
  21575. }
  21576. }
  21577. /**
  21578. * Deletes the bindings for the given renderObject node.
  21579. *
  21580. * @param {RenderObject} renderObject - The renderObject.
  21581. */
  21582. deleteForRender( renderObject ) {
  21583. const bindings = renderObject.getBindings();
  21584. for ( const bindGroup of bindings ) {
  21585. this.delete( bindGroup );
  21586. }
  21587. }
  21588. /**
  21589. * Updates the given array of bindings.
  21590. *
  21591. * @param {Array<BindGroup>} bindings - The bind groups.
  21592. */
  21593. _updateBindings( bindings ) {
  21594. for ( const bindGroup of bindings ) {
  21595. this._update( bindGroup, bindings );
  21596. }
  21597. }
  21598. /**
  21599. * Initializes the given bind group.
  21600. *
  21601. * @param {BindGroup} bindGroup - The bind group to initialize.
  21602. */
  21603. _init( bindGroup ) {
  21604. for ( const binding of bindGroup.bindings ) {
  21605. if ( binding.isSampledTexture ) {
  21606. this.textures.updateTexture( binding.texture );
  21607. } else if ( binding.isSampler ) {
  21608. this.textures.updateSampler( binding.texture );
  21609. } else if ( binding.isStorageBuffer ) {
  21610. const attribute = binding.attribute;
  21611. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21612. this.attributes.update( attribute, attributeType );
  21613. }
  21614. }
  21615. }
  21616. /**
  21617. * Updates the given bind group.
  21618. *
  21619. * @param {BindGroup} bindGroup - The bind group to update.
  21620. * @param {Array<BindGroup>} bindings - The bind groups.
  21621. */
  21622. _update( bindGroup, bindings ) {
  21623. const { backend } = this;
  21624. let needsBindingsUpdate = false;
  21625. let cacheBindings = true;
  21626. let cacheIndex = 0;
  21627. let version = 0;
  21628. // iterate over all bindings and check if buffer updates or a new binding group is required
  21629. for ( const binding of bindGroup.bindings ) {
  21630. if ( binding.isNodeUniformsGroup ) {
  21631. const updated = this.nodes.updateGroup( binding );
  21632. // every uniforms group is a uniform buffer. So if no update is required,
  21633. // we move one with the next binding. Otherwise the next if block will update the group.
  21634. if ( updated === false ) continue;
  21635. }
  21636. if ( binding.isStorageBuffer ) {
  21637. const attribute = binding.attribute;
  21638. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21639. this.attributes.update( attribute, attributeType );
  21640. }
  21641. if ( binding.isUniformBuffer ) {
  21642. const updated = binding.update();
  21643. if ( updated ) {
  21644. backend.updateBinding( binding );
  21645. }
  21646. } else if ( binding.isSampledTexture ) {
  21647. const updated = binding.update();
  21648. // get the texture data after the update, to sync the texture reference from node
  21649. const texture = binding.texture;
  21650. const texturesTextureData = this.textures.get( texture );
  21651. if ( updated ) {
  21652. // version: update the texture data or create a new one
  21653. this.textures.updateTexture( texture );
  21654. // generation: update the bindings if a new texture has been created
  21655. if ( binding.generation !== texturesTextureData.generation ) {
  21656. binding.generation = texturesTextureData.generation;
  21657. needsBindingsUpdate = true;
  21658. cacheBindings = false;
  21659. }
  21660. }
  21661. const textureData = backend.get( texture );
  21662. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  21663. cacheBindings = false;
  21664. } else {
  21665. cacheIndex = cacheIndex * 10 + texture.id;
  21666. version += texture.version;
  21667. }
  21668. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  21669. const textureData = this.get( texture );
  21670. if ( binding.store === true ) {
  21671. textureData.needsMipmap = true;
  21672. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  21673. this.backend.generateMipmaps( texture );
  21674. textureData.needsMipmap = false;
  21675. }
  21676. }
  21677. } else if ( binding.isSampler ) {
  21678. const updated = binding.update();
  21679. if ( updated ) {
  21680. const samplerKey = this.textures.updateSampler( binding.texture );
  21681. if ( binding.samplerKey !== samplerKey ) {
  21682. binding.samplerKey = samplerKey;
  21683. needsBindingsUpdate = true;
  21684. cacheBindings = false;
  21685. }
  21686. }
  21687. }
  21688. }
  21689. if ( needsBindingsUpdate === true ) {
  21690. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  21691. }
  21692. }
  21693. }
  21694. /**
  21695. * Default sorting function for opaque render items.
  21696. *
  21697. * @private
  21698. * @function
  21699. * @param {Object} a - The first render item.
  21700. * @param {Object} b - The second render item.
  21701. * @return {number} A numeric value which defines the sort order.
  21702. */
  21703. function painterSortStable( a, b ) {
  21704. if ( a.groupOrder !== b.groupOrder ) {
  21705. return a.groupOrder - b.groupOrder;
  21706. } else if ( a.renderOrder !== b.renderOrder ) {
  21707. return a.renderOrder - b.renderOrder;
  21708. } else if ( a.z !== b.z ) {
  21709. return a.z - b.z;
  21710. } else {
  21711. return a.id - b.id;
  21712. }
  21713. }
  21714. /**
  21715. * Default sorting function for transparent render items.
  21716. *
  21717. * @private
  21718. * @function
  21719. * @param {Object} a - The first render item.
  21720. * @param {Object} b - The second render item.
  21721. * @return {number} A numeric value which defines the sort order.
  21722. */
  21723. function reversePainterSortStable( a, b ) {
  21724. if ( a.groupOrder !== b.groupOrder ) {
  21725. return a.groupOrder - b.groupOrder;
  21726. } else if ( a.renderOrder !== b.renderOrder ) {
  21727. return a.renderOrder - b.renderOrder;
  21728. } else if ( a.z !== b.z ) {
  21729. return b.z - a.z;
  21730. } else {
  21731. return a.id - b.id;
  21732. }
  21733. }
  21734. /**
  21735. * Returns `true` if the given transparent material requires a double pass.
  21736. *
  21737. * @private
  21738. * @function
  21739. * @param {Material} material - The transparent material.
  21740. * @return {boolean} Whether the given material requires a double pass or not.
  21741. */
  21742. function needsDoublePass( material ) {
  21743. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  21744. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  21745. }
  21746. /**
  21747. * When the renderer analyzes the scene at the beginning of a render call,
  21748. * it stores 3D object for further processing in render lists. Depending on the
  21749. * properties of a 3D objects (like their transformation or material state), the
  21750. * objects are maintained in ordered lists for the actual rendering.
  21751. *
  21752. * Render lists are unique per scene and camera combination.
  21753. *
  21754. * @private
  21755. * @augments Pipeline
  21756. */
  21757. class RenderList {
  21758. /**
  21759. * Constructs a render list.
  21760. *
  21761. * @param {Lighting} lighting - The lighting management component.
  21762. * @param {Scene} scene - The scene.
  21763. * @param {Camera} camera - The camera the scene is rendered with.
  21764. */
  21765. constructor( lighting, scene, camera ) {
  21766. /**
  21767. * 3D objects are transformed into render items and stored in this array.
  21768. *
  21769. * @type {Array<Object>}
  21770. */
  21771. this.renderItems = [];
  21772. /**
  21773. * The current render items index.
  21774. *
  21775. * @type {number}
  21776. * @default 0
  21777. */
  21778. this.renderItemsIndex = 0;
  21779. /**
  21780. * A list with opaque render items.
  21781. *
  21782. * @type {Array<Object>}
  21783. */
  21784. this.opaque = [];
  21785. /**
  21786. * A list with transparent render items which require
  21787. * double pass rendering (e.g. transmissive objects).
  21788. *
  21789. * @type {Array<Object>}
  21790. */
  21791. this.transparentDoublePass = [];
  21792. /**
  21793. * A list with transparent render items.
  21794. *
  21795. * @type {Array<Object>}
  21796. */
  21797. this.transparent = [];
  21798. /**
  21799. * A list with transparent render bundle data.
  21800. *
  21801. * @type {Array<Object>}
  21802. */
  21803. this.bundles = [];
  21804. /**
  21805. * The render list's lights node. This node is later
  21806. * relevant for the actual analytical light nodes which
  21807. * compute the scene's lighting in the shader.
  21808. *
  21809. * @type {LightsNode}
  21810. */
  21811. this.lightsNode = lighting.getNode( scene, camera );
  21812. /**
  21813. * The scene's lights stored in an array. This array
  21814. * is used to setup the lights node.
  21815. *
  21816. * @type {Array<Light>}
  21817. */
  21818. this.lightsArray = [];
  21819. /**
  21820. * The scene.
  21821. *
  21822. * @type {Scene}
  21823. */
  21824. this.scene = scene;
  21825. /**
  21826. * The camera the scene is rendered with.
  21827. *
  21828. * @type {Camera}
  21829. */
  21830. this.camera = camera;
  21831. /**
  21832. * How many objects perform occlusion query tests.
  21833. *
  21834. * @type {number}
  21835. * @default 0
  21836. */
  21837. this.occlusionQueryCount = 0;
  21838. }
  21839. /**
  21840. * This method is called right at the beginning of a render call
  21841. * before the scene is analyzed. It prepares the internal data
  21842. * structures for the upcoming render lists generation.
  21843. *
  21844. * @return {RenderList} A reference to this render list.
  21845. */
  21846. begin() {
  21847. this.renderItemsIndex = 0;
  21848. this.opaque.length = 0;
  21849. this.transparentDoublePass.length = 0;
  21850. this.transparent.length = 0;
  21851. this.bundles.length = 0;
  21852. this.lightsArray.length = 0;
  21853. this.occlusionQueryCount = 0;
  21854. return this;
  21855. }
  21856. /**
  21857. * Returns a render item for the giving render item state. The state is defined
  21858. * by a series of object-related parameters.
  21859. *
  21860. * The method avoids object creation by holding render items and reusing them in
  21861. * subsequent render calls (just with different property values).
  21862. *
  21863. * @param {Object3D} object - The 3D object.
  21864. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21865. * @param {Material} material - The 3D object's material.
  21866. * @param {number} groupOrder - The current group order.
  21867. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21868. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21869. * @param {ClippingContext} clippingContext - The current clipping context.
  21870. * @return {Object} The render item.
  21871. */
  21872. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21873. let renderItem = this.renderItems[ this.renderItemsIndex ];
  21874. if ( renderItem === undefined ) {
  21875. renderItem = {
  21876. id: object.id,
  21877. object: object,
  21878. geometry: geometry,
  21879. material: material,
  21880. groupOrder: groupOrder,
  21881. renderOrder: object.renderOrder,
  21882. z: z,
  21883. group: group,
  21884. clippingContext: clippingContext
  21885. };
  21886. this.renderItems[ this.renderItemsIndex ] = renderItem;
  21887. } else {
  21888. renderItem.id = object.id;
  21889. renderItem.object = object;
  21890. renderItem.geometry = geometry;
  21891. renderItem.material = material;
  21892. renderItem.groupOrder = groupOrder;
  21893. renderItem.renderOrder = object.renderOrder;
  21894. renderItem.z = z;
  21895. renderItem.group = group;
  21896. renderItem.clippingContext = clippingContext;
  21897. }
  21898. this.renderItemsIndex ++;
  21899. return renderItem;
  21900. }
  21901. /**
  21902. * Pushes the given object as a render item to the internal render lists.
  21903. * The selected lists depend on the object properties.
  21904. *
  21905. * @param {Object3D} object - The 3D object.
  21906. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21907. * @param {Material} material - The 3D object's material.
  21908. * @param {number} groupOrder - The current group order.
  21909. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21910. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21911. * @param {ClippingContext} clippingContext - The current clipping context.
  21912. */
  21913. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21914. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21915. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  21916. if ( material.transparent === true || material.transmission > 0 ) {
  21917. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  21918. this.transparent.push( renderItem );
  21919. } else {
  21920. this.opaque.push( renderItem );
  21921. }
  21922. }
  21923. /**
  21924. * Inserts the given object as a render item at the start of the internal render lists.
  21925. * The selected lists depend on the object properties.
  21926. *
  21927. * @param {Object3D} object - The 3D object.
  21928. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21929. * @param {Material} material - The 3D object's material.
  21930. * @param {number} groupOrder - The current group order.
  21931. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21932. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21933. * @param {ClippingContext} clippingContext - The current clipping context.
  21934. */
  21935. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21936. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21937. if ( material.transparent === true || material.transmission > 0 ) {
  21938. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  21939. this.transparent.unshift( renderItem );
  21940. } else {
  21941. this.opaque.unshift( renderItem );
  21942. }
  21943. }
  21944. /**
  21945. * Pushes render bundle group data into the render list.
  21946. *
  21947. * @param {Object} group - Bundle group data.
  21948. */
  21949. pushBundle( group ) {
  21950. this.bundles.push( group );
  21951. }
  21952. /**
  21953. * Pushes a light into the render list.
  21954. *
  21955. * @param {Light} light - The light.
  21956. */
  21957. pushLight( light ) {
  21958. this.lightsArray.push( light );
  21959. }
  21960. /**
  21961. * Sorts the internal render lists.
  21962. *
  21963. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  21964. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  21965. */
  21966. sort( customOpaqueSort, customTransparentSort ) {
  21967. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  21968. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  21969. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  21970. }
  21971. /**
  21972. * This method performs finalizing tasks right after the render lists
  21973. * have been generated.
  21974. */
  21975. finish() {
  21976. // update lights
  21977. this.lightsNode.setLights( this.lightsArray );
  21978. // Clear references from inactive renderItems in the list
  21979. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  21980. const renderItem = this.renderItems[ i ];
  21981. if ( renderItem.id === null ) break;
  21982. renderItem.id = null;
  21983. renderItem.object = null;
  21984. renderItem.geometry = null;
  21985. renderItem.material = null;
  21986. renderItem.groupOrder = null;
  21987. renderItem.renderOrder = null;
  21988. renderItem.z = null;
  21989. renderItem.group = null;
  21990. renderItem.clippingContext = null;
  21991. }
  21992. }
  21993. }
  21994. const _chainKeys$4 = [];
  21995. /**
  21996. * This renderer module manages the render lists which are unique
  21997. * per scene and camera combination.
  21998. *
  21999. * @private
  22000. */
  22001. class RenderLists {
  22002. /**
  22003. * Constructs a render lists management component.
  22004. *
  22005. * @param {Lighting} lighting - The lighting management component.
  22006. */
  22007. constructor( lighting ) {
  22008. /**
  22009. * The lighting management component.
  22010. *
  22011. * @type {Lighting}
  22012. */
  22013. this.lighting = lighting;
  22014. /**
  22015. * The internal chain map which holds the render lists.
  22016. *
  22017. * @type {ChainMap}
  22018. */
  22019. this.lists = new ChainMap();
  22020. }
  22021. /**
  22022. * Returns a render list for the given scene and camera.
  22023. *
  22024. * @param {Scene} scene - The scene.
  22025. * @param {Camera} camera - The camera.
  22026. * @return {RenderList} The render list.
  22027. */
  22028. get( scene, camera ) {
  22029. const lists = this.lists;
  22030. _chainKeys$4[ 0 ] = scene;
  22031. _chainKeys$4[ 1 ] = camera;
  22032. let list = lists.get( _chainKeys$4 );
  22033. if ( list === undefined ) {
  22034. list = new RenderList( this.lighting, scene, camera );
  22035. lists.set( _chainKeys$4, list );
  22036. }
  22037. _chainKeys$4.length = 0;
  22038. return list;
  22039. }
  22040. /**
  22041. * Frees all internal resources.
  22042. */
  22043. dispose() {
  22044. this.lists = new ChainMap();
  22045. }
  22046. }
  22047. let _id$7 = 0;
  22048. /**
  22049. * Any render or compute command is executed in a specific context that defines
  22050. * the state of the renderer and its backend. Typical examples for such context
  22051. * data are the current clear values or data from the active framebuffer. This
  22052. * module is used to represent these contexts as objects.
  22053. *
  22054. * @private
  22055. */
  22056. class RenderContext {
  22057. /**
  22058. * Constructs a new render context.
  22059. */
  22060. constructor() {
  22061. /**
  22062. * The context's ID.
  22063. *
  22064. * @type {number}
  22065. */
  22066. this.id = _id$7 ++;
  22067. /**
  22068. * Whether the current active framebuffer has a color attachment.
  22069. *
  22070. * @type {boolean}
  22071. * @default true
  22072. */
  22073. this.color = true;
  22074. /**
  22075. * Whether the color attachment should be cleared or not.
  22076. *
  22077. * @type {boolean}
  22078. * @default true
  22079. */
  22080. this.clearColor = true;
  22081. /**
  22082. * The clear color value.
  22083. *
  22084. * @type {Object}
  22085. * @default true
  22086. */
  22087. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  22088. /**
  22089. * Whether the current active framebuffer has a depth attachment.
  22090. *
  22091. * @type {boolean}
  22092. * @default true
  22093. */
  22094. this.depth = true;
  22095. /**
  22096. * Whether the depth attachment should be cleared or not.
  22097. *
  22098. * @type {boolean}
  22099. * @default true
  22100. */
  22101. this.clearDepth = true;
  22102. /**
  22103. * The clear depth value.
  22104. *
  22105. * @type {number}
  22106. * @default 1
  22107. */
  22108. this.clearDepthValue = 1;
  22109. /**
  22110. * Whether the current active framebuffer has a stencil attachment.
  22111. *
  22112. * @type {boolean}
  22113. * @default false
  22114. */
  22115. this.stencil = false;
  22116. /**
  22117. * Whether the stencil attachment should be cleared or not.
  22118. *
  22119. * @type {boolean}
  22120. * @default true
  22121. */
  22122. this.clearStencil = true;
  22123. /**
  22124. * The clear stencil value.
  22125. *
  22126. * @type {number}
  22127. * @default 1
  22128. */
  22129. this.clearStencilValue = 1;
  22130. /**
  22131. * By default the viewport encloses the entire framebuffer If a smaller
  22132. * viewport is manually defined, this property is to `true` by the renderer.
  22133. *
  22134. * @type {boolean}
  22135. * @default false
  22136. */
  22137. this.viewport = false;
  22138. /**
  22139. * The viewport value. This value is in physical pixels meaning it incorporates
  22140. * the renderer's pixel ratio. The viewport property of render targets or
  22141. * the renderer is in logical pixels.
  22142. *
  22143. * @type {Vector4}
  22144. */
  22145. this.viewportValue = new Vector4();
  22146. /**
  22147. * When the scissor test is active and scissor rectangle smaller than the
  22148. * framebuffers dimensions, this property is to `true` by the renderer.
  22149. *
  22150. * @type {boolean}
  22151. * @default false
  22152. */
  22153. this.scissor = false;
  22154. /**
  22155. * The scissor rectangle.
  22156. *
  22157. * @type {Vector4}
  22158. */
  22159. this.scissorValue = new Vector4();
  22160. /**
  22161. * The active render target.
  22162. *
  22163. * @type {?RenderTarget}
  22164. * @default null
  22165. */
  22166. this.renderTarget = null;
  22167. /**
  22168. * The textures of the active render target.
  22169. * `null` when no render target is set.
  22170. *
  22171. * @type {?Array<Texture>}
  22172. * @default null
  22173. */
  22174. this.textures = null;
  22175. /**
  22176. * The depth texture of the active render target.
  22177. * `null` when no render target is set.
  22178. *
  22179. * @type {?DepthTexture}
  22180. * @default null
  22181. */
  22182. this.depthTexture = null;
  22183. /**
  22184. * The active cube face.
  22185. *
  22186. * @type {number}
  22187. * @default 0
  22188. */
  22189. this.activeCubeFace = 0;
  22190. /**
  22191. * The active mipmap level.
  22192. *
  22193. * @type {number}
  22194. * @default 0
  22195. */
  22196. this.activeMipmapLevel = 0;
  22197. /**
  22198. * The number of MSAA samples. This value is always `1` when
  22199. * MSAA isn't used.
  22200. *
  22201. * @type {number}
  22202. * @default 1
  22203. */
  22204. this.sampleCount = 1;
  22205. /**
  22206. * The active render target's width in physical pixels.
  22207. *
  22208. * @type {number}
  22209. * @default 0
  22210. */
  22211. this.width = 0;
  22212. /**
  22213. * The active render target's height in physical pixels.
  22214. *
  22215. * @type {number}
  22216. * @default 0
  22217. */
  22218. this.height = 0;
  22219. /**
  22220. * The occlusion query count.
  22221. *
  22222. * @type {number}
  22223. * @default 0
  22224. */
  22225. this.occlusionQueryCount = 0;
  22226. /**
  22227. * The current clipping context.
  22228. *
  22229. * @type {?ClippingContext}
  22230. * @default null
  22231. */
  22232. this.clippingContext = null;
  22233. /**
  22234. * This flag can be used for type testing.
  22235. *
  22236. * @type {boolean}
  22237. * @readonly
  22238. * @default true
  22239. */
  22240. this.isRenderContext = true;
  22241. }
  22242. /**
  22243. * Returns the cache key of this render context.
  22244. *
  22245. * @return {number} The cache key.
  22246. */
  22247. getCacheKey() {
  22248. return getCacheKey( this );
  22249. }
  22250. }
  22251. /**
  22252. * Computes a cache key for the given render context. This key
  22253. * should identify the render target state so it is possible to
  22254. * configure the correct attachments in the respective backend.
  22255. *
  22256. * @param {RenderContext} renderContext - The render context.
  22257. * @return {number} The cache key.
  22258. */
  22259. function getCacheKey( renderContext ) {
  22260. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  22261. const values = [ activeCubeFace, activeMipmapLevel ];
  22262. for ( const texture of textures ) {
  22263. values.push( texture.id );
  22264. }
  22265. return hashArray( values );
  22266. }
  22267. const _chainKeys$3 = [];
  22268. const _defaultScene = /*@__PURE__*/ new Scene();
  22269. const _defaultCamera = /*@__PURE__*/ new Camera();
  22270. /**
  22271. * This module manages the render contexts of the renderer.
  22272. *
  22273. * @private
  22274. */
  22275. class RenderContexts {
  22276. /**
  22277. * Constructs a new render context management component.
  22278. */
  22279. constructor() {
  22280. /**
  22281. * A dictionary that manages render contexts in chain maps
  22282. * for each attachment state.
  22283. *
  22284. * @type {Object<string,ChainMap>}
  22285. */
  22286. this.chainMaps = {};
  22287. }
  22288. /**
  22289. * Returns a render context for the given scene, camera and render target.
  22290. *
  22291. * @param {Scene} scene - The scene.
  22292. * @param {Camera} camera - The camera that is used to render the scene.
  22293. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22294. * @return {RenderContext} The render context.
  22295. */
  22296. get( scene, camera, renderTarget = null ) {
  22297. _chainKeys$3[ 0 ] = scene;
  22298. _chainKeys$3[ 1 ] = camera;
  22299. let attachmentState;
  22300. if ( renderTarget === null ) {
  22301. attachmentState = 'default';
  22302. } else {
  22303. const format = renderTarget.texture.format;
  22304. const count = renderTarget.textures.length;
  22305. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  22306. }
  22307. const chainMap = this._getChainMap( attachmentState );
  22308. let renderState = chainMap.get( _chainKeys$3 );
  22309. if ( renderState === undefined ) {
  22310. renderState = new RenderContext();
  22311. chainMap.set( _chainKeys$3, renderState );
  22312. }
  22313. _chainKeys$3.length = 0;
  22314. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22315. return renderState;
  22316. }
  22317. /**
  22318. * Returns a render context intended for clear operations.
  22319. *
  22320. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22321. * @return {RenderContext} The render context.
  22322. */
  22323. getForClear( renderTarget = null ) {
  22324. return this.get( _defaultScene, _defaultCamera, renderTarget );
  22325. }
  22326. /**
  22327. * Returns a chain map for the given attachment state.
  22328. *
  22329. * @private
  22330. * @param {string} attachmentState - The attachment state.
  22331. * @return {ChainMap} The chain map.
  22332. */
  22333. _getChainMap( attachmentState ) {
  22334. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  22335. }
  22336. /**
  22337. * Frees internal resources.
  22338. */
  22339. dispose() {
  22340. this.chainMaps = {};
  22341. }
  22342. }
  22343. const _size$3 = /*@__PURE__*/ new Vector3();
  22344. /**
  22345. * This module manages the textures of the renderer.
  22346. *
  22347. * @private
  22348. * @augments DataMap
  22349. */
  22350. class Textures extends DataMap {
  22351. /**
  22352. * Constructs a new texture management component.
  22353. *
  22354. * @param {Renderer} renderer - The renderer.
  22355. * @param {Backend} backend - The renderer's backend.
  22356. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22357. */
  22358. constructor( renderer, backend, info ) {
  22359. super();
  22360. /**
  22361. * The renderer.
  22362. *
  22363. * @type {Renderer}
  22364. */
  22365. this.renderer = renderer;
  22366. /**
  22367. * The backend.
  22368. *
  22369. * @type {Backend}
  22370. */
  22371. this.backend = backend;
  22372. /**
  22373. * Renderer component for managing metrics and monitoring data.
  22374. *
  22375. * @type {Info}
  22376. */
  22377. this.info = info;
  22378. }
  22379. /**
  22380. * Updates the given render target. Based on the given render target configuration,
  22381. * it updates the texture states representing the attachments of the framebuffer.
  22382. *
  22383. * @param {RenderTarget} renderTarget - The render target to update.
  22384. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  22385. */
  22386. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  22387. const renderTargetData = this.get( renderTarget );
  22388. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22389. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  22390. const textures = renderTarget.textures;
  22391. const size = this.getSize( textures[ 0 ] );
  22392. const mipWidth = size.width >> activeMipmapLevel;
  22393. const mipHeight = size.height >> activeMipmapLevel;
  22394. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  22395. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  22396. let textureNeedsUpdate = false;
  22397. if ( depthTexture === undefined && useDepthTexture ) {
  22398. depthTexture = new DepthTexture();
  22399. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  22400. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  22401. depthTexture.image.width = mipWidth;
  22402. depthTexture.image.height = mipHeight;
  22403. depthTexture.image.depth = size.depth;
  22404. depthTexture.renderTarget = renderTarget;
  22405. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  22406. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  22407. }
  22408. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  22409. textureNeedsUpdate = true;
  22410. if ( depthTexture ) {
  22411. depthTexture.needsUpdate = true;
  22412. depthTexture.image.width = mipWidth;
  22413. depthTexture.image.height = mipHeight;
  22414. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  22415. }
  22416. }
  22417. renderTargetData.width = size.width;
  22418. renderTargetData.height = size.height;
  22419. renderTargetData.textures = textures;
  22420. renderTargetData.depthTexture = depthTexture || null;
  22421. renderTargetData.depth = renderTarget.depthBuffer;
  22422. renderTargetData.stencil = renderTarget.stencilBuffer;
  22423. renderTargetData.renderTarget = renderTarget;
  22424. if ( renderTargetData.sampleCount !== sampleCount ) {
  22425. textureNeedsUpdate = true;
  22426. if ( depthTexture ) {
  22427. depthTexture.needsUpdate = true;
  22428. }
  22429. renderTargetData.sampleCount = sampleCount;
  22430. }
  22431. //
  22432. const options = { sampleCount };
  22433. // XR render targets require no texture updates
  22434. if ( renderTarget.isXRRenderTarget !== true ) {
  22435. for ( let i = 0; i < textures.length; i ++ ) {
  22436. const texture = textures[ i ];
  22437. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  22438. this.updateTexture( texture, options );
  22439. }
  22440. if ( depthTexture ) {
  22441. this.updateTexture( depthTexture, options );
  22442. }
  22443. }
  22444. // dispose handler
  22445. if ( renderTargetData.initialized !== true ) {
  22446. renderTargetData.initialized = true;
  22447. // dispose
  22448. const onDispose = () => {
  22449. renderTarget.removeEventListener( 'dispose', onDispose );
  22450. for ( let i = 0; i < textures.length; i ++ ) {
  22451. this._destroyTexture( textures[ i ] );
  22452. }
  22453. if ( depthTexture ) {
  22454. this._destroyTexture( depthTexture );
  22455. }
  22456. this.delete( renderTarget );
  22457. this.backend.delete( renderTarget );
  22458. };
  22459. renderTarget.addEventListener( 'dispose', onDispose );
  22460. }
  22461. }
  22462. /**
  22463. * Updates the given texture. Depending on the texture state, this method
  22464. * triggers the upload of texture data to the GPU memory. If the texture data are
  22465. * not yet ready for the upload, it uses default texture data for as a placeholder.
  22466. *
  22467. * @param {Texture} texture - The texture to update.
  22468. * @param {Object} [options={}] - The options.
  22469. */
  22470. updateTexture( texture, options = {} ) {
  22471. const textureData = this.get( texture );
  22472. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  22473. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  22474. const backend = this.backend;
  22475. if ( isRenderTarget && textureData.initialized === true ) {
  22476. // it's an update
  22477. backend.destroyTexture( texture );
  22478. }
  22479. //
  22480. if ( texture.isFramebufferTexture ) {
  22481. const renderTarget = this.renderer.getRenderTarget();
  22482. if ( renderTarget ) {
  22483. texture.type = renderTarget.texture.type;
  22484. } else {
  22485. texture.type = UnsignedByteType;
  22486. }
  22487. }
  22488. //
  22489. const { width, height, depth } = this.getSize( texture );
  22490. options.width = width;
  22491. options.height = height;
  22492. options.depth = depth;
  22493. options.needsMipmaps = this.needsMipmaps( texture );
  22494. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  22495. // TODO: Uniformly handle mipmap definitions
  22496. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  22497. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  22498. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  22499. //
  22500. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  22501. backend.createTexture( texture, options );
  22502. textureData.generation = texture.version;
  22503. } else {
  22504. if ( texture.version > 0 ) {
  22505. const image = texture.image;
  22506. if ( image === undefined ) {
  22507. warn( 'Renderer: Texture marked for update but image is undefined.' );
  22508. } else if ( image.complete === false ) {
  22509. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  22510. } else {
  22511. if ( texture.images ) {
  22512. const images = [];
  22513. for ( const image of texture.images ) {
  22514. images.push( image );
  22515. }
  22516. options.images = images;
  22517. } else {
  22518. options.image = image;
  22519. }
  22520. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  22521. backend.createTexture( texture, options );
  22522. textureData.isDefaultTexture = false;
  22523. textureData.generation = texture.version;
  22524. }
  22525. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  22526. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  22527. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  22528. backend.generateMipmaps( texture );
  22529. }
  22530. if ( texture.onUpdate ) texture.onUpdate( texture );
  22531. }
  22532. } else {
  22533. // async update
  22534. backend.createDefaultTexture( texture );
  22535. textureData.isDefaultTexture = true;
  22536. textureData.generation = texture.version;
  22537. }
  22538. }
  22539. // dispose handler
  22540. if ( textureData.initialized !== true ) {
  22541. textureData.initialized = true;
  22542. textureData.generation = texture.version;
  22543. //
  22544. this.info.memory.textures ++;
  22545. //
  22546. if ( texture.isVideoTexture && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  22547. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  22548. }
  22549. // dispose
  22550. const onDispose = () => {
  22551. texture.removeEventListener( 'dispose', onDispose );
  22552. this._destroyTexture( texture );
  22553. };
  22554. texture.addEventListener( 'dispose', onDispose );
  22555. }
  22556. //
  22557. textureData.version = texture.version;
  22558. }
  22559. /**
  22560. * Updates the sampler for the given texture. This method has no effect
  22561. * for the WebGL backend since it has no concept of samplers. Texture
  22562. * parameters are configured with the `texParameter()` command for each
  22563. * texture.
  22564. *
  22565. * In WebGPU, samplers are objects like textures and it's possible to share
  22566. * them when the texture parameters match.
  22567. *
  22568. * @param {Texture} texture - The texture to update the sampler for.
  22569. * @return {string} The current sampler key.
  22570. */
  22571. updateSampler( texture ) {
  22572. return this.backend.updateSampler( texture );
  22573. }
  22574. /**
  22575. * Computes the size of the given texture and writes the result
  22576. * into the target vector. This vector is also returned by the
  22577. * method.
  22578. *
  22579. * If no texture data are available for the compute yet, the method
  22580. * returns default size values.
  22581. *
  22582. * @param {Texture} texture - The texture to compute the size for.
  22583. * @param {Vector3} target - The target vector.
  22584. * @return {Vector3} The target vector.
  22585. */
  22586. getSize( texture, target = _size$3 ) {
  22587. let image = texture.images ? texture.images[ 0 ] : texture.image;
  22588. if ( image ) {
  22589. if ( image.image !== undefined ) image = image.image;
  22590. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  22591. target.width = image.videoWidth || 1;
  22592. target.height = image.videoHeight || 1;
  22593. target.depth = 1;
  22594. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  22595. target.width = image.displayWidth || 1;
  22596. target.height = image.displayHeight || 1;
  22597. target.depth = 1;
  22598. } else {
  22599. target.width = image.width || 1;
  22600. target.height = image.height || 1;
  22601. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  22602. }
  22603. } else {
  22604. target.width = target.height = target.depth = 1;
  22605. }
  22606. return target;
  22607. }
  22608. /**
  22609. * Computes the number of mipmap levels for the given texture.
  22610. *
  22611. * @param {Texture} texture - The texture.
  22612. * @param {number} width - The texture's width.
  22613. * @param {number} height - The texture's height.
  22614. * @return {number} The number of mipmap levels.
  22615. */
  22616. getMipLevels( texture, width, height ) {
  22617. let mipLevelCount;
  22618. if ( texture.mipmaps.length > 0 ) {
  22619. mipLevelCount = texture.mipmaps.length;
  22620. } else {
  22621. if ( texture.isCompressedTexture === true ) {
  22622. // it is not possible to compute mipmaps for compressed textures. So
  22623. // when no mipmaps are defined in "texture.mipmaps", force a texture
  22624. // level of 1
  22625. mipLevelCount = 1;
  22626. } else {
  22627. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  22628. }
  22629. }
  22630. return mipLevelCount;
  22631. }
  22632. /**
  22633. * Returns `true` if the given texture makes use of mipmapping.
  22634. *
  22635. * @param {Texture} texture - The texture.
  22636. * @return {boolean} Whether mipmaps are required or not.
  22637. */
  22638. needsMipmaps( texture ) {
  22639. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  22640. }
  22641. /**
  22642. * Frees internal resource when the given texture isn't
  22643. * required anymore.
  22644. *
  22645. * @param {Texture} texture - The texture to destroy.
  22646. */
  22647. _destroyTexture( texture ) {
  22648. if ( this.has( texture ) === true ) {
  22649. // if a texture is not ready for use, it falls back to a default texture so it's possible
  22650. // to use it for rendering. If a texture in this state is disposed, it's important to
  22651. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  22652. // other textures.
  22653. const isDefaultTexture = this.get( texture ).isDefaultTexture;
  22654. this.backend.destroyTexture( texture, isDefaultTexture );
  22655. this.delete( texture );
  22656. this.info.memory.textures --;
  22657. }
  22658. }
  22659. }
  22660. /**
  22661. * A four-component version of {@link Color} which is internally
  22662. * used by the renderer to represents clear color with alpha as
  22663. * one object.
  22664. *
  22665. * @private
  22666. * @augments Color
  22667. */
  22668. class Color4 extends Color {
  22669. /**
  22670. * Constructs a new four-component color.
  22671. * You can also pass a single THREE.Color, hex or
  22672. * string argument to this constructor.
  22673. *
  22674. * @param {number|string} [r=1] - The red value.
  22675. * @param {number} [g=1] - The green value.
  22676. * @param {number} [b=1] - The blue value.
  22677. * @param {number} [a=1] - The alpha value.
  22678. */
  22679. constructor( r, g, b, a = 1 ) {
  22680. super( r, g, b );
  22681. this.a = a;
  22682. }
  22683. /**
  22684. * Overwrites the default to honor alpha.
  22685. * You can also pass a single THREE.Color, hex or
  22686. * string argument to this method.
  22687. *
  22688. * @param {number|string|Color} r - The red value.
  22689. * @param {number} [g] - The green value.
  22690. * @param {number} [b] - The blue value.
  22691. * @param {number} [a=1] - The alpha value.
  22692. * @return {Color4} A reference to this object.
  22693. */
  22694. set( r, g, b, a = 1 ) {
  22695. this.a = a;
  22696. return super.set( r, g, b );
  22697. }
  22698. /**
  22699. * Overwrites the default to honor alpha.
  22700. *
  22701. * @param {Color4} color - The color to copy.
  22702. * @return {Color4} A reference to this object.
  22703. */
  22704. copy( color ) {
  22705. if ( color.a !== undefined ) this.a = color.a;
  22706. return super.copy( color );
  22707. }
  22708. /**
  22709. * Overwrites the default to honor alpha.
  22710. *
  22711. * @return {Color4} The cloned color.
  22712. */
  22713. clone() {
  22714. return new this.constructor( this.r, this.g, this.b, this.a );
  22715. }
  22716. }
  22717. /**
  22718. * Special version of {@link PropertyNode} which is used for parameters.
  22719. *
  22720. * @augments PropertyNode
  22721. */
  22722. class ParameterNode extends PropertyNode {
  22723. static get type() {
  22724. return 'ParameterNode';
  22725. }
  22726. /**
  22727. * Constructs a new parameter node.
  22728. *
  22729. * @param {string} nodeType - The type of the node.
  22730. * @param {?string} [name=null] - The name of the parameter in the shader.
  22731. */
  22732. constructor( nodeType, name = null ) {
  22733. super( nodeType, name );
  22734. /**
  22735. * This flag can be used for type testing.
  22736. *
  22737. * @type {boolean}
  22738. * @readonly
  22739. * @default true
  22740. */
  22741. this.isParameterNode = true;
  22742. }
  22743. /**
  22744. * Gets the type of a member variable in the parameter node.
  22745. *
  22746. * @param {NodeBuilder} builder - The node builder.
  22747. * @param {string} name - The name of the member variable.
  22748. * @returns {string}
  22749. */
  22750. getMemberType( builder, name ) {
  22751. const type = this.getNodeType( builder );
  22752. const struct = builder.getStructTypeNode( type );
  22753. let memberType;
  22754. if ( struct !== null ) {
  22755. memberType = struct.getMemberType( builder, name );
  22756. } else {
  22757. error( `TSL: Member "${ name }" not found in struct "${ type }".` );
  22758. memberType = 'float';
  22759. }
  22760. return memberType;
  22761. }
  22762. getHash() {
  22763. return this.uuid;
  22764. }
  22765. generate() {
  22766. return this.name;
  22767. }
  22768. }
  22769. /**
  22770. * TSL function for creating a parameter node.
  22771. *
  22772. * @tsl
  22773. * @function
  22774. * @param {string} type - The type of the node.
  22775. * @param {?string} name - The name of the parameter in the shader.
  22776. * @returns {ParameterNode}
  22777. */
  22778. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  22779. /**
  22780. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  22781. * They are usually needed in cases like `If`, `Else`.
  22782. *
  22783. * @augments Node
  22784. */
  22785. class StackNode extends Node {
  22786. static get type() {
  22787. return 'StackNode';
  22788. }
  22789. /**
  22790. * Constructs a new stack node.
  22791. *
  22792. * @param {?StackNode} [parent=null] - The parent stack node.
  22793. */
  22794. constructor( parent = null ) {
  22795. super();
  22796. /**
  22797. * List of nodes.
  22798. *
  22799. * @type {Array<Node>}
  22800. */
  22801. this.nodes = [];
  22802. /**
  22803. * The output node.
  22804. *
  22805. * @type {?Node}
  22806. * @default null
  22807. */
  22808. this.outputNode = null;
  22809. /**
  22810. * The parent stack node.
  22811. *
  22812. * @type {?StackNode}
  22813. * @default null
  22814. */
  22815. this.parent = parent;
  22816. /**
  22817. * The current conditional node.
  22818. *
  22819. * @private
  22820. * @type {ConditionalNode}
  22821. * @default null
  22822. */
  22823. this._currentCond = null;
  22824. /**
  22825. * The expression node. Only
  22826. * relevant for Switch/Case.
  22827. *
  22828. * @private
  22829. * @type {Node}
  22830. * @default null
  22831. */
  22832. this._expressionNode = null;
  22833. /**
  22834. * This flag can be used for type testing.
  22835. *
  22836. * @type {boolean}
  22837. * @readonly
  22838. * @default true
  22839. */
  22840. this.isStackNode = true;
  22841. }
  22842. getNodeType( builder ) {
  22843. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  22844. }
  22845. getMemberType( builder, name ) {
  22846. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  22847. }
  22848. /**
  22849. * Adds a node to this stack.
  22850. *
  22851. * @param {Node} node - The node to add.
  22852. * @return {StackNode} A reference to this stack node.
  22853. */
  22854. add( node ) {
  22855. if ( node.isNode !== true ) {
  22856. error( 'TSL: Invalid node added to stack.' );
  22857. return this;
  22858. }
  22859. this.nodes.push( node );
  22860. return this;
  22861. }
  22862. /**
  22863. * Represent an `if` statement in TSL.
  22864. *
  22865. * @param {Node} boolNode - Represents the condition.
  22866. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22867. * @return {StackNode} A reference to this stack node.
  22868. */
  22869. If( boolNode, method ) {
  22870. const methodNode = new ShaderNode( method );
  22871. this._currentCond = select( boolNode, methodNode );
  22872. return this.add( this._currentCond );
  22873. }
  22874. /**
  22875. * Represent an `elseif` statement in TSL.
  22876. *
  22877. * @param {Node} boolNode - Represents the condition.
  22878. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22879. * @return {StackNode} A reference to this stack node.
  22880. */
  22881. ElseIf( boolNode, method ) {
  22882. const methodNode = new ShaderNode( method );
  22883. const ifNode = select( boolNode, methodNode );
  22884. this._currentCond.elseNode = ifNode;
  22885. this._currentCond = ifNode;
  22886. return this;
  22887. }
  22888. /**
  22889. * Represent an `else` statement in TSL.
  22890. *
  22891. * @param {Function} method - TSL code which is executed in the `else` case.
  22892. * @return {StackNode} A reference to this stack node.
  22893. */
  22894. Else( method ) {
  22895. this._currentCond.elseNode = new ShaderNode( method );
  22896. return this;
  22897. }
  22898. /**
  22899. * Represents a `switch` statement in TSL.
  22900. *
  22901. * @param {any} expression - Represents the expression.
  22902. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22903. * @return {StackNode} A reference to this stack node.
  22904. */
  22905. Switch( expression ) {
  22906. this._expressionNode = nodeObject( expression );
  22907. return this;
  22908. }
  22909. /**
  22910. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  22911. * The last parameter must be the callback method that should be executed in the `true` case.
  22912. *
  22913. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  22914. * @return {StackNode} A reference to this stack node.
  22915. */
  22916. Case( ...params ) {
  22917. const caseNodes = [];
  22918. // extract case nodes from the parameter list
  22919. if ( params.length >= 2 ) {
  22920. for ( let i = 0; i < params.length - 1; i ++ ) {
  22921. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  22922. }
  22923. } else {
  22924. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  22925. }
  22926. // extract method
  22927. const method = params[ params.length - 1 ];
  22928. const methodNode = new ShaderNode( method );
  22929. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  22930. let caseNode = caseNodes[ 0 ];
  22931. for ( let i = 1; i < caseNodes.length; i ++ ) {
  22932. caseNode = caseNode.or( caseNodes[ i ] );
  22933. }
  22934. // build condition
  22935. const condNode = select( caseNode, methodNode );
  22936. if ( this._currentCond === null ) {
  22937. this._currentCond = condNode;
  22938. return this.add( this._currentCond );
  22939. } else {
  22940. this._currentCond.elseNode = condNode;
  22941. this._currentCond = condNode;
  22942. return this;
  22943. }
  22944. }
  22945. /**
  22946. * Represents the default code block of a Switch/Case statement.
  22947. *
  22948. * @param {Function} method - TSL code which is executed in the `else` case.
  22949. * @return {StackNode} A reference to this stack node.
  22950. */
  22951. Default( method ) {
  22952. this.Else( method );
  22953. return this;
  22954. }
  22955. setup( builder ) {
  22956. const nodeProperties = builder.getNodeProperties( this );
  22957. let index = 0;
  22958. for ( const childNode of this.getChildren() ) {
  22959. if ( childNode.isVarNode && childNode.intent === true ) {
  22960. if ( childNode.isAssign( builder ) !== true ) {
  22961. continue;
  22962. }
  22963. }
  22964. nodeProperties[ 'node' + index ++ ] = childNode;
  22965. }
  22966. // return a outputNode if exists or null
  22967. return nodeProperties.outputNode || null;
  22968. }
  22969. get hasOutput() {
  22970. return this.outputNode && this.outputNode.isNode;
  22971. }
  22972. build( builder, ...params ) {
  22973. const previousBuildStack = builder.currentStack;
  22974. const previousStack = getCurrentStack();
  22975. setCurrentStack( this );
  22976. builder.currentStack = this;
  22977. const buildStage = builder.buildStage;
  22978. for ( const node of this.nodes ) {
  22979. if ( node.isVarNode && node.intent === true ) {
  22980. if ( node.isAssign( builder ) !== true ) {
  22981. continue;
  22982. }
  22983. }
  22984. if ( buildStage === 'setup' ) {
  22985. node.build( builder );
  22986. } else if ( buildStage === 'analyze' ) {
  22987. node.build( builder, this );
  22988. } else if ( buildStage === 'generate' ) {
  22989. const stages = builder.getDataFromNode( node, 'any' ).stages;
  22990. const parents = stages && stages[ builder.shaderStage ];
  22991. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  22992. continue; // skip var nodes that are only used in .toVarying()
  22993. }
  22994. node.build( builder, 'void' );
  22995. }
  22996. }
  22997. //
  22998. let result;
  22999. if ( this.hasOutput ) {
  23000. result = this.outputNode.build( builder, ...params );
  23001. } else {
  23002. result = super.build( builder, ...params );
  23003. }
  23004. setCurrentStack( previousStack );
  23005. builder.currentStack = previousBuildStack;
  23006. return result;
  23007. }
  23008. }
  23009. /**
  23010. * TSL function for creating a stack node.
  23011. *
  23012. * @tsl
  23013. * @function
  23014. * @param {?StackNode} [parent=null] - The parent stack node.
  23015. * @returns {StackNode}
  23016. */
  23017. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  23018. /**
  23019. * Generates a layout for struct members.
  23020. * This function takes an object representing struct members and returns an array of member layouts.
  23021. * Each member layout includes the member's name, type, and whether it is atomic.
  23022. *
  23023. * @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.
  23024. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  23025. */
  23026. function getMembersLayout( members ) {
  23027. return Object.entries( members ).map( ( [ name, value ] ) => {
  23028. if ( typeof value === 'string' ) {
  23029. return { name, type: value, atomic: false };
  23030. }
  23031. return { name, type: value.type, atomic: value.atomic || false };
  23032. } );
  23033. }
  23034. /**
  23035. * Represents a struct type node in the node-based system.
  23036. * This class is used to define and manage the layout and types of struct members.
  23037. * It extends the base Node class and provides methods to get the length of the struct,
  23038. * retrieve member types, and generate the struct type for a builder.
  23039. *
  23040. * @augments Node
  23041. */
  23042. class StructTypeNode extends Node {
  23043. static get type() {
  23044. return 'StructTypeNode';
  23045. }
  23046. /**
  23047. * Creates an instance of StructTypeNode.
  23048. *
  23049. * @param {Object} membersLayout - The layout of the members for the struct.
  23050. * @param {?string} [name=null] - The optional name of the struct.
  23051. */
  23052. constructor( membersLayout, name = null ) {
  23053. super( 'struct' );
  23054. /**
  23055. * The layout of the members for the struct
  23056. *
  23057. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  23058. */
  23059. this.membersLayout = getMembersLayout( membersLayout );
  23060. /**
  23061. * The name of the struct.
  23062. *
  23063. * @type {?string}
  23064. * @default null
  23065. */
  23066. this.name = name;
  23067. /**
  23068. * This flag can be used for type testing.
  23069. *
  23070. * @type {boolean}
  23071. * @readonly
  23072. * @default true
  23073. */
  23074. this.isStructLayoutNode = true;
  23075. }
  23076. /**
  23077. * Returns the length of the struct.
  23078. * The length is calculated by summing the lengths of the struct's members.
  23079. *
  23080. * @returns {number} The length of the struct.
  23081. */
  23082. getLength() {
  23083. const GPU_CHUNK_BYTES = 8;
  23084. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  23085. let offset = 0; // global buffer offset in bytes
  23086. for ( const member of this.membersLayout ) {
  23087. const type = member.type;
  23088. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  23089. const boundary = getByteBoundaryFromType( type );
  23090. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  23091. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  23092. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  23093. offset += chunkPadding;
  23094. // Check for chunk overflow
  23095. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  23096. // Add padding to the end of the chunk
  23097. offset += ( GPU_CHUNK_BYTES - chunkStart );
  23098. }
  23099. offset += itemSize;
  23100. }
  23101. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  23102. }
  23103. getMemberType( builder, name ) {
  23104. const member = this.membersLayout.find( m => m.name === name );
  23105. return member ? member.type : 'void';
  23106. }
  23107. getNodeType( builder ) {
  23108. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23109. return structType.name;
  23110. }
  23111. setup( builder ) {
  23112. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23113. builder.addInclude( this );
  23114. }
  23115. generate( builder ) {
  23116. return this.getNodeType( builder );
  23117. }
  23118. }
  23119. /**
  23120. * StructNode allows to create custom structures with multiple members.
  23121. * This can also be used to define structures in attribute and uniform data.
  23122. *
  23123. * ```js
  23124. * // Define a custom struct
  23125. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  23126. *
  23127. * // Create a new instance of the struct
  23128. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  23129. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  23130. *
  23131. * // Access the struct members
  23132. * const min = bb.get( 'min' );
  23133. *
  23134. * // Assign a new value to a member
  23135. * min.assign( vec3() );
  23136. * ```
  23137. * @augments Node
  23138. */
  23139. class StructNode extends Node {
  23140. static get type() {
  23141. return 'StructNode';
  23142. }
  23143. constructor( structTypeNode, values ) {
  23144. super( 'vec3' );
  23145. this.structTypeNode = structTypeNode;
  23146. this.values = values;
  23147. this.isStructNode = true;
  23148. }
  23149. getNodeType( builder ) {
  23150. return this.structTypeNode.getNodeType( builder );
  23151. }
  23152. getMemberType( builder, name ) {
  23153. return this.structTypeNode.getMemberType( builder, name );
  23154. }
  23155. generate( builder ) {
  23156. const nodeVar = builder.getVarFromNode( this );
  23157. const structType = nodeVar.type;
  23158. const propertyName = builder.getPropertyName( nodeVar );
  23159. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  23160. return nodeVar.name;
  23161. }
  23162. }
  23163. /**
  23164. * TSL function for creating a struct node.
  23165. *
  23166. * @tsl
  23167. * @function
  23168. * @param {Object} membersLayout - The layout of the struct members.
  23169. * @param {?string} [name=null] - The name of the struct.
  23170. * @returns {Function} The struct function.
  23171. */
  23172. const struct = ( membersLayout, name = null ) => {
  23173. const structLayout = new StructTypeNode( membersLayout, name );
  23174. const struct = ( ...params ) => {
  23175. let values = null;
  23176. if ( params.length > 0 ) {
  23177. if ( params[ 0 ].isNode ) {
  23178. values = {};
  23179. const names = Object.keys( membersLayout );
  23180. for ( let i = 0; i < params.length; i ++ ) {
  23181. values[ names[ i ] ] = params[ i ];
  23182. }
  23183. } else {
  23184. values = params[ 0 ];
  23185. }
  23186. }
  23187. return nodeObject( new StructNode( structLayout, values ) );
  23188. };
  23189. struct.layout = structLayout;
  23190. struct.isStruct = true;
  23191. return struct;
  23192. };
  23193. /**
  23194. * This node can be used to define multiple outputs in a shader programs.
  23195. *
  23196. * @augments Node
  23197. */
  23198. class OutputStructNode extends Node {
  23199. static get type() {
  23200. return 'OutputStructNode';
  23201. }
  23202. /**
  23203. * Constructs a new output struct node. The constructor can be invoked with an
  23204. * arbitrary number of nodes representing the members.
  23205. *
  23206. * @param {...Node} members - A parameter list of nodes.
  23207. */
  23208. constructor( ...members ) {
  23209. super();
  23210. /**
  23211. * An array of nodes which defines the output.
  23212. *
  23213. * @type {Array<Node>}
  23214. */
  23215. this.members = members;
  23216. /**
  23217. * This flag can be used for type testing.
  23218. *
  23219. * @type {boolean}
  23220. * @readonly
  23221. * @default true
  23222. */
  23223. this.isOutputStructNode = true;
  23224. }
  23225. getNodeType( builder ) {
  23226. const properties = builder.getNodeProperties( this );
  23227. if ( properties.membersLayout === undefined ) {
  23228. const members = this.members;
  23229. const membersLayout = [];
  23230. for ( let i = 0; i < members.length; i ++ ) {
  23231. const name = 'm' + i;
  23232. const type = members[ i ].getNodeType( builder );
  23233. membersLayout.push( { name, type, index: i } );
  23234. }
  23235. properties.membersLayout = membersLayout;
  23236. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  23237. }
  23238. return properties.structType.name;
  23239. }
  23240. generate( builder ) {
  23241. const propertyName = builder.getOutputStructName();
  23242. const members = this.members;
  23243. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  23244. for ( let i = 0; i < members.length; i ++ ) {
  23245. const snippet = members[ i ].build( builder );
  23246. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  23247. }
  23248. return propertyName;
  23249. }
  23250. }
  23251. /**
  23252. * TSL function for creating an output struct node.
  23253. *
  23254. * @tsl
  23255. * @function
  23256. * @param {...Node} members - A parameter list of nodes.
  23257. * @returns {OutputStructNode}
  23258. */
  23259. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  23260. /**
  23261. * Returns the MRT texture index for the given name.
  23262. *
  23263. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  23264. * @param {string} name - The name of the MRT texture which index is requested.
  23265. * @return {number} The texture index.
  23266. */
  23267. function getTextureIndex( textures, name ) {
  23268. for ( let i = 0; i < textures.length; i ++ ) {
  23269. if ( textures[ i ].name === name ) {
  23270. return i;
  23271. }
  23272. }
  23273. return -1;
  23274. }
  23275. /**
  23276. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  23277. * post-processing is shown below:
  23278. * ```js
  23279. * const mrtNode = mrt( {
  23280. * output: output,
  23281. * normal: normalView
  23282. * } ) );
  23283. * ```
  23284. * The MRT output is defined as a dictionary.
  23285. *
  23286. * @augments OutputStructNode
  23287. */
  23288. class MRTNode extends OutputStructNode {
  23289. static get type() {
  23290. return 'MRTNode';
  23291. }
  23292. /**
  23293. * Constructs a new output struct node.
  23294. *
  23295. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23296. */
  23297. constructor( outputNodes ) {
  23298. super();
  23299. /**
  23300. * A dictionary representing the MRT outputs. The key
  23301. * is the name of the output, the value the node which produces
  23302. * the output result.
  23303. *
  23304. * @type {Object<string, Node>}
  23305. */
  23306. this.outputNodes = outputNodes;
  23307. /**
  23308. * This flag can be used for type testing.
  23309. *
  23310. * @type {boolean}
  23311. * @readonly
  23312. * @default true
  23313. */
  23314. this.isMRTNode = true;
  23315. }
  23316. /**
  23317. * Returns `true` if the MRT node has an output with the given name.
  23318. *
  23319. * @param {string} name - The name of the output.
  23320. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  23321. */
  23322. has( name ) {
  23323. return this.outputNodes[ name ] !== undefined;
  23324. }
  23325. /**
  23326. * Returns the output node for the given name.
  23327. *
  23328. * @param {string} name - The name of the output.
  23329. * @return {Node} The output node.
  23330. */
  23331. get( name ) {
  23332. return this.outputNodes[ name ];
  23333. }
  23334. /**
  23335. * Merges the outputs of the given MRT node with the outputs of this node.
  23336. *
  23337. * @param {MRTNode} mrtNode - The MRT to merge.
  23338. * @return {MRTNode} A new MRT node with merged outputs..
  23339. */
  23340. merge( mrtNode ) {
  23341. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  23342. return mrt( outputs );
  23343. }
  23344. setup( builder ) {
  23345. const outputNodes = this.outputNodes;
  23346. const mrt = builder.renderer.getRenderTarget();
  23347. const members = [];
  23348. const textures = mrt.textures;
  23349. for ( const name in outputNodes ) {
  23350. const index = getTextureIndex( textures, name );
  23351. members[ index ] = vec4( outputNodes[ name ] );
  23352. }
  23353. this.members = members;
  23354. return super.setup( builder );
  23355. }
  23356. }
  23357. /**
  23358. * TSL function for creating a MRT node.
  23359. *
  23360. * @tsl
  23361. * @function
  23362. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23363. * @returns {MRTNode}
  23364. */
  23365. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  23366. /**
  23367. * This node represents an operation that reinterprets the bit representation of a value
  23368. * in one type as a value in another type.
  23369. *
  23370. * @augments TempNode
  23371. */
  23372. class BitcastNode extends TempNode {
  23373. static get type() {
  23374. return 'BitcastNode';
  23375. }
  23376. /**
  23377. * Constructs a new bitcast node.
  23378. *
  23379. * @param {Node} valueNode - The value to convert.
  23380. * @param {string} conversionType - The type to convert to.
  23381. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  23382. */
  23383. constructor( valueNode, conversionType, inputType = null ) {
  23384. super();
  23385. /**
  23386. * The data to bitcast to a new type.
  23387. *
  23388. * @type {Node}
  23389. */
  23390. this.valueNode = valueNode;
  23391. /**
  23392. * The type the value will be converted to.
  23393. *
  23394. * @type {string}
  23395. */
  23396. this.conversionType = conversionType;
  23397. /**
  23398. * The expected input data type of the bitcast operation.
  23399. *
  23400. *
  23401. * @type {string}
  23402. * @default null
  23403. */
  23404. this.inputType = inputType;
  23405. /**
  23406. * This flag can be used for type testing.
  23407. *
  23408. * @type {boolean}
  23409. * @readonly
  23410. * @default true
  23411. */
  23412. this.isBitcastNode = true;
  23413. }
  23414. getNodeType( builder ) {
  23415. // GLSL aliasing
  23416. if ( this.inputType !== null ) {
  23417. const valueType = this.valueNode.getNodeType( builder );
  23418. const valueLength = builder.getTypeLength( valueType );
  23419. return builder.getTypeFromLength( valueLength, this.conversionType );
  23420. }
  23421. return this.conversionType;
  23422. }
  23423. generate( builder ) {
  23424. const type = this.getNodeType( builder );
  23425. let inputType = '';
  23426. if ( this.inputType !== null ) {
  23427. const valueType = this.valueNode.getNodeType( builder );
  23428. const valueTypeLength = builder.getTypeLength( valueType );
  23429. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  23430. } else {
  23431. inputType = this.valueNode.getNodeType( builder );
  23432. }
  23433. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  23434. }
  23435. }
  23436. /**
  23437. * Reinterpret the bit representation of a value in one type as a value in another type.
  23438. *
  23439. * @tsl
  23440. * @function
  23441. * @param {Node | number} x - The parameter.
  23442. * @param {string} y - The new type.
  23443. * @returns {Node}
  23444. */
  23445. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  23446. /**
  23447. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  23448. *
  23449. * @tsl
  23450. * @function
  23451. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23452. * @returns {BitcastNode}
  23453. */
  23454. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  23455. /**
  23456. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  23457. *
  23458. * @tsl
  23459. * @function
  23460. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23461. * @returns {BitcastNode}
  23462. */
  23463. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  23464. /**
  23465. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  23466. *
  23467. * @tsl
  23468. * @function
  23469. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  23470. * @returns {BitcastNode}
  23471. */
  23472. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  23473. /**
  23474. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  23475. *
  23476. * @tsl
  23477. * @function
  23478. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  23479. * @returns {BitcastNode}
  23480. */
  23481. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  23482. /**
  23483. * Generates a hash value in the range `[0, 1]` from the given seed.
  23484. *
  23485. * @tsl
  23486. * @function
  23487. * @param {Node<float>} seed - The seed.
  23488. * @return {Node<float>} The hash value.
  23489. */
  23490. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  23491. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  23492. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  23493. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  23494. const result = word.shiftRight( 22 ).bitXor( word );
  23495. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  23496. } );
  23497. /**
  23498. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23499. * The corners are mapped to `0` and the center to `1`.
  23500. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23501. *
  23502. * @tsl
  23503. * @function
  23504. * @param {Node<float>} x - The value to remap.
  23505. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  23506. * @return {Node<float>} The remapped value.
  23507. */
  23508. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  23509. /**
  23510. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23511. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  23512. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23513. *
  23514. * @tsl
  23515. * @function
  23516. * @param {Node<float>} x - The value to remap.
  23517. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  23518. * @return {Node<float>} The remapped value.
  23519. */
  23520. 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 ) );
  23521. /**
  23522. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23523. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  23524. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23525. *
  23526. * @tsl
  23527. * @function
  23528. * @param {Node<float>} x - The value to remap.
  23529. * @param {Node<float>} a - First control parameter.
  23530. * @param {Node<float>} b - Second control parameter.
  23531. * @return {Node<float>} The remapped value.
  23532. */
  23533. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  23534. /**
  23535. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  23536. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23537. *
  23538. * @tsl
  23539. * @function
  23540. * @param {Node<float>} x - The value to compute the sin for.
  23541. * @param {Node<float>} k - Controls the amount of bounces.
  23542. * @return {Node<float>} The result value.
  23543. */
  23544. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  23545. // https://github.com/cabbibo/glsl-tri-noise-3d
  23546. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  23547. return x.fract().sub( .5 ).abs();
  23548. } ).setLayout( {
  23549. name: 'tri',
  23550. type: 'float',
  23551. inputs: [
  23552. { name: 'x', type: 'float' }
  23553. ]
  23554. } );
  23555. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  23556. 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. ) ) ) ) );
  23557. } ).setLayout( {
  23558. name: 'tri3',
  23559. type: 'vec3',
  23560. inputs: [
  23561. { name: 'p', type: 'vec3' }
  23562. ]
  23563. } );
  23564. /**
  23565. * Generates a noise value from the given position, speed and time parameters.
  23566. *
  23567. * @tsl
  23568. * @function
  23569. * @param {Node<vec3>} position - The position.
  23570. * @param {Node<float>} speed - The speed.
  23571. * @param {Node<float>} time - The time.
  23572. * @return {Node<float>} The generated noise.
  23573. */
  23574. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  23575. const p = vec3( position ).toVar();
  23576. const z = float( 1.4 ).toVar();
  23577. const rz = float( 0.0 ).toVar();
  23578. const bp = vec3( p ).toVar();
  23579. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  23580. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  23581. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  23582. bp.mulAssign( 1.8 );
  23583. z.mulAssign( 1.5 );
  23584. p.mulAssign( 1.2 );
  23585. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  23586. rz.addAssign( t.div( z ) );
  23587. bp.addAssign( 0.14 );
  23588. } );
  23589. return rz;
  23590. } ).setLayout( {
  23591. name: 'triNoise3D',
  23592. type: 'float',
  23593. inputs: [
  23594. { name: 'position', type: 'vec3' },
  23595. { name: 'speed', type: 'float' },
  23596. { name: 'time', type: 'float' }
  23597. ]
  23598. } );
  23599. /**
  23600. * This class allows to define multiple overloaded versions
  23601. * of the same function. Depending on the parameters of the function
  23602. * call, the node picks the best-fit overloaded version.
  23603. *
  23604. * @augments Node
  23605. */
  23606. class FunctionOverloadingNode extends Node {
  23607. static get type() {
  23608. return 'FunctionOverloadingNode';
  23609. }
  23610. /**
  23611. * Constructs a new function overloading node.
  23612. *
  23613. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  23614. * @param {...Node} parametersNodes - A list of parameter nodes.
  23615. */
  23616. constructor( functionNodes = [], ...parametersNodes ) {
  23617. super();
  23618. /**
  23619. * Array of `Fn` function definitions.
  23620. *
  23621. * @type {Array<Function>}
  23622. */
  23623. this.functionNodes = functionNodes;
  23624. /**
  23625. * A list of parameter nodes.
  23626. *
  23627. * @type {Array<Node>}
  23628. */
  23629. this.parametersNodes = parametersNodes;
  23630. /**
  23631. * The selected overloaded function call.
  23632. *
  23633. * @private
  23634. * @type {ShaderCallNodeInternal}
  23635. */
  23636. this._candidateFnCall = null;
  23637. /**
  23638. * This node is marked as global.
  23639. *
  23640. * @type {boolean}
  23641. * @default true
  23642. */
  23643. this.global = true;
  23644. }
  23645. /**
  23646. * This method is overwritten since the node type is inferred from
  23647. * the function's return type.
  23648. *
  23649. * @param {NodeBuilder} builder - The current node builder.
  23650. * @return {string} The node type.
  23651. */
  23652. getNodeType() {
  23653. return this.functionNodes[ 0 ].shaderNode.layout.type;
  23654. }
  23655. setup( builder ) {
  23656. const params = this.parametersNodes;
  23657. let candidateFnCall = this._candidateFnCall;
  23658. if ( candidateFnCall === null ) {
  23659. let candidateFn = null;
  23660. let candidateScore = -1;
  23661. for ( const functionNode of this.functionNodes ) {
  23662. const shaderNode = functionNode.shaderNode;
  23663. const layout = shaderNode.layout;
  23664. if ( layout === null ) {
  23665. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  23666. }
  23667. const inputs = layout.inputs;
  23668. if ( params.length === inputs.length ) {
  23669. let score = 0;
  23670. for ( let i = 0; i < params.length; i ++ ) {
  23671. const param = params[ i ];
  23672. const input = inputs[ i ];
  23673. if ( param.getNodeType( builder ) === input.type ) {
  23674. score ++;
  23675. } else {
  23676. score = 0;
  23677. }
  23678. }
  23679. if ( score > candidateScore ) {
  23680. candidateFn = functionNode;
  23681. candidateScore = score;
  23682. }
  23683. }
  23684. }
  23685. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  23686. }
  23687. return candidateFnCall;
  23688. }
  23689. }
  23690. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  23691. /**
  23692. * TSL function for creating a function overloading node.
  23693. *
  23694. * @tsl
  23695. * @function
  23696. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  23697. * @returns {FunctionOverloadingNode}
  23698. */
  23699. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  23700. /**
  23701. * Represents the elapsed time in seconds.
  23702. *
  23703. * @tsl
  23704. * @type {UniformNode<float>}
  23705. */
  23706. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  23707. /**
  23708. * Represents the delta time in seconds.
  23709. *
  23710. * @tsl
  23711. * @type {UniformNode<float>}
  23712. */
  23713. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  23714. /**
  23715. * Represents the current frame ID.
  23716. *
  23717. * @tsl
  23718. * @type {UniformNode<uint>}
  23719. */
  23720. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  23721. /**
  23722. * Generates a sine wave oscillation based on a timer.
  23723. *
  23724. * @tsl
  23725. * @function
  23726. * @param {Node<float>} t - The timer to generate the oscillation with.
  23727. * @return {Node<float>} The oscillation node.
  23728. */
  23729. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  23730. /**
  23731. * Generates a square wave oscillation based on a timer.
  23732. *
  23733. * @tsl
  23734. * @function
  23735. * @param {Node<float>} t - The timer to generate the oscillation with.
  23736. * @return {Node<float>} The oscillation node.
  23737. */
  23738. const oscSquare = ( t = time ) => t.fract().round();
  23739. /**
  23740. * Generates a triangle wave oscillation based on a timer.
  23741. *
  23742. * @tsl
  23743. * @function
  23744. * @param {Node<float>} t - The timer to generate the oscillation with.
  23745. * @return {Node<float>} The oscillation node.
  23746. */
  23747. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  23748. /**
  23749. * Generates a sawtooth wave oscillation based on a timer.
  23750. *
  23751. * @tsl
  23752. * @function
  23753. * @param {Node<float>} t - The timer to generate the oscillation with.
  23754. * @return {Node<float>} The oscillation node.
  23755. */
  23756. const oscSawtooth = ( t = time ) => t.fract();
  23757. /**
  23758. * Rotates the given uv coordinates around a center point
  23759. *
  23760. * @tsl
  23761. * @function
  23762. * @param {Node<vec2>} uv - The uv coordinates.
  23763. * @param {Node<float>} rotation - The rotation defined in radians.
  23764. * @param {Node<vec2>} center - The center of rotation
  23765. * @return {Node<vec2>} The rotated uv coordinates.
  23766. */
  23767. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  23768. return rotate( uv.sub( center ), rotation ).add( center );
  23769. } );
  23770. /**
  23771. * Applies a spherical warping effect to the given uv coordinates.
  23772. *
  23773. * @tsl
  23774. * @function
  23775. * @param {Node<vec2>} uv - The uv coordinates.
  23776. * @param {Node<float>} strength - The strength of the effect.
  23777. * @param {Node<vec2>} center - The center point
  23778. * @return {Node<vec2>} The updated uv coordinates.
  23779. */
  23780. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  23781. const delta = uv.sub( center );
  23782. const delta2 = delta.dot( delta );
  23783. const delta4 = delta2.mul( delta2 );
  23784. const deltaOffset = delta4.mul( strength );
  23785. return uv.add( delta.mul( deltaOffset ) );
  23786. } );
  23787. /**
  23788. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  23789. * oriented always towards the camera.
  23790. *
  23791. * ```js
  23792. * material.vertexNode = billboarding();
  23793. * ```
  23794. *
  23795. * @tsl
  23796. * @function
  23797. * @param {Object} config - The configuration object.
  23798. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  23799. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  23800. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  23801. * @return {Node<vec3>} The updated vertex position in clip space.
  23802. */
  23803. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  23804. let worldMatrix;
  23805. if ( position !== null ) {
  23806. worldMatrix = modelWorldMatrix.toVar();
  23807. worldMatrix[ 3 ][ 0 ] = position.x;
  23808. worldMatrix[ 3 ][ 1 ] = position.y;
  23809. worldMatrix[ 3 ][ 2 ] = position.z;
  23810. } else {
  23811. worldMatrix = modelWorldMatrix;
  23812. }
  23813. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  23814. if ( defined( horizontal ) ) {
  23815. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  23816. modelViewMatrix[ 0 ][ 1 ] = 0;
  23817. modelViewMatrix[ 0 ][ 2 ] = 0;
  23818. }
  23819. if ( defined( vertical ) ) {
  23820. modelViewMatrix[ 1 ][ 0 ] = 0;
  23821. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  23822. modelViewMatrix[ 1 ][ 2 ] = 0;
  23823. }
  23824. modelViewMatrix[ 2 ][ 0 ] = 0;
  23825. modelViewMatrix[ 2 ][ 1 ] = 0;
  23826. modelViewMatrix[ 2 ][ 2 ] = 1;
  23827. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  23828. } );
  23829. /**
  23830. * A special version of a screen uv function that involves a depth comparison
  23831. * when computing the final uvs. The function mitigates visual errors when
  23832. * using viewport texture nodes for refraction purposes. Without this function
  23833. * objects in front of a refractive surface might appear on the refractive surface
  23834. * which is incorrect.
  23835. *
  23836. * @tsl
  23837. * @function
  23838. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  23839. * @return {Node<vec2>} The update uv coordinates.
  23840. */
  23841. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  23842. const depth = linearDepth();
  23843. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  23844. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  23845. return finalUV;
  23846. } );
  23847. /**
  23848. * Can be used to compute texture coordinates for animated sprite sheets.
  23849. *
  23850. * ```js
  23851. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  23852. *
  23853. * material.colorNode = texture( spriteSheet, uvNode );
  23854. * ```
  23855. *
  23856. * @augments Node
  23857. */
  23858. class SpriteSheetUVNode extends Node {
  23859. static get type() {
  23860. return 'SpriteSheetUVNode';
  23861. }
  23862. /**
  23863. * Constructs a new sprite sheet uv node.
  23864. *
  23865. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23866. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  23867. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23868. */
  23869. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  23870. super( 'vec2' );
  23871. /**
  23872. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23873. *
  23874. * @type {Node<vec2>}
  23875. */
  23876. this.countNode = countNode;
  23877. /**
  23878. * The uv node.
  23879. *
  23880. * @type {Node<vec2>}
  23881. */
  23882. this.uvNode = uvNode;
  23883. /**
  23884. * The node that defines the current frame/sprite.
  23885. *
  23886. * @type {Node<float>}
  23887. */
  23888. this.frameNode = frameNode;
  23889. }
  23890. setup() {
  23891. const { frameNode, uvNode, countNode } = this;
  23892. const { width, height } = countNode;
  23893. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  23894. const column = frameNum.mod( width );
  23895. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  23896. const scale = countNode.reciprocal();
  23897. const uvFrameOffset = vec2( column, row );
  23898. return uvNode.add( uvFrameOffset ).mul( scale );
  23899. }
  23900. }
  23901. /**
  23902. * TSL function for creating a sprite sheet uv node.
  23903. *
  23904. * @tsl
  23905. * @function
  23906. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23907. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  23908. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23909. * @returns {SpriteSheetUVNode}
  23910. */
  23911. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  23912. /**
  23913. * TSL function for creating a triplanar textures node.
  23914. *
  23915. * Can be used for triplanar texture mapping.
  23916. *
  23917. * ```js
  23918. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  23919. * ```
  23920. *
  23921. * @tsl
  23922. * @function
  23923. * @param {Node} textureXNode - First texture node.
  23924. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23925. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23926. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23927. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23928. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23929. * @returns {Node<vec4>}
  23930. */
  23931. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  23932. // Reference: https://github.com/keijiro/StandardTriplanar
  23933. // Blending factor of triplanar mapping
  23934. let bf = normalNode.abs().normalize();
  23935. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  23936. // Triplanar mapping
  23937. const tx = positionNode.yz.mul( scaleNode );
  23938. const ty = positionNode.zx.mul( scaleNode );
  23939. const tz = positionNode.xy.mul( scaleNode );
  23940. // Base color
  23941. const textureX = textureXNode.value;
  23942. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  23943. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  23944. const cx = texture( textureX, tx ).mul( bf.x );
  23945. const cy = texture( textureY, ty ).mul( bf.y );
  23946. const cz = texture( textureZ, tz ).mul( bf.z );
  23947. return add( cx, cy, cz );
  23948. } );
  23949. /**
  23950. * TSL function for creating a triplanar textures node.
  23951. *
  23952. * @tsl
  23953. * @function
  23954. * @param {Node} textureXNode - First texture node.
  23955. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23956. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23957. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23958. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23959. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23960. * @returns {Node<vec4>}
  23961. */
  23962. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  23963. const _reflectorPlane = new Plane();
  23964. const _normal = new Vector3();
  23965. const _reflectorWorldPosition = new Vector3();
  23966. const _cameraWorldPosition = new Vector3();
  23967. const _rotationMatrix = new Matrix4();
  23968. const _lookAtPosition = new Vector3( 0, 0, -1 );
  23969. const clipPlane = new Vector4();
  23970. const _view = new Vector3();
  23971. const _target = new Vector3();
  23972. const _q = new Vector4();
  23973. const _size$2 = new Vector2();
  23974. const _defaultRT = new RenderTarget();
  23975. const _defaultUV = screenUV.flipX();
  23976. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  23977. let _inReflector = false;
  23978. /**
  23979. * This node can be used to implement mirror-like flat reflective surfaces.
  23980. *
  23981. * ```js
  23982. * const groundReflector = reflector();
  23983. * material.colorNode = groundReflector;
  23984. *
  23985. * const plane = new Mesh( geometry, material );
  23986. * plane.add( groundReflector.target );
  23987. * ```
  23988. *
  23989. * @augments TextureNode
  23990. */
  23991. class ReflectorNode extends TextureNode {
  23992. static get type() {
  23993. return 'ReflectorNode';
  23994. }
  23995. /**
  23996. * Constructs a new reflector node.
  23997. *
  23998. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23999. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24000. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  24001. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24002. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24003. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24004. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24005. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  24006. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  24007. */
  24008. constructor( parameters = {} ) {
  24009. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  24010. /**
  24011. * A reference to the internal reflector base node which holds the actual implementation.
  24012. *
  24013. * @private
  24014. * @type {ReflectorBaseNode}
  24015. * @default ReflectorBaseNode
  24016. */
  24017. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  24018. /**
  24019. * A reference to the internal depth node.
  24020. *
  24021. * @private
  24022. * @type {?Node}
  24023. * @default null
  24024. */
  24025. this._depthNode = null;
  24026. this.setUpdateMatrix( false );
  24027. }
  24028. /**
  24029. * A reference to the internal reflector node.
  24030. *
  24031. * @type {ReflectorBaseNode}
  24032. */
  24033. get reflector() {
  24034. return this._reflectorBaseNode;
  24035. }
  24036. /**
  24037. * A reference to 3D object the reflector is linked to.
  24038. *
  24039. * @type {Object3D}
  24040. */
  24041. get target() {
  24042. return this._reflectorBaseNode.target;
  24043. }
  24044. /**
  24045. * Returns a node representing the mirror's depth. That can be used
  24046. * to implement more advanced reflection effects like distance attenuation.
  24047. *
  24048. * @return {Node} The depth node.
  24049. */
  24050. getDepthNode() {
  24051. if ( this._depthNode === null ) {
  24052. if ( this._reflectorBaseNode.depth !== true ) {
  24053. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  24054. }
  24055. this._depthNode = nodeObject( new ReflectorNode( {
  24056. defaultTexture: _defaultRT.depthTexture,
  24057. reflector: this._reflectorBaseNode
  24058. } ) );
  24059. }
  24060. return this._depthNode;
  24061. }
  24062. setup( builder ) {
  24063. // ignore if used in post-processing
  24064. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  24065. return super.setup( builder );
  24066. }
  24067. clone() {
  24068. const newNode = new this.constructor( this.reflectorNode );
  24069. newNode.uvNode = this.uvNode;
  24070. newNode.levelNode = this.levelNode;
  24071. newNode.biasNode = this.biasNode;
  24072. newNode.sampler = this.sampler;
  24073. newNode.depthNode = this.depthNode;
  24074. newNode.compareNode = this.compareNode;
  24075. newNode.gradNode = this.gradNode;
  24076. newNode.offsetNode = this.offsetNode;
  24077. newNode._reflectorBaseNode = this._reflectorBaseNode;
  24078. return newNode;
  24079. }
  24080. /**
  24081. * Frees internal resources. Should be called when the node is no longer in use.
  24082. */
  24083. dispose() {
  24084. super.dispose();
  24085. this._reflectorBaseNode.dispose();
  24086. }
  24087. }
  24088. /**
  24089. * Holds the actual implementation of the reflector.
  24090. *
  24091. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  24092. * in `ReflectorNode`, see #29619.
  24093. *
  24094. * @private
  24095. * @augments Node
  24096. */
  24097. class ReflectorBaseNode extends Node {
  24098. static get type() {
  24099. return 'ReflectorBaseNode';
  24100. }
  24101. /**
  24102. * Constructs a new reflector base node.
  24103. *
  24104. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  24105. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24106. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24107. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  24108. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24109. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24110. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24111. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24112. */
  24113. constructor( textureNode, parameters = {} ) {
  24114. super();
  24115. const {
  24116. target = new Object3D(),
  24117. resolutionScale = 1,
  24118. generateMipmaps = false,
  24119. bounces = true,
  24120. depth = false,
  24121. samples = 0
  24122. } = parameters;
  24123. /**
  24124. * Represents the rendered reflections as a texture node.
  24125. *
  24126. * @type {TextureNode}
  24127. */
  24128. this.textureNode = textureNode;
  24129. /**
  24130. * The 3D object the reflector is linked to.
  24131. *
  24132. * @type {Object3D}
  24133. * @default {new Object3D()}
  24134. */
  24135. this.target = target;
  24136. /**
  24137. * The resolution scale.
  24138. *
  24139. * @type {number}
  24140. * @default {1}
  24141. */
  24142. this.resolutionScale = resolutionScale;
  24143. if ( parameters.resolution !== undefined ) {
  24144. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  24145. this.resolutionScale = parameters.resolution;
  24146. }
  24147. /**
  24148. * Whether mipmaps should be generated or not.
  24149. *
  24150. * @type {boolean}
  24151. * @default {false}
  24152. */
  24153. this.generateMipmaps = generateMipmaps;
  24154. /**
  24155. * Whether reflectors can render other reflector nodes or not.
  24156. *
  24157. * @type {boolean}
  24158. * @default {true}
  24159. */
  24160. this.bounces = bounces;
  24161. /**
  24162. * Whether depth data should be generated or not.
  24163. *
  24164. * @type {boolean}
  24165. * @default {false}
  24166. */
  24167. this.depth = depth;
  24168. /**
  24169. * The number of anti-aliasing samples for the render-target
  24170. *
  24171. * @type {number}
  24172. * @default {0}
  24173. */
  24174. this.samples = samples;
  24175. /**
  24176. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  24177. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  24178. *
  24179. * @type {string}
  24180. * @default 'render'
  24181. */
  24182. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  24183. /**
  24184. * Weak map for managing virtual cameras.
  24185. *
  24186. * @type {WeakMap<Camera, Camera>}
  24187. */
  24188. this.virtualCameras = new WeakMap();
  24189. /**
  24190. * Weak map for managing render targets.
  24191. *
  24192. * @type {Map<Camera, RenderTarget>}
  24193. */
  24194. this.renderTargets = new Map();
  24195. /**
  24196. * Force render even if reflector is facing away from camera.
  24197. *
  24198. * @type {boolean}
  24199. * @default {false}
  24200. */
  24201. this.forceUpdate = false;
  24202. /**
  24203. * Whether the reflector has been rendered or not.
  24204. *
  24205. * When the reflector is facing away from the camera,
  24206. * this flag is set to `false` and the texture will be empty(black).
  24207. *
  24208. * @type {boolean}
  24209. * @default {false}
  24210. */
  24211. this.hasOutput = false;
  24212. }
  24213. /**
  24214. * Updates the resolution of the internal render target.
  24215. *
  24216. * @private
  24217. * @param {RenderTarget} renderTarget - The render target to resize.
  24218. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  24219. */
  24220. _updateResolution( renderTarget, renderer ) {
  24221. const resolution = this.resolutionScale;
  24222. renderer.getDrawingBufferSize( _size$2 );
  24223. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  24224. }
  24225. setup( builder ) {
  24226. this._updateResolution( _defaultRT, builder.renderer );
  24227. return super.setup( builder );
  24228. }
  24229. /**
  24230. * Frees internal resources. Should be called when the node is no longer in use.
  24231. */
  24232. dispose() {
  24233. super.dispose();
  24234. for ( const renderTarget of this.renderTargets.values() ) {
  24235. renderTarget.dispose();
  24236. }
  24237. }
  24238. /**
  24239. * Returns a virtual camera for the given camera. The virtual camera is used to
  24240. * render the scene from the reflector's view so correct reflections can be produced.
  24241. *
  24242. * @param {Camera} camera - The scene's camera.
  24243. * @return {Camera} The corresponding virtual camera.
  24244. */
  24245. getVirtualCamera( camera ) {
  24246. let virtualCamera = this.virtualCameras.get( camera );
  24247. if ( virtualCamera === undefined ) {
  24248. virtualCamera = camera.clone();
  24249. this.virtualCameras.set( camera, virtualCamera );
  24250. }
  24251. return virtualCamera;
  24252. }
  24253. /**
  24254. * Returns a render target for the given camera. The reflections are rendered
  24255. * into this render target.
  24256. *
  24257. * @param {Camera} camera - The scene's camera.
  24258. * @return {RenderTarget} The render target.
  24259. */
  24260. getRenderTarget( camera ) {
  24261. let renderTarget = this.renderTargets.get( camera );
  24262. if ( renderTarget === undefined ) {
  24263. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  24264. if ( this.generateMipmaps === true ) {
  24265. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  24266. renderTarget.texture.generateMipmaps = true;
  24267. }
  24268. if ( this.depth === true ) {
  24269. renderTarget.depthTexture = new DepthTexture();
  24270. }
  24271. this.renderTargets.set( camera, renderTarget );
  24272. }
  24273. return renderTarget;
  24274. }
  24275. updateBefore( frame ) {
  24276. if ( this.bounces === false && _inReflector ) return false;
  24277. _inReflector = true;
  24278. const { scene, camera, renderer, material } = frame;
  24279. const { target } = this;
  24280. const virtualCamera = this.getVirtualCamera( camera );
  24281. const renderTarget = this.getRenderTarget( virtualCamera );
  24282. renderer.getDrawingBufferSize( _size$2 );
  24283. this._updateResolution( renderTarget, renderer );
  24284. //
  24285. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  24286. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  24287. _rotationMatrix.extractRotation( target.matrixWorld );
  24288. _normal.set( 0, 0, 1 );
  24289. _normal.applyMatrix4( _rotationMatrix );
  24290. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  24291. // Avoid rendering when reflector is facing away unless forcing an update
  24292. const isFacingAway = _view.dot( _normal ) > 0;
  24293. let needsClear = false;
  24294. if ( isFacingAway === true && this.forceUpdate === false ) {
  24295. if ( this.hasOutput === false ) {
  24296. _inReflector = false;
  24297. return;
  24298. }
  24299. needsClear = true;
  24300. }
  24301. _view.reflect( _normal ).negate();
  24302. _view.add( _reflectorWorldPosition );
  24303. _rotationMatrix.extractRotation( camera.matrixWorld );
  24304. _lookAtPosition.set( 0, 0, -1 );
  24305. _lookAtPosition.applyMatrix4( _rotationMatrix );
  24306. _lookAtPosition.add( _cameraWorldPosition );
  24307. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  24308. _target.reflect( _normal ).negate();
  24309. _target.add( _reflectorWorldPosition );
  24310. //
  24311. virtualCamera.coordinateSystem = camera.coordinateSystem;
  24312. virtualCamera.position.copy( _view );
  24313. virtualCamera.up.set( 0, 1, 0 );
  24314. virtualCamera.up.applyMatrix4( _rotationMatrix );
  24315. virtualCamera.up.reflect( _normal );
  24316. virtualCamera.lookAt( _target );
  24317. virtualCamera.near = camera.near;
  24318. virtualCamera.far = camera.far;
  24319. virtualCamera.updateMatrixWorld();
  24320. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  24321. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  24322. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  24323. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  24324. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  24325. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  24326. const projectionMatrix = virtualCamera.projectionMatrix;
  24327. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  24328. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  24329. _q.z = -1;
  24330. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  24331. // Calculate the scaled plane vector
  24332. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  24333. const clipBias = 0;
  24334. // Replacing the third row of the projection matrix
  24335. projectionMatrix.elements[ 2 ] = clipPlane.x;
  24336. projectionMatrix.elements[ 6 ] = clipPlane.y;
  24337. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  24338. projectionMatrix.elements[ 14 ] = clipPlane.w;
  24339. //
  24340. this.textureNode.value = renderTarget.texture;
  24341. if ( this.depth === true ) {
  24342. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  24343. }
  24344. material.visible = false;
  24345. const currentRenderTarget = renderer.getRenderTarget();
  24346. const currentMRT = renderer.getMRT();
  24347. const currentAutoClear = renderer.autoClear;
  24348. renderer.setMRT( null );
  24349. renderer.setRenderTarget( renderTarget );
  24350. renderer.autoClear = true;
  24351. const previousName = scene.name;
  24352. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  24353. if ( needsClear ) {
  24354. renderer.clear();
  24355. this.hasOutput = false;
  24356. } else {
  24357. renderer.render( scene, virtualCamera );
  24358. this.hasOutput = true;
  24359. }
  24360. scene.name = previousName;
  24361. renderer.setMRT( currentMRT );
  24362. renderer.setRenderTarget( currentRenderTarget );
  24363. renderer.autoClear = currentAutoClear;
  24364. material.visible = true;
  24365. _inReflector = false;
  24366. this.forceUpdate = false;
  24367. }
  24368. /**
  24369. * The resolution scale.
  24370. *
  24371. * @deprecated
  24372. * @type {number}
  24373. * @default {1}
  24374. */
  24375. get resolution() {
  24376. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  24377. return this.resolutionScale;
  24378. }
  24379. set resolution( value ) {
  24380. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  24381. this.resolutionScale = value;
  24382. }
  24383. }
  24384. /**
  24385. * TSL function for creating a reflector node.
  24386. *
  24387. * @tsl
  24388. * @function
  24389. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24390. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24391. * @param {number} [parameters.resolution=1] - The resolution scale.
  24392. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24393. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24394. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24395. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24396. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  24397. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  24398. * @returns {ReflectorNode}
  24399. */
  24400. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  24401. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  24402. /**
  24403. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  24404. *
  24405. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  24406. *
  24407. * @private
  24408. * @augments BufferGeometry
  24409. */
  24410. class QuadGeometry extends BufferGeometry {
  24411. /**
  24412. * Constructs a new quad geometry.
  24413. *
  24414. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  24415. */
  24416. constructor( flipY = false ) {
  24417. super();
  24418. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  24419. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  24420. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  24421. }
  24422. }
  24423. const _geometry = /*@__PURE__*/ new QuadGeometry();
  24424. /**
  24425. * This module is a helper for passes which need to render a full
  24426. * screen effect which is quite common in context of post processing.
  24427. *
  24428. * The intended usage is to reuse a single quad mesh for rendering
  24429. * subsequent passes by just reassigning the `material` reference.
  24430. *
  24431. * Note: This module can only be used with `WebGPURenderer`.
  24432. *
  24433. * @augments Mesh
  24434. */
  24435. class QuadMesh extends Mesh {
  24436. /**
  24437. * Constructs a new quad mesh.
  24438. *
  24439. * @param {?Material} [material=null] - The material to render the quad mesh with.
  24440. */
  24441. constructor( material = null ) {
  24442. super( _geometry, material );
  24443. /**
  24444. * The camera to render the quad mesh with.
  24445. *
  24446. * @type {OrthographicCamera}
  24447. * @readonly
  24448. */
  24449. this.camera = _camera;
  24450. /**
  24451. * This flag can be used for type testing.
  24452. *
  24453. * @type {boolean}
  24454. * @readonly
  24455. * @default true
  24456. */
  24457. this.isQuadMesh = true;
  24458. }
  24459. /**
  24460. * Async version of `render()`.
  24461. *
  24462. * @async
  24463. * @deprecated
  24464. * @param {Renderer} renderer - The renderer.
  24465. * @return {Promise} A Promise that resolves when the render has been finished.
  24466. */
  24467. async renderAsync( renderer ) {
  24468. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  24469. await renderer.init();
  24470. renderer.render( this, _camera );
  24471. }
  24472. /**
  24473. * Renders the quad mesh
  24474. *
  24475. * @param {Renderer} renderer - The renderer.
  24476. */
  24477. render( renderer ) {
  24478. renderer.render( this, _camera );
  24479. }
  24480. }
  24481. const _size$1 = /*@__PURE__*/ new Vector2();
  24482. /**
  24483. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  24484. * This module is especially relevant in context of post processing where certain nodes require
  24485. * texture input for their effects. With the helper function `convertToTexture()` which is based
  24486. * on this module, the node system can automatically ensure texture input if required.
  24487. *
  24488. * @augments TextureNode
  24489. */
  24490. class RTTNode extends TextureNode {
  24491. static get type() {
  24492. return 'RTTNode';
  24493. }
  24494. /**
  24495. * Constructs a new RTT node.
  24496. *
  24497. * @param {Node} node - The node to render a texture with.
  24498. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24499. * @param {?number} [height=null] - The height of the internal render target.
  24500. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24501. */
  24502. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  24503. const renderTarget = new RenderTarget( width, height, options );
  24504. super( renderTarget.texture, uv$1() );
  24505. /**
  24506. * This flag can be used for type testing.
  24507. *
  24508. * @type {boolean}
  24509. * @readonly
  24510. * @default true
  24511. */
  24512. this.isRTTNode = true;
  24513. /**
  24514. * The node to render a texture with.
  24515. *
  24516. * @type {Node}
  24517. */
  24518. this.node = node;
  24519. /**
  24520. * The width of the internal render target.
  24521. * If not width is applied, the render target is automatically resized.
  24522. *
  24523. * @type {?number}
  24524. * @default null
  24525. */
  24526. this.width = width;
  24527. /**
  24528. * The height of the internal render target.
  24529. *
  24530. * @type {?number}
  24531. * @default null
  24532. */
  24533. this.height = height;
  24534. /**
  24535. * The pixel ratio
  24536. *
  24537. * @type {number}
  24538. * @default 1
  24539. */
  24540. this.pixelRatio = 1;
  24541. /**
  24542. * The render target
  24543. *
  24544. * @type {RenderTarget}
  24545. */
  24546. this.renderTarget = renderTarget;
  24547. /**
  24548. * Whether the texture requires an update or not.
  24549. *
  24550. * @type {boolean}
  24551. * @default true
  24552. */
  24553. this.textureNeedsUpdate = true;
  24554. /**
  24555. * Whether the texture should automatically be updated or not.
  24556. *
  24557. * @type {boolean}
  24558. * @default true
  24559. */
  24560. this.autoUpdate = true;
  24561. /**
  24562. * The node which is used with the quad mesh for RTT.
  24563. *
  24564. * @private
  24565. * @type {Node}
  24566. * @default null
  24567. */
  24568. this._rttNode = null;
  24569. /**
  24570. * The internal quad mesh for RTT.
  24571. *
  24572. * @private
  24573. * @type {QuadMesh}
  24574. */
  24575. this._quadMesh = new QuadMesh( new NodeMaterial() );
  24576. /**
  24577. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  24578. * the texture once per render in its {@link RTTNode#updateBefore} method.
  24579. *
  24580. * @type {string}
  24581. * @default 'render'
  24582. */
  24583. this.updateBeforeType = NodeUpdateType.RENDER;
  24584. }
  24585. /**
  24586. * Whether the internal render target should automatically be resized or not.
  24587. *
  24588. * @type {boolean}
  24589. * @readonly
  24590. * @default true
  24591. */
  24592. get autoResize() {
  24593. return this.width === null;
  24594. }
  24595. setup( builder ) {
  24596. this._rttNode = this.node.context( builder.getSharedContext() );
  24597. this._quadMesh.material.name = 'RTT';
  24598. this._quadMesh.material.needsUpdate = true;
  24599. return super.setup( builder );
  24600. }
  24601. /**
  24602. * Sets the size of the internal render target
  24603. *
  24604. * @param {number} width - The width to set.
  24605. * @param {number} height - The width to set.
  24606. */
  24607. setSize( width, height ) {
  24608. this.width = width;
  24609. this.height = height;
  24610. const effectiveWidth = width * this.pixelRatio;
  24611. const effectiveHeight = height * this.pixelRatio;
  24612. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24613. this.textureNeedsUpdate = true;
  24614. }
  24615. /**
  24616. * Sets the pixel ratio. This will also resize the render target.
  24617. *
  24618. * @param {number} pixelRatio - The pixel ratio to set.
  24619. */
  24620. setPixelRatio( pixelRatio ) {
  24621. this.pixelRatio = pixelRatio;
  24622. this.setSize( this.width, this.height );
  24623. }
  24624. updateBefore( { renderer } ) {
  24625. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  24626. this.textureNeedsUpdate = false;
  24627. //
  24628. if ( this.autoResize === true ) {
  24629. const pixelRatio = renderer.getPixelRatio();
  24630. const size = renderer.getSize( _size$1 );
  24631. const effectiveWidth = size.width * pixelRatio;
  24632. const effectiveHeight = size.height * pixelRatio;
  24633. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  24634. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24635. this.textureNeedsUpdate = true;
  24636. }
  24637. }
  24638. //
  24639. let name = 'RTT';
  24640. if ( this.node.name ) {
  24641. name = this.node.name + ' [ ' + name + ' ]';
  24642. }
  24643. this._quadMesh.material.fragmentNode = this._rttNode;
  24644. this._quadMesh.name = name;
  24645. //
  24646. const currentRenderTarget = renderer.getRenderTarget();
  24647. renderer.setRenderTarget( this.renderTarget );
  24648. this._quadMesh.render( renderer );
  24649. renderer.setRenderTarget( currentRenderTarget );
  24650. }
  24651. clone() {
  24652. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  24653. newNode.sampler = this.sampler;
  24654. newNode.referenceNode = this;
  24655. return newNode;
  24656. }
  24657. }
  24658. /**
  24659. * TSL function for creating a RTT node.
  24660. *
  24661. * @tsl
  24662. * @function
  24663. * @param {Node} node - The node to render a texture with.
  24664. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24665. * @param {?number} [height=null] - The height of the internal render target.
  24666. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24667. * @returns {RTTNode}
  24668. */
  24669. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  24670. /**
  24671. * TSL function for converting nodes to textures nodes.
  24672. *
  24673. * @tsl
  24674. * @function
  24675. * @param {Node} node - The node to render a texture with.
  24676. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24677. * @param {?number} [height=null] - The height of the internal render target.
  24678. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24679. * @returns {RTTNode}
  24680. */
  24681. const convertToTexture = ( node, ...params ) => {
  24682. if ( node.isSampleNode || node.isTextureNode ) return node;
  24683. if ( node.isPassNode ) return node.getTextureNode();
  24684. return rtt( node, ...params );
  24685. };
  24686. /**
  24687. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  24688. * depth value and the camera's inverse projection matrix.
  24689. *
  24690. * @tsl
  24691. * @function
  24692. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  24693. * @param {Node<float>} depth - The fragment's depth value.
  24694. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  24695. * @return {Node<vec3>} The fragments position in view space.
  24696. */
  24697. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  24698. let clipSpacePosition;
  24699. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  24700. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  24701. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  24702. } else {
  24703. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  24704. }
  24705. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  24706. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  24707. } );
  24708. /**
  24709. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  24710. * and the camera's projection matrix
  24711. *
  24712. * @tsl
  24713. * @function
  24714. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  24715. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  24716. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  24717. */
  24718. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  24719. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  24720. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  24721. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  24722. } );
  24723. /**
  24724. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  24725. * target is available or if flat surface normals are required.
  24726. *
  24727. * @tsl
  24728. * @function
  24729. * @param {Node<vec2>} uv - The texture coordinate.
  24730. * @param {DepthTexture} depthTexture - The depth texture.
  24731. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  24732. * @return {Node<vec3>} The computed normal vector.
  24733. */
  24734. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  24735. const size = textureSize( textureLoad( depthTexture ) );
  24736. const p = ivec2( uv.mul( size ) ).toVar();
  24737. const c0 = textureLoad( depthTexture, p ).toVar();
  24738. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  24739. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  24740. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  24741. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  24742. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  24743. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  24744. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  24745. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  24746. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  24747. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  24748. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  24749. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  24750. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  24751. 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 ) ) );
  24752. 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 ) ) );
  24753. return normalize( cross( dpdx, dpdy ) );
  24754. } );
  24755. /**
  24756. * Class representing a node that samples a value using a provided callback function.
  24757. *
  24758. * @extends Node
  24759. */
  24760. class SampleNode extends Node {
  24761. /**
  24762. * Returns the type of the node.
  24763. *
  24764. * @type {string}
  24765. * @readonly
  24766. * @static
  24767. */
  24768. static get type() {
  24769. return 'SampleNode';
  24770. }
  24771. /**
  24772. * Creates an instance of SampleNode.
  24773. *
  24774. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24775. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  24776. */
  24777. constructor( callback, uvNode = null ) {
  24778. super();
  24779. this.callback = callback;
  24780. /**
  24781. * Represents the texture coordinates.
  24782. *
  24783. * @type {?Node<vec2|vec3>}
  24784. * @default null
  24785. */
  24786. this.uvNode = uvNode;
  24787. /**
  24788. * This flag can be used for type testing.
  24789. *
  24790. * @type {boolean}
  24791. * @readonly
  24792. * @default true
  24793. */
  24794. this.isSampleNode = true;
  24795. }
  24796. /**
  24797. * Sets up the node by sampling with the default UV accessor.
  24798. *
  24799. * @returns {Node} The result of the callback function when called with the UV node.
  24800. */
  24801. setup() {
  24802. return this.sample( uv$1() );
  24803. }
  24804. /**
  24805. * Calls the callback function with the provided UV node.
  24806. *
  24807. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  24808. * @returns {Node} The result of the callback function.
  24809. */
  24810. sample( uv ) {
  24811. return this.callback( uv );
  24812. }
  24813. }
  24814. /**
  24815. * Helper function to create a SampleNode wrapped as a node object.
  24816. *
  24817. * @function
  24818. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24819. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  24820. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  24821. */
  24822. const sample = ( callback, uv = null ) => nodeObject( new SampleNode( callback, nodeObject( uv ) ) );
  24823. /**
  24824. * EventNode is a node that executes a callback during specific update phases.
  24825. *
  24826. * @augments Node
  24827. */
  24828. class EventNode extends Node {
  24829. static get type() {
  24830. return 'EventNode';
  24831. }
  24832. /**
  24833. * Creates an EventNode.
  24834. *
  24835. * @param {string} eventType - The type of event
  24836. * @param {Function} callback - The callback to execute on update.
  24837. */
  24838. constructor( eventType, callback ) {
  24839. super( 'void' );
  24840. this.eventType = eventType;
  24841. this.callback = callback;
  24842. if ( eventType === EventNode.OBJECT ) {
  24843. this.updateType = NodeUpdateType.OBJECT;
  24844. } else if ( eventType === EventNode.MATERIAL ) {
  24845. this.updateType = NodeUpdateType.RENDER;
  24846. }
  24847. }
  24848. update( frame ) {
  24849. this.callback( frame );
  24850. }
  24851. }
  24852. EventNode.OBJECT = 'object';
  24853. EventNode.MATERIAL = 'material';
  24854. /**
  24855. * Helper to create an EventNode and add it to the stack.
  24856. *
  24857. * @param {string} type - The event type.
  24858. * @param {Function} callback - The callback function.
  24859. * @returns {EventNode}
  24860. */
  24861. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  24862. /**
  24863. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  24864. *
  24865. * 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.
  24866. *
  24867. * @param {Function} callback - The callback function.
  24868. * @returns {EventNode}
  24869. */
  24870. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  24871. /**
  24872. * Creates an event that triggers a function when the first object that uses the material is rendered.
  24873. *
  24874. * 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.
  24875. *
  24876. * @param {Function} callback - The callback function.
  24877. * @returns {EventNode}
  24878. */
  24879. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  24880. /**
  24881. * This special type of instanced buffer attribute is intended for compute shaders.
  24882. * In earlier three.js versions it was only possible to update attribute data
  24883. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24884. * new material system and renderer it is now possible to use compute shaders
  24885. * to compute the data for an attribute more efficiently on the GPU.
  24886. *
  24887. * The idea is to create an instance of this class and provide it as an input
  24888. * to {@link StorageBufferNode}.
  24889. *
  24890. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24891. *
  24892. * @augments InstancedBufferAttribute
  24893. */
  24894. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  24895. /**
  24896. * Constructs a new storage instanced buffer attribute.
  24897. *
  24898. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24899. * The subsequent parameters are then obsolete.
  24900. * @param {number} itemSize - The item size.
  24901. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24902. */
  24903. constructor( count, itemSize, typeClass = Float32Array ) {
  24904. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24905. super( array, itemSize );
  24906. /**
  24907. * This flag can be used for type testing.
  24908. *
  24909. * @type {boolean}
  24910. * @readonly
  24911. * @default true
  24912. */
  24913. this.isStorageInstancedBufferAttribute = true;
  24914. }
  24915. }
  24916. /**
  24917. * This special type of buffer attribute is intended for compute shaders.
  24918. * In earlier three.js versions it was only possible to update attribute data
  24919. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24920. * new material system and renderer it is now possible to use compute shaders
  24921. * to compute the data for an attribute more efficiently on the GPU.
  24922. *
  24923. * The idea is to create an instance of this class and provide it as an input
  24924. * to {@link StorageBufferNode}.
  24925. *
  24926. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24927. *
  24928. * @augments BufferAttribute
  24929. */
  24930. class StorageBufferAttribute extends BufferAttribute {
  24931. /**
  24932. * Constructs a new storage buffer attribute.
  24933. *
  24934. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24935. * The subsequent parameters are then obsolete.
  24936. * @param {number} itemSize - The item size.
  24937. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24938. */
  24939. constructor( count, itemSize, typeClass = Float32Array ) {
  24940. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24941. super( array, itemSize );
  24942. /**
  24943. * This flag can be used for type testing.
  24944. *
  24945. * @type {boolean}
  24946. * @readonly
  24947. * @default true
  24948. */
  24949. this.isStorageBufferAttribute = true;
  24950. }
  24951. }
  24952. /**
  24953. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  24954. *
  24955. * @tsl
  24956. * @function
  24957. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24958. * @param {string|Struct} [type='float'] - The data type.
  24959. * @returns {StorageBufferNode}
  24960. */
  24961. const attributeArray = ( count, type = 'float' ) => {
  24962. let itemSize, typedArray;
  24963. if ( type.isStruct === true ) {
  24964. itemSize = type.layout.getLength();
  24965. typedArray = getTypedArrayFromType( 'float' );
  24966. } else {
  24967. itemSize = getLengthFromType( type );
  24968. typedArray = getTypedArrayFromType( type );
  24969. }
  24970. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  24971. const node = storage( buffer, type, count );
  24972. return node;
  24973. };
  24974. /**
  24975. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  24976. *
  24977. * @tsl
  24978. * @function
  24979. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24980. * @param {string|Struct} [type='float'] - The data type.
  24981. * @returns {StorageBufferNode}
  24982. */
  24983. const instancedArray = ( count, type = 'float' ) => {
  24984. let itemSize, typedArray;
  24985. if ( type.isStruct === true ) {
  24986. itemSize = type.layout.getLength();
  24987. typedArray = getTypedArrayFromType( 'float' );
  24988. } else {
  24989. itemSize = getLengthFromType( type );
  24990. typedArray = getTypedArrayFromType( type );
  24991. }
  24992. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  24993. const node = storage( buffer, type, count );
  24994. return node;
  24995. };
  24996. /**
  24997. * A node for representing the uv coordinates of points.
  24998. *
  24999. * Can only be used with a WebGL backend. In WebGPU, point
  25000. * primitives always have the size of one pixel and can thus
  25001. * can't be used as sprite-like objects that display textures.
  25002. *
  25003. * @augments Node
  25004. */
  25005. class PointUVNode extends Node {
  25006. static get type() {
  25007. return 'PointUVNode';
  25008. }
  25009. /**
  25010. * Constructs a new point uv node.
  25011. */
  25012. constructor() {
  25013. super( 'vec2' );
  25014. /**
  25015. * This flag can be used for type testing.
  25016. *
  25017. * @type {boolean}
  25018. * @readonly
  25019. * @default true
  25020. */
  25021. this.isPointUVNode = true;
  25022. }
  25023. generate( /*builder*/ ) {
  25024. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  25025. }
  25026. }
  25027. /**
  25028. * TSL object that represents the uv coordinates of points.
  25029. *
  25030. * @tsl
  25031. * @type {PointUVNode}
  25032. */
  25033. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  25034. const _e1 = /*@__PURE__*/ new Euler();
  25035. const _m1 = /*@__PURE__*/ new Matrix4();
  25036. /**
  25037. * This module allows access to a collection of scene properties. The following predefined TSL objects
  25038. * are available for easier use:
  25039. *
  25040. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  25041. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  25042. * - `backgroundRotation`: A node that represents the scene's background rotation.
  25043. *
  25044. * @augments Node
  25045. */
  25046. class SceneNode extends Node {
  25047. static get type() {
  25048. return 'SceneNode';
  25049. }
  25050. /**
  25051. * Constructs a new scene node.
  25052. *
  25053. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  25054. * @param {?Scene} [scene=null] - A reference to the scene.
  25055. */
  25056. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  25057. super();
  25058. /**
  25059. * The scope defines the type of scene property that is accessed.
  25060. *
  25061. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  25062. */
  25063. this.scope = scope;
  25064. /**
  25065. * A reference to the scene that is going to be accessed.
  25066. *
  25067. * @type {?Scene}
  25068. * @default null
  25069. */
  25070. this.scene = scene;
  25071. }
  25072. /**
  25073. * Depending on the scope, the method returns a different type of node that represents
  25074. * the respective scene property.
  25075. *
  25076. * @param {NodeBuilder} builder - The current node builder.
  25077. * @return {Node} The output node.
  25078. */
  25079. setup( builder ) {
  25080. const scope = this.scope;
  25081. const scene = this.scene !== null ? this.scene : builder.scene;
  25082. let output;
  25083. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  25084. output = reference( 'backgroundBlurriness', 'float', scene );
  25085. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  25086. output = reference( 'backgroundIntensity', 'float', scene );
  25087. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  25088. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  25089. const background = scene.background;
  25090. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  25091. _e1.copy( scene.backgroundRotation );
  25092. // accommodate left-handed frame
  25093. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  25094. _m1.makeRotationFromEuler( _e1 );
  25095. } else {
  25096. _m1.identity();
  25097. }
  25098. return _m1;
  25099. } );
  25100. } else {
  25101. error( 'SceneNode: Unknown scope:', scope );
  25102. }
  25103. return output;
  25104. }
  25105. }
  25106. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  25107. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  25108. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  25109. /**
  25110. * TSL object that represents the scene's background blurriness.
  25111. *
  25112. * @tsl
  25113. * @type {SceneNode}
  25114. */
  25115. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  25116. /**
  25117. * TSL object that represents the scene's background intensity.
  25118. *
  25119. * @tsl
  25120. * @type {SceneNode}
  25121. */
  25122. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  25123. /**
  25124. * TSL object that represents the scene's background rotation.
  25125. *
  25126. * @tsl
  25127. * @type {SceneNode}
  25128. */
  25129. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  25130. /**
  25131. * This special version of a texture node can be used to
  25132. * write data into a storage texture with a compute shader.
  25133. *
  25134. * ```js
  25135. * const storageTexture = new THREE.StorageTexture( width, height );
  25136. *
  25137. * const computeTexture = Fn( ( { storageTexture } ) => {
  25138. *
  25139. * const posX = instanceIndex.mod( width );
  25140. * const posY = instanceIndex.div( width );
  25141. * const indexUV = uvec2( posX, posY );
  25142. *
  25143. * // generate RGB values
  25144. *
  25145. * const r = 1;
  25146. * const g = 1;
  25147. * const b = 1;
  25148. *
  25149. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  25150. *
  25151. * } );
  25152. *
  25153. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  25154. * renderer.computeAsync( computeNode );
  25155. * ```
  25156. *
  25157. * This node can only be used with a WebGPU backend.
  25158. *
  25159. * @augments TextureNode
  25160. */
  25161. class StorageTextureNode extends TextureNode {
  25162. static get type() {
  25163. return 'StorageTextureNode';
  25164. }
  25165. /**
  25166. * Constructs a new storage texture node.
  25167. *
  25168. * @param {StorageTexture} value - The storage texture.
  25169. * @param {Node<vec2|vec3>} uvNode - The uv node.
  25170. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25171. */
  25172. constructor( value, uvNode, storeNode = null ) {
  25173. super( value, uvNode );
  25174. /**
  25175. * The value node that should be stored in the texture.
  25176. *
  25177. * @type {?Node}
  25178. * @default null
  25179. */
  25180. this.storeNode = storeNode;
  25181. /**
  25182. * The mip level to write to for storage textures.
  25183. *
  25184. * @type {number}
  25185. * @default 0
  25186. */
  25187. this.mipLevel = 0;
  25188. /**
  25189. * This flag can be used for type testing.
  25190. *
  25191. * @type {boolean}
  25192. * @readonly
  25193. * @default true
  25194. */
  25195. this.isStorageTextureNode = true;
  25196. /**
  25197. * The access type of the texture node.
  25198. *
  25199. * @type {string}
  25200. * @default 'writeOnly'
  25201. */
  25202. this.access = NodeAccess.WRITE_ONLY;
  25203. }
  25204. /**
  25205. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  25206. *
  25207. * @param {NodeBuilder} builder - The current node builder.
  25208. * @return {string} The input type.
  25209. */
  25210. getInputType( /*builder*/ ) {
  25211. return 'storageTexture';
  25212. }
  25213. setup( builder ) {
  25214. super.setup( builder );
  25215. const properties = builder.getNodeProperties( this );
  25216. properties.storeNode = this.storeNode;
  25217. return properties;
  25218. }
  25219. /**
  25220. * Defines the node access.
  25221. *
  25222. * @param {string} value - The node access.
  25223. * @return {StorageTextureNode} A reference to this node.
  25224. */
  25225. setAccess( value ) {
  25226. this.access = value;
  25227. return this;
  25228. }
  25229. /**
  25230. * Sets the mip level to write to.
  25231. *
  25232. * @param {number} level - The mip level.
  25233. * @return {StorageTextureNode} A reference to this node.
  25234. */
  25235. setMipLevel( level ) {
  25236. this.mipLevel = level;
  25237. return this;
  25238. }
  25239. /**
  25240. * Generates the code snippet of the storage node. If no `storeNode`
  25241. * is defined, the texture node is generated as normal texture.
  25242. *
  25243. * @param {NodeBuilder} builder - The current node builder.
  25244. * @param {string} output - The current output.
  25245. * @return {string} The generated code snippet.
  25246. */
  25247. generate( builder, output ) {
  25248. let snippet;
  25249. if ( this.storeNode !== null ) {
  25250. snippet = this.generateStore( builder );
  25251. } else {
  25252. snippet = super.generate( builder, output );
  25253. }
  25254. return snippet;
  25255. }
  25256. /**
  25257. * Convenience method for configuring a read/write node access.
  25258. *
  25259. * @return {StorageTextureNode} A reference to this node.
  25260. */
  25261. toReadWrite() {
  25262. return this.setAccess( NodeAccess.READ_WRITE );
  25263. }
  25264. /**
  25265. * Convenience method for configuring a read-only node access.
  25266. *
  25267. * @return {StorageTextureNode} A reference to this node.
  25268. */
  25269. toReadOnly() {
  25270. return this.setAccess( NodeAccess.READ_ONLY );
  25271. }
  25272. /**
  25273. * Convenience method for configuring a write-only node access.
  25274. *
  25275. * @return {StorageTextureNode} A reference to this node.
  25276. */
  25277. toWriteOnly() {
  25278. return this.setAccess( NodeAccess.WRITE_ONLY );
  25279. }
  25280. /**
  25281. * Generates the code snippet of the storage texture node.
  25282. *
  25283. * @param {NodeBuilder} builder - The current node builder.
  25284. */
  25285. generateStore( builder ) {
  25286. const properties = builder.getNodeProperties( this );
  25287. const { uvNode, storeNode, depthNode } = properties;
  25288. const textureProperty = super.generate( builder, 'property' );
  25289. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  25290. const storeSnippet = storeNode.build( builder, 'vec4' );
  25291. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  25292. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  25293. builder.addLineFlowCode( snippet, this );
  25294. }
  25295. clone() {
  25296. const newNode = super.clone();
  25297. newNode.storeNode = this.storeNode;
  25298. newNode.mipLevel = this.mipLevel;
  25299. return newNode;
  25300. }
  25301. }
  25302. /**
  25303. * TSL function for creating a storage texture node.
  25304. *
  25305. * @tsl
  25306. * @function
  25307. * @param {StorageTexture} value - The storage texture.
  25308. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  25309. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25310. * @returns {StorageTextureNode}
  25311. */
  25312. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  25313. /**
  25314. * TODO: Explain difference to `storageTexture()`.
  25315. *
  25316. * @tsl
  25317. * @function
  25318. * @param {StorageTexture} value - The storage texture.
  25319. * @param {Node<vec2|vec3>} uvNode - The uv node.
  25320. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25321. * @returns {StorageTextureNode}
  25322. */
  25323. const textureStore = ( value, uvNode, storeNode ) => {
  25324. const node = storageTexture( value, uvNode, storeNode );
  25325. if ( storeNode !== null ) node.toStack();
  25326. return node;
  25327. };
  25328. const normal = Fn( ( { texture, uv } ) => {
  25329. const epsilon = 0.0001;
  25330. const ret = vec3().toVar();
  25331. If( uv.x.lessThan( epsilon ), () => {
  25332. ret.assign( vec3( 1, 0, 0 ) );
  25333. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  25334. ret.assign( vec3( 0, 1, 0 ) );
  25335. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  25336. ret.assign( vec3( 0, 0, 1 ) );
  25337. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  25338. ret.assign( vec3( -1, 0, 0 ) );
  25339. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  25340. ret.assign( vec3( 0, -1, 0 ) );
  25341. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  25342. ret.assign( vec3( 0, 0, -1 ) );
  25343. } ).Else( () => {
  25344. const step = 0.01;
  25345. 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 );
  25346. 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 );
  25347. 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 );
  25348. ret.assign( vec3( x, y, z ) );
  25349. } );
  25350. return ret.normalize();
  25351. } );
  25352. /**
  25353. * This type of uniform node represents a 3D texture.
  25354. *
  25355. * @augments TextureNode
  25356. */
  25357. class Texture3DNode extends TextureNode {
  25358. static get type() {
  25359. return 'Texture3DNode';
  25360. }
  25361. /**
  25362. * Constructs a new 3D texture node.
  25363. *
  25364. * @param {Data3DTexture} value - The 3D texture.
  25365. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  25366. * @param {?Node<int>} [levelNode=null] - The level node.
  25367. */
  25368. constructor( value, uvNode = null, levelNode = null ) {
  25369. super( value, uvNode, levelNode );
  25370. /**
  25371. * This flag can be used for type testing.
  25372. *
  25373. * @type {boolean}
  25374. * @readonly
  25375. * @default true
  25376. */
  25377. this.isTexture3DNode = true;
  25378. }
  25379. /**
  25380. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  25381. *
  25382. * @param {NodeBuilder} builder - The current node builder.
  25383. * @return {string} The input type.
  25384. */
  25385. getInputType( /*builder*/ ) {
  25386. return 'texture3D';
  25387. }
  25388. /**
  25389. * Returns a default uv node which is in context of 3D textures a three-dimensional
  25390. * uv node.
  25391. *
  25392. * @return {Node<vec3>} The default uv node.
  25393. */
  25394. getDefaultUV() {
  25395. return vec3( 0.5, 0.5, 0.5 );
  25396. }
  25397. /**
  25398. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  25399. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  25400. *
  25401. * @param {boolean} value - The update toggle.
  25402. */
  25403. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  25404. /**
  25405. * Overwrites the default implementation to return the unmodified uv node.
  25406. *
  25407. * @param {NodeBuilder} builder - The current node builder.
  25408. * @param {Node} uvNode - The uv node to setup.
  25409. * @return {Node} The unmodified uv node.
  25410. */
  25411. setupUV( builder, uvNode ) {
  25412. const texture = this.value;
  25413. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  25414. if ( this.sampler ) {
  25415. uvNode = uvNode.flipY();
  25416. } else {
  25417. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  25418. }
  25419. }
  25420. return uvNode;
  25421. }
  25422. /**
  25423. * Generates the uv code snippet.
  25424. *
  25425. * @param {NodeBuilder} builder - The current node builder.
  25426. * @param {Node} uvNode - The uv node to generate code for.
  25427. * @return {string} The generated code snippet.
  25428. */
  25429. generateUV( builder, uvNode ) {
  25430. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  25431. }
  25432. /**
  25433. * Generates the offset code snippet.
  25434. *
  25435. * @param {NodeBuilder} builder - The current node builder.
  25436. * @param {Node} offsetNode - The offset node to generate code for.
  25437. * @return {string} The generated code snippet.
  25438. */
  25439. generateOffset( builder, offsetNode ) {
  25440. return offsetNode.build( builder, 'ivec3' );
  25441. }
  25442. /**
  25443. * TODO.
  25444. *
  25445. * @param {Node<vec3>} uvNode - The uv node .
  25446. * @return {Node<vec3>} TODO.
  25447. */
  25448. normal( uvNode ) {
  25449. return normal( { texture: this, uv: uvNode } );
  25450. }
  25451. }
  25452. /**
  25453. * TSL function for creating a 3D texture node.
  25454. *
  25455. * @tsl
  25456. * @function
  25457. * @param {Data3DTexture} value - The 3D texture.
  25458. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  25459. * @param {?Node<int>} [levelNode=null] - The level node.
  25460. * @returns {Texture3DNode}
  25461. */
  25462. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  25463. /**
  25464. * A special type of reference node that allows to link values in
  25465. * `userData` fields to node objects.
  25466. * ```js
  25467. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  25468. *
  25469. * const material = new THREE.SpriteNodeMaterial();
  25470. * material.rotationNode = userData( 'rotation', 'float' );
  25471. * ```
  25472. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  25473. * will automatically be updated when the `rotation` user data field changes.
  25474. *
  25475. * @augments ReferenceNode
  25476. */
  25477. class UserDataNode extends ReferenceNode {
  25478. static get type() {
  25479. return 'UserDataNode';
  25480. }
  25481. /**
  25482. * Constructs a new user data node.
  25483. *
  25484. * @param {string} property - The property name that should be referenced by the node.
  25485. * @param {string} inputType - The node data type of the reference.
  25486. * @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.
  25487. */
  25488. constructor( property, inputType, userData = null ) {
  25489. super( property, inputType, userData );
  25490. /**
  25491. * A reference to the `userData` object. If not provided, the `userData`
  25492. * property of the 3D object that uses the node material is evaluated.
  25493. *
  25494. * @type {?Object}
  25495. * @default null
  25496. */
  25497. this.userData = userData;
  25498. }
  25499. /**
  25500. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  25501. * `userData` field.
  25502. *
  25503. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  25504. * @return {Object} A reference to the `userData` field.
  25505. */
  25506. updateReference( state ) {
  25507. this.reference = this.userData !== null ? this.userData : state.object.userData;
  25508. return this.reference;
  25509. }
  25510. }
  25511. /**
  25512. * TSL function for creating a user data node.
  25513. *
  25514. * @tsl
  25515. * @function
  25516. * @param {string} name - The property name that should be referenced by the node.
  25517. * @param {string} inputType - The node data type of the reference.
  25518. * @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.
  25519. * @returns {UserDataNode}
  25520. */
  25521. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  25522. const _objectData = new WeakMap();
  25523. /**
  25524. * A node for representing motion or velocity vectors. Foundation
  25525. * for advanced post processing effects like motion blur or TRAA.
  25526. *
  25527. * The node keeps track of the model, view and projection matrices
  25528. * of the previous frame and uses them to compute offsets in NDC space.
  25529. * These offsets represent the final velocity.
  25530. *
  25531. * @augments TempNode
  25532. */
  25533. class VelocityNode extends TempNode {
  25534. static get type() {
  25535. return 'VelocityNode';
  25536. }
  25537. /**
  25538. * Constructs a new vertex color node.
  25539. */
  25540. constructor() {
  25541. super( 'vec2' );
  25542. /**
  25543. * The current projection matrix.
  25544. *
  25545. * @type {?Matrix4}
  25546. * @default null
  25547. */
  25548. this.projectionMatrix = null;
  25549. /**
  25550. * Overwritten since velocity nodes are updated per object.
  25551. *
  25552. * @type {string}
  25553. * @default 'object'
  25554. */
  25555. this.updateType = NodeUpdateType.OBJECT;
  25556. /**
  25557. * Overwritten since velocity nodes save data after the update.
  25558. *
  25559. * @type {string}
  25560. * @default 'object'
  25561. */
  25562. this.updateAfterType = NodeUpdateType.OBJECT;
  25563. /**
  25564. * Uniform node representing the previous model matrix in world space.
  25565. *
  25566. * @type {UniformNode<mat4>}
  25567. * @default null
  25568. */
  25569. this.previousModelWorldMatrix = uniform( new Matrix4() );
  25570. /**
  25571. * Uniform node representing the previous projection matrix.
  25572. *
  25573. * @type {UniformNode<mat4>}
  25574. * @default null
  25575. */
  25576. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  25577. /**
  25578. * Uniform node representing the previous view matrix.
  25579. *
  25580. * @type {UniformNode<mat4>}
  25581. * @default null
  25582. */
  25583. this.previousCameraViewMatrix = uniform( new Matrix4() );
  25584. }
  25585. /**
  25586. * Sets the given projection matrix.
  25587. *
  25588. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  25589. */
  25590. setProjectionMatrix( projectionMatrix ) {
  25591. this.projectionMatrix = projectionMatrix;
  25592. }
  25593. /**
  25594. * Updates velocity specific uniforms.
  25595. *
  25596. * @param {NodeFrame} frame - A reference to the current node frame.
  25597. */
  25598. update( { frameId, camera, object } ) {
  25599. const previousModelMatrix = getPreviousMatrix( object );
  25600. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  25601. //
  25602. const cameraData = getData( camera );
  25603. if ( cameraData.frameId !== frameId ) {
  25604. cameraData.frameId = frameId;
  25605. if ( cameraData.previousProjectionMatrix === undefined ) {
  25606. cameraData.previousProjectionMatrix = new Matrix4();
  25607. cameraData.previousCameraViewMatrix = new Matrix4();
  25608. cameraData.currentProjectionMatrix = new Matrix4();
  25609. cameraData.currentCameraViewMatrix = new Matrix4();
  25610. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  25611. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  25612. } else {
  25613. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  25614. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  25615. }
  25616. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  25617. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  25618. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  25619. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  25620. }
  25621. }
  25622. /**
  25623. * Overwritten to updated velocity specific uniforms.
  25624. *
  25625. * @param {NodeFrame} frame - A reference to the current node frame.
  25626. */
  25627. updateAfter( { object } ) {
  25628. getPreviousMatrix( object ).copy( object.matrixWorld );
  25629. }
  25630. /**
  25631. * Implements the velocity computation based on the previous and current vertex data.
  25632. *
  25633. * @param {NodeBuilder} builder - A reference to the current node builder.
  25634. * @return {Node<vec2>} The motion vector.
  25635. */
  25636. setup( /*builder*/ ) {
  25637. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  25638. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  25639. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  25640. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  25641. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  25642. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  25643. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  25644. return velocity;
  25645. }
  25646. }
  25647. function getData( object ) {
  25648. let objectData = _objectData.get( object );
  25649. if ( objectData === undefined ) {
  25650. objectData = {};
  25651. _objectData.set( object, objectData );
  25652. }
  25653. return objectData;
  25654. }
  25655. function getPreviousMatrix( object, index = 0 ) {
  25656. const objectData = getData( object );
  25657. let matrix = objectData[ index ];
  25658. if ( matrix === undefined ) {
  25659. objectData[ index ] = matrix = new Matrix4();
  25660. objectData[ index ].copy( object.matrixWorld );
  25661. }
  25662. return matrix;
  25663. }
  25664. /**
  25665. * TSL object that represents the velocity of a render pass.
  25666. *
  25667. * @tsl
  25668. * @type {VelocityNode}
  25669. */
  25670. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  25671. /**
  25672. * Computes a grayscale value for the given RGB color value.
  25673. *
  25674. * @tsl
  25675. * @function
  25676. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  25677. * @return {Node<vec3>} The grayscale color.
  25678. */
  25679. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  25680. return luminance( color.rgb );
  25681. } );
  25682. /**
  25683. * Super-saturates or desaturates the given RGB color.
  25684. *
  25685. * @tsl
  25686. * @function
  25687. * @param {Node<vec3>} color - The input color.
  25688. * @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.
  25689. * @return {Node<vec3>} The saturated color.
  25690. */
  25691. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25692. return adjustment.mix( luminance( color.rgb ), color.rgb );
  25693. } );
  25694. /**
  25695. * Selectively enhance the intensity of less saturated RGB colors. Can result
  25696. * in a more natural and visually appealing image with enhanced color depth
  25697. * compared to {@link ColorAdjustment#saturation}.
  25698. *
  25699. * @tsl
  25700. * @function
  25701. * @param {Node<vec3>} color - The input color.
  25702. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  25703. * @return {Node<vec3>} The updated color.
  25704. */
  25705. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25706. const average = add( color.r, color.g, color.b ).div( 3.0 );
  25707. const mx = color.r.max( color.g.max( color.b ) );
  25708. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  25709. return mix( color.rgb, mx, amt );
  25710. } );
  25711. /**
  25712. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  25713. *
  25714. * @tsl
  25715. * @function
  25716. * @param {Node<vec3>} color - The input color.
  25717. * @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.
  25718. * @return {Node<vec3>} The updated color.
  25719. */
  25720. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25721. const k = vec3( 0.57735, 0.57735, 0.57735 );
  25722. const cosAngle = adjustment.cos();
  25723. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  25724. } );
  25725. /**
  25726. * Computes the luminance for the given RGB color value.
  25727. *
  25728. * @tsl
  25729. * @function
  25730. * @param {Node<vec3>} color - The color value to compute the luminance for.
  25731. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  25732. * @return {Node<float>} The luminance.
  25733. */
  25734. const luminance = (
  25735. color,
  25736. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  25737. ) => dot( color, luminanceCoefficients );
  25738. /**
  25739. * Color Decision List (CDL) v1.2
  25740. *
  25741. * Compact representation of color grading information, defined by slope, offset, power, and
  25742. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  25743. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  25744. *
  25745. * @tsl
  25746. * @function
  25747. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  25748. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  25749. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  25750. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  25751. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  25752. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  25753. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  25754. *
  25755. * References:
  25756. * - ASC CDL v1.2
  25757. * - {@link https://blender.stackexchange.com/a/55239/43930}
  25758. * - {@link https://docs.acescentral.com/specifications/acescc/}
  25759. */
  25760. const cdl = /*@__PURE__*/ Fn( ( [
  25761. color,
  25762. slope = vec3( 1 ),
  25763. offset = vec3( 0 ),
  25764. power = vec3( 1 ),
  25765. saturation = float( 1 ),
  25766. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  25767. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  25768. ] ) => {
  25769. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  25770. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  25771. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  25772. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  25773. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  25774. const pv = v.pow( power ).toVar();
  25775. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  25776. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  25777. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  25778. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  25779. return vec4( v.rgb, color.a );
  25780. } );
  25781. /**
  25782. * Represents a posterize effect which reduces the number of colors
  25783. * in an image, resulting in a more blocky and stylized appearance.
  25784. *
  25785. * @augments TempNode
  25786. */
  25787. class PosterizeNode extends TempNode {
  25788. static get type() {
  25789. return 'PosterizeNode';
  25790. }
  25791. /**
  25792. * Constructs a new posterize node.
  25793. *
  25794. * @param {Node} sourceNode - The input color.
  25795. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25796. */
  25797. constructor( sourceNode, stepsNode ) {
  25798. super();
  25799. /**
  25800. * The input color.
  25801. *
  25802. * @type {Node}
  25803. */
  25804. this.sourceNode = sourceNode;
  25805. /**
  25806. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25807. *
  25808. * @type {Node}
  25809. */
  25810. this.stepsNode = stepsNode;
  25811. }
  25812. setup() {
  25813. const { sourceNode, stepsNode } = this;
  25814. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  25815. }
  25816. }
  25817. /**
  25818. * TSL function for creating a posterize node.
  25819. *
  25820. * @tsl
  25821. * @function
  25822. * @param {Node} sourceNode - The input color.
  25823. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25824. * @returns {PosterizeNode}
  25825. */
  25826. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  25827. const _size = /*@__PURE__*/ new Vector2();
  25828. /**
  25829. * Represents the texture of a pass node.
  25830. *
  25831. * @augments TextureNode
  25832. */
  25833. class PassTextureNode extends TextureNode {
  25834. static get type() {
  25835. return 'PassTextureNode';
  25836. }
  25837. /**
  25838. * Constructs a new pass texture node.
  25839. *
  25840. * @param {PassNode} passNode - The pass node.
  25841. * @param {Texture} texture - The output texture.
  25842. */
  25843. constructor( passNode, texture ) {
  25844. super( texture );
  25845. /**
  25846. * A reference to the pass node.
  25847. *
  25848. * @type {PassNode}
  25849. */
  25850. this.passNode = passNode;
  25851. this.setUpdateMatrix( false );
  25852. }
  25853. setup( builder ) {
  25854. this.passNode.build( builder );
  25855. return super.setup( builder );
  25856. }
  25857. clone() {
  25858. return new this.constructor( this.passNode, this.value );
  25859. }
  25860. }
  25861. /**
  25862. * An extension of `PassTextureNode` which allows to manage more than one
  25863. * internal texture. Relevant for the `getPreviousTexture()` related API.
  25864. *
  25865. * @augments PassTextureNode
  25866. */
  25867. class PassMultipleTextureNode extends PassTextureNode {
  25868. static get type() {
  25869. return 'PassMultipleTextureNode';
  25870. }
  25871. /**
  25872. * Constructs a new pass texture node.
  25873. *
  25874. * @param {PassNode} passNode - The pass node.
  25875. * @param {string} textureName - The output texture name.
  25876. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  25877. */
  25878. constructor( passNode, textureName, previousTexture = false ) {
  25879. // null is passed to the super call since this class does not
  25880. // use an external texture for rendering pass data into. Instead
  25881. // the texture is managed by the pass node itself
  25882. super( passNode, null );
  25883. /**
  25884. * The output texture name.
  25885. *
  25886. * @type {string}
  25887. */
  25888. this.textureName = textureName;
  25889. /**
  25890. * Whether previous frame data should be used or not.
  25891. *
  25892. * @type {boolean}
  25893. */
  25894. this.previousTexture = previousTexture;
  25895. }
  25896. /**
  25897. * Updates the texture reference of this node.
  25898. */
  25899. updateTexture() {
  25900. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  25901. }
  25902. setup( builder ) {
  25903. this.updateTexture();
  25904. return super.setup( builder );
  25905. }
  25906. clone() {
  25907. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  25908. newNode.uvNode = this.uvNode;
  25909. newNode.levelNode = this.levelNode;
  25910. newNode.biasNode = this.biasNode;
  25911. newNode.sampler = this.sampler;
  25912. newNode.depthNode = this.depthNode;
  25913. newNode.compareNode = this.compareNode;
  25914. newNode.gradNode = this.gradNode;
  25915. newNode.offsetNode = this.offsetNode;
  25916. return newNode;
  25917. }
  25918. }
  25919. /**
  25920. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  25921. * This pass produces a render for the given scene and camera and can provide multiple outputs
  25922. * via MRT for further processing.
  25923. *
  25924. * ```js
  25925. * const postProcessing = new PostProcessing( renderer );
  25926. *
  25927. * const scenePass = pass( scene, camera );
  25928. *
  25929. * postProcessing.outputNode = scenePass;
  25930. * ```
  25931. *
  25932. * @augments TempNode
  25933. */
  25934. class PassNode extends TempNode {
  25935. static get type() {
  25936. return 'PassNode';
  25937. }
  25938. /**
  25939. * Constructs a new pass node.
  25940. *
  25941. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  25942. * @param {Scene} scene - A reference to the scene.
  25943. * @param {Camera} camera - A reference to the camera.
  25944. * @param {Object} options - Options for the internal render target.
  25945. */
  25946. constructor( scope, scene, camera, options = {} ) {
  25947. super( 'vec4' );
  25948. /**
  25949. * The scope of the pass. The scope determines whether the node outputs color or depth.
  25950. *
  25951. * @type {('color'|'depth')}
  25952. */
  25953. this.scope = scope;
  25954. /**
  25955. * A reference to the scene.
  25956. *
  25957. * @type {Scene}
  25958. */
  25959. this.scene = scene;
  25960. /**
  25961. * A reference to the camera.
  25962. *
  25963. * @type {Camera}
  25964. */
  25965. this.camera = camera;
  25966. /**
  25967. * Options for the internal render target.
  25968. *
  25969. * @type {Object}
  25970. */
  25971. this.options = options;
  25972. /**
  25973. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  25974. *
  25975. * @private
  25976. * @type {number}
  25977. * @default 1
  25978. */
  25979. this._pixelRatio = 1;
  25980. /**
  25981. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  25982. * @private
  25983. * @type {number}
  25984. * @default 1
  25985. */
  25986. this._width = 1;
  25987. /**
  25988. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  25989. * @private
  25990. * @type {number}
  25991. * @default 1
  25992. */
  25993. this._height = 1;
  25994. const depthTexture = new DepthTexture();
  25995. depthTexture.isRenderTargetTexture = true;
  25996. //depthTexture.type = FloatType;
  25997. depthTexture.name = 'depth';
  25998. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  25999. renderTarget.texture.name = 'output';
  26000. renderTarget.depthTexture = depthTexture;
  26001. /**
  26002. * The pass's render target.
  26003. *
  26004. * @type {RenderTarget}
  26005. */
  26006. this.renderTarget = renderTarget;
  26007. /**
  26008. * A dictionary holding the internal result textures.
  26009. *
  26010. * @private
  26011. * @type {Object<string, Texture>}
  26012. */
  26013. this._textures = {
  26014. output: renderTarget.texture,
  26015. depth: depthTexture
  26016. };
  26017. /**
  26018. * A dictionary holding the internal texture nodes.
  26019. *
  26020. * @private
  26021. * @type {Object<string, TextureNode>}
  26022. */
  26023. this._textureNodes = {};
  26024. /**
  26025. * A dictionary holding the internal depth nodes.
  26026. *
  26027. * @private
  26028. * @type {Object}
  26029. */
  26030. this._linearDepthNodes = {};
  26031. /**
  26032. * A dictionary holding the internal viewZ nodes.
  26033. *
  26034. * @private
  26035. * @type {Object}
  26036. */
  26037. this._viewZNodes = {};
  26038. /**
  26039. * A dictionary holding the texture data of the previous frame.
  26040. * Used for computing velocity/motion vectors.
  26041. *
  26042. * @private
  26043. * @type {Object<string, Texture>}
  26044. */
  26045. this._previousTextures = {};
  26046. /**
  26047. * A dictionary holding the texture nodes of the previous frame.
  26048. * Used for computing velocity/motion vectors.
  26049. *
  26050. * @private
  26051. * @type {Object<string, TextureNode>}
  26052. */
  26053. this._previousTextureNodes = {};
  26054. /**
  26055. * The `near` property of the camera as a uniform.
  26056. *
  26057. * @private
  26058. * @type {UniformNode}
  26059. */
  26060. this._cameraNear = uniform( 0 );
  26061. /**
  26062. * The `far` property of the camera as a uniform.
  26063. *
  26064. * @private
  26065. * @type {UniformNode}
  26066. */
  26067. this._cameraFar = uniform( 0 );
  26068. /**
  26069. * A MRT node configuring the MRT settings.
  26070. *
  26071. * @private
  26072. * @type {?MRTNode}
  26073. * @default null
  26074. */
  26075. this._mrt = null;
  26076. /**
  26077. * Layer object for configuring the camera that is used
  26078. * to produce the pass.
  26079. *
  26080. * @private
  26081. * @type {?Layers}
  26082. * @default null
  26083. */
  26084. this._layers = null;
  26085. /**
  26086. * Scales the resolution of the internal render target.
  26087. *
  26088. * @private
  26089. * @type {number}
  26090. * @default 1
  26091. */
  26092. this._resolutionScale = 1;
  26093. /**
  26094. * Custom viewport definition.
  26095. *
  26096. * @private
  26097. * @type {?Vector4}
  26098. * @default null
  26099. */
  26100. this._viewport = null;
  26101. /**
  26102. * Custom scissor definition.
  26103. *
  26104. * @private
  26105. * @type {?Vector4}
  26106. * @default null
  26107. */
  26108. this._scissor = null;
  26109. /**
  26110. * This flag can be used for type testing.
  26111. *
  26112. * @type {boolean}
  26113. * @readonly
  26114. * @default true
  26115. */
  26116. this.isPassNode = true;
  26117. /**
  26118. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  26119. * scene once per frame in its {@link PassNode#updateBefore} method.
  26120. *
  26121. * @type {string}
  26122. * @default 'frame'
  26123. */
  26124. this.updateBeforeType = NodeUpdateType.FRAME;
  26125. /**
  26126. * This flag is used for global cache.
  26127. *
  26128. * @type {boolean}
  26129. * @default true
  26130. */
  26131. this.global = true;
  26132. }
  26133. /**
  26134. * Sets the resolution scale for the pass.
  26135. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  26136. *
  26137. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  26138. * @return {PassNode} A reference to this pass.
  26139. */
  26140. setResolutionScale( resolutionScale ) {
  26141. this._resolutionScale = resolutionScale;
  26142. return this;
  26143. }
  26144. /**
  26145. * Gets the current resolution scale of the pass.
  26146. *
  26147. * @return {number} The current resolution scale. A value of `1` means full resolution.
  26148. */
  26149. getResolutionScale() {
  26150. return this._resolutionScale;
  26151. }
  26152. /**
  26153. * Sets the resolution for the pass.
  26154. * The resolution is a factor that is multiplied with the renderer's width and height.
  26155. *
  26156. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  26157. * @return {PassNode} A reference to this pass.
  26158. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  26159. */
  26160. setResolution( resolution ) { // @deprecated, r181
  26161. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  26162. return this.setResolutionScale( resolution );
  26163. }
  26164. /**
  26165. * Gets the current resolution of the pass.
  26166. *
  26167. * @return {number} The current resolution. A value of `1` means full resolution.
  26168. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  26169. */
  26170. getResolution() { // @deprecated, r181
  26171. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  26172. return this.getResolutionScale();
  26173. }
  26174. /**
  26175. * Sets the layer configuration that should be used when rendering the pass.
  26176. *
  26177. * @param {Layers} layers - The layers object to set.
  26178. * @return {PassNode} A reference to this pass.
  26179. */
  26180. setLayers( layers ) {
  26181. this._layers = layers;
  26182. return this;
  26183. }
  26184. /**
  26185. * Gets the current layer configuration of the pass.
  26186. *
  26187. * @return {?Layers} .
  26188. */
  26189. getLayers() {
  26190. return this._layers;
  26191. }
  26192. /**
  26193. * Sets the given MRT node to setup MRT for this pass.
  26194. *
  26195. * @param {MRTNode} mrt - The MRT object.
  26196. * @return {PassNode} A reference to this pass.
  26197. */
  26198. setMRT( mrt ) {
  26199. this._mrt = mrt;
  26200. return this;
  26201. }
  26202. /**
  26203. * Returns the current MRT node.
  26204. *
  26205. * @return {MRTNode} The current MRT node.
  26206. */
  26207. getMRT() {
  26208. return this._mrt;
  26209. }
  26210. /**
  26211. * Returns the texture for the given output name.
  26212. *
  26213. * @param {string} name - The output name to get the texture for.
  26214. * @return {Texture} The texture.
  26215. */
  26216. getTexture( name ) {
  26217. let texture = this._textures[ name ];
  26218. if ( texture === undefined ) {
  26219. const refTexture = this.renderTarget.texture;
  26220. texture = refTexture.clone();
  26221. texture.name = name;
  26222. this._textures[ name ] = texture;
  26223. this.renderTarget.textures.push( texture );
  26224. }
  26225. return texture;
  26226. }
  26227. /**
  26228. * Returns the texture holding the data of the previous frame for the given output name.
  26229. *
  26230. * @param {string} name - The output name to get the texture for.
  26231. * @return {Texture} The texture holding the data of the previous frame.
  26232. */
  26233. getPreviousTexture( name ) {
  26234. let texture = this._previousTextures[ name ];
  26235. if ( texture === undefined ) {
  26236. texture = this.getTexture( name ).clone();
  26237. this._previousTextures[ name ] = texture;
  26238. }
  26239. return texture;
  26240. }
  26241. /**
  26242. * Switches current and previous textures for the given output name.
  26243. *
  26244. * @param {string} name - The output name.
  26245. */
  26246. toggleTexture( name ) {
  26247. const prevTexture = this._previousTextures[ name ];
  26248. if ( prevTexture !== undefined ) {
  26249. const texture = this._textures[ name ];
  26250. const index = this.renderTarget.textures.indexOf( texture );
  26251. this.renderTarget.textures[ index ] = prevTexture;
  26252. this._textures[ name ] = prevTexture;
  26253. this._previousTextures[ name ] = texture;
  26254. this._textureNodes[ name ].updateTexture();
  26255. this._previousTextureNodes[ name ].updateTexture();
  26256. }
  26257. }
  26258. /**
  26259. * Returns the texture node for the given output name.
  26260. *
  26261. * @param {string} [name='output'] - The output name to get the texture node for.
  26262. * @return {TextureNode} The texture node.
  26263. */
  26264. getTextureNode( name = 'output' ) {
  26265. let textureNode = this._textureNodes[ name ];
  26266. if ( textureNode === undefined ) {
  26267. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  26268. textureNode.updateTexture();
  26269. this._textureNodes[ name ] = textureNode;
  26270. }
  26271. return textureNode;
  26272. }
  26273. /**
  26274. * Returns the previous texture node for the given output name.
  26275. *
  26276. * @param {string} [name='output'] - The output name to get the previous texture node for.
  26277. * @return {TextureNode} The previous texture node.
  26278. */
  26279. getPreviousTextureNode( name = 'output' ) {
  26280. let textureNode = this._previousTextureNodes[ name ];
  26281. if ( textureNode === undefined ) {
  26282. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  26283. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  26284. textureNode.updateTexture();
  26285. this._previousTextureNodes[ name ] = textureNode;
  26286. }
  26287. return textureNode;
  26288. }
  26289. /**
  26290. * Returns a viewZ node of this pass.
  26291. *
  26292. * @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.
  26293. * @return {Node} The viewZ node.
  26294. */
  26295. getViewZNode( name = 'depth' ) {
  26296. let viewZNode = this._viewZNodes[ name ];
  26297. if ( viewZNode === undefined ) {
  26298. const cameraNear = this._cameraNear;
  26299. const cameraFar = this._cameraFar;
  26300. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  26301. }
  26302. return viewZNode;
  26303. }
  26304. /**
  26305. * Returns a linear depth node of this pass.
  26306. *
  26307. * @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.
  26308. * @return {Node} The linear depth node.
  26309. */
  26310. getLinearDepthNode( name = 'depth' ) {
  26311. let linearDepthNode = this._linearDepthNodes[ name ];
  26312. if ( linearDepthNode === undefined ) {
  26313. const cameraNear = this._cameraNear;
  26314. const cameraFar = this._cameraFar;
  26315. const viewZNode = this.getViewZNode( name );
  26316. // TODO: just if ( builder.camera.isPerspectiveCamera )
  26317. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  26318. }
  26319. return linearDepthNode;
  26320. }
  26321. /**
  26322. * Precompiles the pass.
  26323. *
  26324. * Note that this method must be called after the pass configuration is complete.
  26325. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  26326. *
  26327. * @async
  26328. * @param {Renderer} renderer - The renderer.
  26329. * @return {Promise} A Promise that resolves when the compile has been finished.
  26330. * @see {@link Renderer#compileAsync}
  26331. */
  26332. async compileAsync( renderer ) {
  26333. const currentRenderTarget = renderer.getRenderTarget();
  26334. const currentMRT = renderer.getMRT();
  26335. renderer.setRenderTarget( this.renderTarget );
  26336. renderer.setMRT( this._mrt );
  26337. await renderer.compileAsync( this.scene, this.camera );
  26338. renderer.setRenderTarget( currentRenderTarget );
  26339. renderer.setMRT( currentMRT );
  26340. }
  26341. setup( { renderer } ) {
  26342. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  26343. this.renderTarget.texture.type = renderer.getColorBufferType();
  26344. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  26345. }
  26346. updateBefore( frame ) {
  26347. const { renderer } = frame;
  26348. const { scene } = this;
  26349. let camera;
  26350. let pixelRatio;
  26351. const outputRenderTarget = renderer.getOutputRenderTarget();
  26352. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  26353. pixelRatio = 1;
  26354. camera = renderer.xr.getCamera();
  26355. renderer.xr.updateCamera( camera );
  26356. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  26357. } else {
  26358. camera = this.camera;
  26359. pixelRatio = renderer.getPixelRatio();
  26360. renderer.getSize( _size );
  26361. }
  26362. this._pixelRatio = pixelRatio;
  26363. this.setSize( _size.width, _size.height );
  26364. const currentRenderTarget = renderer.getRenderTarget();
  26365. const currentMRT = renderer.getMRT();
  26366. const currentAutoClear = renderer.autoClear;
  26367. const currentMask = camera.layers.mask;
  26368. this._cameraNear.value = camera.near;
  26369. this._cameraFar.value = camera.far;
  26370. if ( this._layers !== null ) {
  26371. camera.layers.mask = this._layers.mask;
  26372. }
  26373. for ( const name in this._previousTextures ) {
  26374. this.toggleTexture( name );
  26375. }
  26376. renderer.setRenderTarget( this.renderTarget );
  26377. renderer.setMRT( this._mrt );
  26378. renderer.autoClear = true;
  26379. const currentSceneName = scene.name;
  26380. scene.name = this.name ? this.name : scene.name;
  26381. renderer.render( scene, camera );
  26382. scene.name = currentSceneName;
  26383. renderer.setRenderTarget( currentRenderTarget );
  26384. renderer.setMRT( currentMRT );
  26385. renderer.autoClear = currentAutoClear;
  26386. camera.layers.mask = currentMask;
  26387. }
  26388. /**
  26389. * Sets the size of the pass's render target. Honors the pixel ratio.
  26390. *
  26391. * @param {number} width - The width to set.
  26392. * @param {number} height - The height to set.
  26393. */
  26394. setSize( width, height ) {
  26395. this._width = width;
  26396. this._height = height;
  26397. const effectiveWidth = this._width * this._pixelRatio * this._resolutionScale;
  26398. const effectiveHeight = this._height * this._pixelRatio * this._resolutionScale;
  26399. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  26400. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  26401. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  26402. }
  26403. /**
  26404. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  26405. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  26406. * with `null` as the single argument.
  26407. *
  26408. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  26409. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  26410. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  26411. * @param {number} width - The width of the scissor box in logical pixel unit.
  26412. * @param {number} height - The height of the scissor box in logical pixel unit.
  26413. */
  26414. setScissor( x, y, width, height ) {
  26415. if ( x === null ) {
  26416. this._scissor = null;
  26417. } else {
  26418. if ( this._scissor === null ) this._scissor = new Vector4();
  26419. if ( x.isVector4 ) {
  26420. this._scissor.copy( x );
  26421. } else {
  26422. this._scissor.set( x, y, width, height );
  26423. }
  26424. this._scissor.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  26425. }
  26426. }
  26427. /**
  26428. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  26429. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  26430. * with `null` as the single argument.
  26431. *
  26432. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  26433. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  26434. * @param {number} width - The width of the viewport in logical pixel unit.
  26435. * @param {number} height - The height of the viewport in logical pixel unit.
  26436. */
  26437. setViewport( x, y, width, height ) {
  26438. if ( x === null ) {
  26439. this._viewport = null;
  26440. } else {
  26441. if ( this._viewport === null ) this._viewport = new Vector4();
  26442. if ( x.isVector4 ) {
  26443. this._viewport.copy( x );
  26444. } else {
  26445. this._viewport.set( x, y, width, height );
  26446. }
  26447. this._viewport.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  26448. }
  26449. }
  26450. /**
  26451. * Sets the pixel ratio the pass's render target and updates the size.
  26452. *
  26453. * @param {number} pixelRatio - The pixel ratio to set.
  26454. */
  26455. setPixelRatio( pixelRatio ) {
  26456. this._pixelRatio = pixelRatio;
  26457. this.setSize( this._width, this._height );
  26458. }
  26459. /**
  26460. * Frees internal resources. Should be called when the node is no longer in use.
  26461. */
  26462. dispose() {
  26463. this.renderTarget.dispose();
  26464. }
  26465. }
  26466. /**
  26467. * @static
  26468. * @type {'color'}
  26469. * @default 'color'
  26470. */
  26471. PassNode.COLOR = 'color';
  26472. /**
  26473. * @static
  26474. * @type {'depth'}
  26475. * @default 'depth'
  26476. */
  26477. PassNode.DEPTH = 'depth';
  26478. /**
  26479. * TSL function for creating a pass node.
  26480. *
  26481. * @tsl
  26482. * @function
  26483. * @param {Scene} scene - A reference to the scene.
  26484. * @param {Camera} camera - A reference to the camera.
  26485. * @param {Object} options - Options for the internal render target.
  26486. * @returns {PassNode}
  26487. */
  26488. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  26489. /**
  26490. * TSL function for creating a pass texture node.
  26491. *
  26492. * @tsl
  26493. * @function
  26494. * @param {PassNode} pass - The pass node.
  26495. * @param {Texture} texture - The output texture.
  26496. * @returns {PassTextureNode}
  26497. */
  26498. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  26499. /**
  26500. * TSL function for creating a depth pass node.
  26501. *
  26502. * @tsl
  26503. * @function
  26504. * @param {Scene} scene - A reference to the scene.
  26505. * @param {Camera} camera - A reference to the camera.
  26506. * @param {Object} options - Options for the internal render target.
  26507. * @returns {PassNode}
  26508. */
  26509. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  26510. /**
  26511. * Represents a render pass for producing a toon outline effect on compatible objects.
  26512. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  26513. * will receive the outline.
  26514. *
  26515. * ```js
  26516. * const postProcessing = new PostProcessing( renderer );
  26517. *
  26518. * const scenePass = toonOutlinePass( scene, camera );
  26519. *
  26520. * postProcessing.outputNode = scenePass;
  26521. * ```
  26522. * @augments PassNode
  26523. */
  26524. class ToonOutlinePassNode extends PassNode {
  26525. static get type() {
  26526. return 'ToonOutlinePassNode';
  26527. }
  26528. /**
  26529. * Constructs a new outline pass node.
  26530. *
  26531. * @param {Scene} scene - A reference to the scene.
  26532. * @param {Camera} camera - A reference to the camera.
  26533. * @param {Node} colorNode - Defines the outline's color.
  26534. * @param {Node} thicknessNode - Defines the outline's thickness.
  26535. * @param {Node} alphaNode - Defines the outline's alpha.
  26536. */
  26537. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  26538. super( PassNode.COLOR, scene, camera );
  26539. /**
  26540. * Defines the outline's color.
  26541. *
  26542. * @type {Node}
  26543. */
  26544. this.colorNode = colorNode;
  26545. /**
  26546. * Defines the outline's thickness.
  26547. *
  26548. * @type {Node}
  26549. */
  26550. this.thicknessNode = thicknessNode;
  26551. /**
  26552. * Defines the outline's alpha.
  26553. *
  26554. * @type {Node}
  26555. */
  26556. this.alphaNode = alphaNode;
  26557. /**
  26558. * An internal material cache.
  26559. *
  26560. * @private
  26561. * @type {WeakMap<Material, NodeMaterial>}
  26562. */
  26563. this._materialCache = new WeakMap();
  26564. /**
  26565. * The name of this pass.
  26566. *
  26567. * @type {string}
  26568. * @default 'Outline Pass'
  26569. */
  26570. this.name = 'Outline Pass';
  26571. }
  26572. updateBefore( frame ) {
  26573. const { renderer } = frame;
  26574. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26575. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  26576. // only render outline for supported materials
  26577. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  26578. if ( material.wireframe === false ) {
  26579. const outlineMaterial = this._getOutlineMaterial( material );
  26580. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  26581. }
  26582. }
  26583. // default
  26584. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  26585. } );
  26586. super.updateBefore( frame );
  26587. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26588. }
  26589. /**
  26590. * Creates the material used for outline rendering.
  26591. *
  26592. * @private
  26593. * @return {NodeMaterial} The outline material.
  26594. */
  26595. _createMaterial() {
  26596. const material = new NodeMaterial();
  26597. material.isMeshToonOutlineMaterial = true;
  26598. material.name = 'Toon_Outline';
  26599. material.side = BackSide;
  26600. // vertex node
  26601. const outlineNormal = normalLocal.negate();
  26602. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  26603. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  26604. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  26605. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  26606. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  26607. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  26608. // color node
  26609. material.colorNode = vec4( this.colorNode, this.alphaNode );
  26610. return material;
  26611. }
  26612. /**
  26613. * For the given toon material, this method returns a corresponding
  26614. * outline material.
  26615. *
  26616. * @private
  26617. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  26618. * @return {NodeMaterial} The outline material.
  26619. */
  26620. _getOutlineMaterial( originalMaterial ) {
  26621. let outlineMaterial = this._materialCache.get( originalMaterial );
  26622. if ( outlineMaterial === undefined ) {
  26623. outlineMaterial = this._createMaterial();
  26624. this._materialCache.set( originalMaterial, outlineMaterial );
  26625. }
  26626. return outlineMaterial;
  26627. }
  26628. }
  26629. /**
  26630. * TSL function for creating a toon outline pass node.
  26631. *
  26632. * @tsl
  26633. * @function
  26634. * @param {Scene} scene - A reference to the scene.
  26635. * @param {Camera} camera - A reference to the camera.
  26636. * @param {Color} color - Defines the outline's color.
  26637. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  26638. * @param {number} [alpha=1] - Defines the outline's alpha.
  26639. * @returns {ToonOutlinePassNode}
  26640. */
  26641. 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 ) ) );
  26642. /**
  26643. * Linear tone mapping, exposure only.
  26644. *
  26645. * @tsl
  26646. * @function
  26647. * @param {Node<vec3>} color - The color that should be tone mapped.
  26648. * @param {Node<float>} exposure - The exposure.
  26649. * @return {Node<vec3>} The tone mapped color.
  26650. */
  26651. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26652. return color.mul( exposure ).clamp();
  26653. } ).setLayout( {
  26654. name: 'linearToneMapping',
  26655. type: 'vec3',
  26656. inputs: [
  26657. { name: 'color', type: 'vec3' },
  26658. { name: 'exposure', type: 'float' }
  26659. ]
  26660. } );
  26661. /**
  26662. * Reinhard tone mapping.
  26663. *
  26664. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  26665. *
  26666. * @tsl
  26667. * @function
  26668. * @param {Node<vec3>} color - The color that should be tone mapped.
  26669. * @param {Node<float>} exposure - The exposure.
  26670. * @return {Node<vec3>} The tone mapped color.
  26671. */
  26672. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26673. color = color.mul( exposure );
  26674. return color.div( color.add( 1.0 ) ).clamp();
  26675. } ).setLayout( {
  26676. name: 'reinhardToneMapping',
  26677. type: 'vec3',
  26678. inputs: [
  26679. { name: 'color', type: 'vec3' },
  26680. { name: 'exposure', type: 'float' }
  26681. ]
  26682. } );
  26683. /**
  26684. * Cineon tone mapping.
  26685. *
  26686. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  26687. *
  26688. * @tsl
  26689. * @function
  26690. * @param {Node<vec3>} color - The color that should be tone mapped.
  26691. * @param {Node<float>} exposure - The exposure.
  26692. * @return {Node<vec3>} The tone mapped color.
  26693. */
  26694. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26695. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  26696. color = color.mul( exposure );
  26697. color = color.sub( 0.004 ).max( 0.0 );
  26698. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  26699. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  26700. return a.div( b ).pow( 2.2 );
  26701. } ).setLayout( {
  26702. name: 'cineonToneMapping',
  26703. type: 'vec3',
  26704. inputs: [
  26705. { name: 'color', type: 'vec3' },
  26706. { name: 'exposure', type: 'float' }
  26707. ]
  26708. } );
  26709. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  26710. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  26711. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  26712. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  26713. return a.div( b );
  26714. } );
  26715. /**
  26716. * ACESFilmic tone mapping.
  26717. *
  26718. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  26719. *
  26720. * @tsl
  26721. * @function
  26722. * @param {Node<vec3>} color - The color that should be tone mapped.
  26723. * @param {Node<float>} exposure - The exposure.
  26724. * @return {Node<vec3>} The tone mapped color.
  26725. */
  26726. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26727. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  26728. const ACESInputMat = mat3(
  26729. 0.59719, 0.35458, 0.04823,
  26730. 0.07600, 0.90834, 0.01566,
  26731. 0.02840, 0.13383, 0.83777
  26732. );
  26733. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  26734. const ACESOutputMat = mat3(
  26735. 1.60475, -0.53108, -0.07367,
  26736. -0.10208, 1.10813, -605e-5,
  26737. -327e-5, -0.07276, 1.07602
  26738. );
  26739. color = color.mul( exposure ).div( 0.6 );
  26740. color = ACESInputMat.mul( color );
  26741. // Apply RRT and ODT
  26742. color = RRTAndODTFit( color );
  26743. color = ACESOutputMat.mul( color );
  26744. // Clamp to [0, 1]
  26745. return color.clamp();
  26746. } ).setLayout( {
  26747. name: 'acesFilmicToneMapping',
  26748. type: 'vec3',
  26749. inputs: [
  26750. { name: 'color', type: 'vec3' },
  26751. { name: 'exposure', type: 'float' }
  26752. ]
  26753. } );
  26754. 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 ) );
  26755. 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 ) );
  26756. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26757. const x = vec3( x_immutable ).toVar();
  26758. const x2 = vec3( x.mul( x ) ).toVar();
  26759. const x4 = vec3( x2.mul( x2 ) ).toVar();
  26760. 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 ) ) ) );
  26761. } );
  26762. /**
  26763. * AgX tone mapping.
  26764. *
  26765. * @tsl
  26766. * @function
  26767. * @param {Node<vec3>} color - The color that should be tone mapped.
  26768. * @param {Node<float>} exposure - The exposure.
  26769. * @return {Node<vec3>} The tone mapped color.
  26770. */
  26771. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26772. const colortone = vec3( color ).toVar();
  26773. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  26774. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  26775. const AgxMinEv = float( -12.47393 );
  26776. const AgxMaxEv = float( 4.026069 );
  26777. colortone.mulAssign( exposure );
  26778. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  26779. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  26780. colortone.assign( max$1( colortone, 1e-10 ) );
  26781. colortone.assign( log2( colortone ) );
  26782. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  26783. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  26784. colortone.assign( agxDefaultContrastApprox( colortone ) );
  26785. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  26786. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  26787. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  26788. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  26789. return colortone;
  26790. } ).setLayout( {
  26791. name: 'agxToneMapping',
  26792. type: 'vec3',
  26793. inputs: [
  26794. { name: 'color', type: 'vec3' },
  26795. { name: 'exposure', type: 'float' }
  26796. ]
  26797. } );
  26798. /**
  26799. * Neutral tone mapping.
  26800. *
  26801. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  26802. *
  26803. * @tsl
  26804. * @function
  26805. * @param {Node<vec3>} color - The color that should be tone mapped.
  26806. * @param {Node<float>} exposure - The exposure.
  26807. * @return {Node<vec3>} The tone mapped color.
  26808. */
  26809. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26810. const StartCompression = float( 0.8 - 0.04 );
  26811. const Desaturation = float( 0.15 );
  26812. color = color.mul( exposure );
  26813. const x = min$1( color.r, min$1( color.g, color.b ) );
  26814. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  26815. color.subAssign( offset );
  26816. const peak = max$1( color.r, max$1( color.g, color.b ) );
  26817. If( peak.lessThan( StartCompression ), () => {
  26818. return color;
  26819. } );
  26820. const d = sub( 1, StartCompression );
  26821. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  26822. color.mulAssign( newPeak.div( peak ) );
  26823. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  26824. return mix( color, vec3( newPeak ), g );
  26825. } ).setLayout( {
  26826. name: 'neutralToneMapping',
  26827. type: 'vec3',
  26828. inputs: [
  26829. { name: 'color', type: 'vec3' },
  26830. { name: 'exposure', type: 'float' }
  26831. ]
  26832. } );
  26833. /**
  26834. * This class represents native code sections. It is the base
  26835. * class for modules like {@link FunctionNode} which allows to implement
  26836. * functions with native shader languages.
  26837. *
  26838. * @augments Node
  26839. */
  26840. class CodeNode extends Node {
  26841. static get type() {
  26842. return 'CodeNode';
  26843. }
  26844. /**
  26845. * Constructs a new code node.
  26846. *
  26847. * @param {string} [code=''] - The native code.
  26848. * @param {Array<Node>} [includes=[]] - An array of includes.
  26849. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26850. */
  26851. constructor( code = '', includes = [], language = '' ) {
  26852. super( 'code' );
  26853. /**
  26854. * This flag can be used for type testing.
  26855. *
  26856. * @type {boolean}
  26857. * @readonly
  26858. * @default true
  26859. */
  26860. this.isCodeNode = true;
  26861. /**
  26862. * This flag is used for global cache.
  26863. *
  26864. * @type {boolean}
  26865. * @default true
  26866. */
  26867. this.global = true;
  26868. /**
  26869. * The native code.
  26870. *
  26871. * @type {string}
  26872. * @default ''
  26873. */
  26874. this.code = code;
  26875. /**
  26876. * An array of includes
  26877. *
  26878. * @type {Array<Node>}
  26879. * @default []
  26880. */
  26881. this.includes = includes;
  26882. /**
  26883. * The used language.
  26884. *
  26885. * @type {('js'|'wgsl'|'glsl')}
  26886. * @default ''
  26887. */
  26888. this.language = language;
  26889. }
  26890. /**
  26891. * Sets the includes of this code node.
  26892. *
  26893. * @param {Array<Node>} includes - The includes to set.
  26894. * @return {CodeNode} A reference to this node.
  26895. */
  26896. setIncludes( includes ) {
  26897. this.includes = includes;
  26898. return this;
  26899. }
  26900. /**
  26901. * Returns the includes of this code node.
  26902. *
  26903. * @param {NodeBuilder} builder - The current node builder.
  26904. * @return {Array<Node>} The includes.
  26905. */
  26906. getIncludes( /*builder*/ ) {
  26907. return this.includes;
  26908. }
  26909. generate( builder ) {
  26910. const includes = this.getIncludes( builder );
  26911. for ( const include of includes ) {
  26912. include.build( builder );
  26913. }
  26914. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  26915. nodeCode.code = this.code;
  26916. return nodeCode.code;
  26917. }
  26918. serialize( data ) {
  26919. super.serialize( data );
  26920. data.code = this.code;
  26921. data.language = this.language;
  26922. }
  26923. deserialize( data ) {
  26924. super.deserialize( data );
  26925. this.code = data.code;
  26926. this.language = data.language;
  26927. }
  26928. }
  26929. /**
  26930. * TSL function for creating a code node.
  26931. *
  26932. * @tsl
  26933. * @function
  26934. * @param {string} [code] - The native code.
  26935. * @param {?Array<Node>} [includes=[]] - An array of includes.
  26936. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26937. * @returns {CodeNode}
  26938. */
  26939. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  26940. /**
  26941. * TSL function for creating a JS code node.
  26942. *
  26943. * @tsl
  26944. * @function
  26945. * @param {string} src - The native code.
  26946. * @param {Array<Node>} includes - An array of includes.
  26947. * @returns {CodeNode}
  26948. */
  26949. const js = ( src, includes ) => code( src, includes, 'js' );
  26950. /**
  26951. * TSL function for creating a WGSL code node.
  26952. *
  26953. * @tsl
  26954. * @function
  26955. * @param {string} src - The native code.
  26956. * @param {Array<Node>} includes - An array of includes.
  26957. * @returns {CodeNode}
  26958. */
  26959. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  26960. /**
  26961. * TSL function for creating a GLSL code node.
  26962. *
  26963. * @tsl
  26964. * @function
  26965. * @param {string} src - The native code.
  26966. * @param {Array<Node>} includes - An array of includes.
  26967. * @returns {CodeNode}
  26968. */
  26969. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  26970. /**
  26971. * This class represents a native shader function. It can be used to implement
  26972. * certain aspects of a node material with native shader code. There are two predefined
  26973. * TSL functions for easier usage.
  26974. *
  26975. * - `wgslFn`: Creates a WGSL function node.
  26976. * - `glslFn`: Creates a GLSL function node.
  26977. *
  26978. * A basic example with one include looks like so:
  26979. *
  26980. * ```js
  26981. * const desaturateWGSLFn = wgslFn( `
  26982. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  26983. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  26984. * return vec3<f32>( dot( lum, color ) );
  26985. * }`
  26986. *);
  26987. * const someWGSLFn = wgslFn( `
  26988. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  26989. * return desaturate( color );
  26990. * }
  26991. * `, [ desaturateWGSLFn ] );
  26992. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  26993. *```
  26994. * @augments CodeNode
  26995. */
  26996. class FunctionNode extends CodeNode {
  26997. static get type() {
  26998. return 'FunctionNode';
  26999. }
  27000. /**
  27001. * Constructs a new function node.
  27002. *
  27003. * @param {string} [code=''] - The native code.
  27004. * @param {Array<Node>} [includes=[]] - An array of includes.
  27005. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  27006. */
  27007. constructor( code = '', includes = [], language = '' ) {
  27008. super( code, includes, language );
  27009. }
  27010. /**
  27011. * Returns the type of this function node.
  27012. *
  27013. * @param {NodeBuilder} builder - The current node builder.
  27014. * @return {string} The type.
  27015. */
  27016. getNodeType( builder ) {
  27017. return this.getNodeFunction( builder ).type;
  27018. }
  27019. /**
  27020. * Returns the type of a member of this function node.
  27021. *
  27022. * @param {NodeBuilder} builder - The current node builder.
  27023. * @param {string} name - The name of the member.
  27024. * @return {string} The type of the member.
  27025. */
  27026. getMemberType( builder, name ) {
  27027. const type = this.getNodeType( builder );
  27028. const structType = builder.getStructTypeNode( type );
  27029. return structType.getMemberType( builder, name );
  27030. }
  27031. /**
  27032. * Returns the inputs of this function node.
  27033. *
  27034. * @param {NodeBuilder} builder - The current node builder.
  27035. * @return {Array<NodeFunctionInput>} The inputs.
  27036. */
  27037. getInputs( builder ) {
  27038. return this.getNodeFunction( builder ).inputs;
  27039. }
  27040. /**
  27041. * Returns the node function for this function node.
  27042. *
  27043. * @param {NodeBuilder} builder - The current node builder.
  27044. * @return {NodeFunction} The node function.
  27045. */
  27046. getNodeFunction( builder ) {
  27047. const nodeData = builder.getDataFromNode( this );
  27048. let nodeFunction = nodeData.nodeFunction;
  27049. if ( nodeFunction === undefined ) {
  27050. nodeFunction = builder.parser.parseFunction( this.code );
  27051. nodeData.nodeFunction = nodeFunction;
  27052. }
  27053. return nodeFunction;
  27054. }
  27055. generate( builder, output ) {
  27056. super.generate( builder );
  27057. const nodeFunction = this.getNodeFunction( builder );
  27058. const name = nodeFunction.name;
  27059. const type = nodeFunction.type;
  27060. const nodeCode = builder.getCodeFromNode( this, type );
  27061. if ( name !== '' ) {
  27062. // use a custom property name
  27063. nodeCode.name = name;
  27064. }
  27065. const propertyName = builder.getPropertyName( nodeCode );
  27066. const code = this.getNodeFunction( builder ).getCode( propertyName );
  27067. nodeCode.code = code + '\n';
  27068. if ( output === 'property' ) {
  27069. return propertyName;
  27070. } else {
  27071. return builder.format( `${ propertyName }()`, type, output );
  27072. }
  27073. }
  27074. }
  27075. const nativeFn = ( code, includes = [], language = '' ) => {
  27076. for ( let i = 0; i < includes.length; i ++ ) {
  27077. const include = includes[ i ];
  27078. // TSL Function: glslFn, wgslFn
  27079. if ( typeof include === 'function' ) {
  27080. includes[ i ] = include.functionNode;
  27081. }
  27082. }
  27083. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  27084. const fn = ( ...params ) => functionNode.call( ...params );
  27085. fn.functionNode = functionNode;
  27086. return fn;
  27087. };
  27088. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  27089. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  27090. /**
  27091. * `ScriptableNode` uses this class to manage script inputs and outputs.
  27092. *
  27093. * @augments Node
  27094. */
  27095. class ScriptableValueNode extends Node {
  27096. static get type() {
  27097. return 'ScriptableValueNode';
  27098. }
  27099. /**
  27100. * Constructs a new scriptable node.
  27101. *
  27102. * @param {any} [value=null] - The value.
  27103. */
  27104. constructor( value = null ) {
  27105. super();
  27106. /**
  27107. * A reference to the value.
  27108. *
  27109. * @private
  27110. * @default null
  27111. */
  27112. this._value = value;
  27113. /**
  27114. * Depending on the type of `_value`, this property might cache parsed data.
  27115. *
  27116. * @private
  27117. * @default null
  27118. */
  27119. this._cache = null;
  27120. /**
  27121. * If this node represents an input, this property represents the input type.
  27122. *
  27123. * @type {?string}
  27124. * @default null
  27125. */
  27126. this.inputType = null;
  27127. /**
  27128. * If this node represents an output, this property represents the output type.
  27129. *
  27130. * @type {?string}
  27131. * @default null
  27132. */
  27133. this.outputType = null;
  27134. /**
  27135. * An event dispatcher for managing events.
  27136. *
  27137. * @type {EventDispatcher}
  27138. */
  27139. this.events = new EventDispatcher();
  27140. /**
  27141. * This flag can be used for type testing.
  27142. *
  27143. * @type {boolean}
  27144. * @readonly
  27145. * @default true
  27146. */
  27147. this.isScriptableValueNode = true;
  27148. }
  27149. /**
  27150. * Whether this node represents an output or not.
  27151. *
  27152. * @type {boolean}
  27153. * @readonly
  27154. * @default true
  27155. */
  27156. get isScriptableOutputNode() {
  27157. return this.outputType !== null;
  27158. }
  27159. set value( val ) {
  27160. if ( this._value === val ) return;
  27161. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  27162. URL.revokeObjectURL( this._cache );
  27163. this._cache = null;
  27164. }
  27165. this._value = val;
  27166. this.events.dispatchEvent( { type: 'change' } );
  27167. this.refresh();
  27168. }
  27169. /**
  27170. * The node's value.
  27171. *
  27172. * @type {any}
  27173. */
  27174. get value() {
  27175. return this._value;
  27176. }
  27177. /**
  27178. * Dispatches the `refresh` event.
  27179. */
  27180. refresh() {
  27181. this.events.dispatchEvent( { type: 'refresh' } );
  27182. }
  27183. /**
  27184. * The `value` property usually represents a node or even binary data in form of array buffers.
  27185. * In this case, this method tries to return the actual value behind the complex type.
  27186. *
  27187. * @return {any} The value.
  27188. */
  27189. getValue() {
  27190. const value = this.value;
  27191. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  27192. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  27193. } else if ( value && value.value !== null && value.value !== undefined && (
  27194. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  27195. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  27196. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  27197. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  27198. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  27199. ( this.inputType === 'Color' && value.value.isColor ) ||
  27200. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  27201. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  27202. ) ) {
  27203. return value.value;
  27204. }
  27205. return this._cache || value;
  27206. }
  27207. /**
  27208. * Overwritten since the node type is inferred from the value.
  27209. *
  27210. * @param {NodeBuilder} builder - The current node builder.
  27211. * @return {string} The node type.
  27212. */
  27213. getNodeType( builder ) {
  27214. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  27215. }
  27216. setup() {
  27217. return this.value && this.value.isNode ? this.value : float();
  27218. }
  27219. serialize( data ) {
  27220. super.serialize( data );
  27221. if ( this.value !== null ) {
  27222. if ( this.inputType === 'ArrayBuffer' ) {
  27223. data.value = arrayBufferToBase64( this.value );
  27224. } else {
  27225. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  27226. }
  27227. } else {
  27228. data.value = null;
  27229. }
  27230. data.inputType = this.inputType;
  27231. data.outputType = this.outputType;
  27232. }
  27233. deserialize( data ) {
  27234. super.deserialize( data );
  27235. let value = null;
  27236. if ( data.value !== null ) {
  27237. if ( data.inputType === 'ArrayBuffer' ) {
  27238. value = base64ToArrayBuffer( data.value );
  27239. } else if ( data.inputType === 'Texture' ) {
  27240. value = data.meta.textures[ data.value ];
  27241. } else {
  27242. value = data.meta.nodes[ data.value ] || null;
  27243. }
  27244. }
  27245. this.value = value;
  27246. this.inputType = data.inputType;
  27247. this.outputType = data.outputType;
  27248. }
  27249. }
  27250. /**
  27251. * TSL function for creating a scriptable value node.
  27252. *
  27253. * @tsl
  27254. * @function
  27255. * @param {any} [value] - The value.
  27256. * @returns {ScriptableValueNode}
  27257. */
  27258. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  27259. /**
  27260. * A Map-like data structure for managing resources of scriptable nodes.
  27261. *
  27262. * @augments Map
  27263. */
  27264. class Resources extends Map {
  27265. get( key, callback = null, ...params ) {
  27266. if ( this.has( key ) ) return super.get( key );
  27267. if ( callback !== null ) {
  27268. const value = callback( ...params );
  27269. this.set( key, value );
  27270. return value;
  27271. }
  27272. }
  27273. }
  27274. class Parameters {
  27275. constructor( scriptableNode ) {
  27276. this.scriptableNode = scriptableNode;
  27277. }
  27278. get parameters() {
  27279. return this.scriptableNode.parameters;
  27280. }
  27281. get layout() {
  27282. return this.scriptableNode.getLayout();
  27283. }
  27284. getInputLayout( id ) {
  27285. return this.scriptableNode.getInputLayout( id );
  27286. }
  27287. get( name ) {
  27288. const param = this.parameters[ name ];
  27289. const value = param ? param.getValue() : null;
  27290. return value;
  27291. }
  27292. }
  27293. /**
  27294. * Defines the resources (e.g. namespaces) of scriptable nodes.
  27295. *
  27296. * @type {Resources}
  27297. */
  27298. const ScriptableNodeResources = new Resources();
  27299. /**
  27300. * This type of node allows to implement nodes with custom scripts. The script
  27301. * section is represented as an instance of `CodeNode` written with JavaScript.
  27302. * The script itself must adhere to a specific structure.
  27303. *
  27304. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  27305. * - layout: The layout object defines the script's interface (inputs and outputs).
  27306. *
  27307. * ```js
  27308. * ScriptableNodeResources.set( 'TSL', TSL );
  27309. *
  27310. * const scriptableNode = scriptable( js( `
  27311. * layout = {
  27312. * outputType: 'node',
  27313. * elements: [
  27314. * { name: 'source', inputType: 'node' },
  27315. * ]
  27316. * };
  27317. *
  27318. * const { mul, oscSine } = TSL;
  27319. *
  27320. * function main() {
  27321. * const source = parameters.get( 'source' ) || float();
  27322. * return mul( source, oscSine() ) );
  27323. * }
  27324. *
  27325. * ` ) );
  27326. *
  27327. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  27328. *
  27329. * const material = new THREE.MeshBasicNodeMaterial();
  27330. * material.colorNode = scriptableNode;
  27331. * ```
  27332. *
  27333. * @augments Node
  27334. */
  27335. class ScriptableNode extends Node {
  27336. static get type() {
  27337. return 'ScriptableNode';
  27338. }
  27339. /**
  27340. * Constructs a new scriptable node.
  27341. *
  27342. * @param {?CodeNode} [codeNode=null] - The code node.
  27343. * @param {Object} [parameters={}] - The parameters definition.
  27344. */
  27345. constructor( codeNode = null, parameters = {} ) {
  27346. super();
  27347. /**
  27348. * The code node.
  27349. *
  27350. * @type {?CodeNode}
  27351. * @default null
  27352. */
  27353. this.codeNode = codeNode;
  27354. /**
  27355. * The parameters definition.
  27356. *
  27357. * @type {Object}
  27358. * @default {}
  27359. */
  27360. this.parameters = parameters;
  27361. this._local = new Resources();
  27362. this._output = scriptableValue( null );
  27363. this._outputs = {};
  27364. this._source = this.source;
  27365. this._method = null;
  27366. this._object = null;
  27367. this._value = null;
  27368. this._needsOutputUpdate = true;
  27369. this.onRefresh = this.onRefresh.bind( this );
  27370. /**
  27371. * This flag can be used for type testing.
  27372. *
  27373. * @type {boolean}
  27374. * @readonly
  27375. * @default true
  27376. */
  27377. this.isScriptableNode = true;
  27378. }
  27379. /**
  27380. * The source code of the scriptable node.
  27381. *
  27382. * @type {string}
  27383. */
  27384. get source() {
  27385. return this.codeNode ? this.codeNode.code : '';
  27386. }
  27387. /**
  27388. * Sets the reference of a local script variable.
  27389. *
  27390. * @param {string} name - The variable name.
  27391. * @param {Object} value - The reference to set.
  27392. * @return {Resources} The resource map
  27393. */
  27394. setLocal( name, value ) {
  27395. return this._local.set( name, value );
  27396. }
  27397. /**
  27398. * Gets the value of a local script variable.
  27399. *
  27400. * @param {string} name - The variable name.
  27401. * @return {Object} The value.
  27402. */
  27403. getLocal( name ) {
  27404. return this._local.get( name );
  27405. }
  27406. /**
  27407. * Event listener for the `refresh` event.
  27408. */
  27409. onRefresh() {
  27410. this._refresh();
  27411. }
  27412. /**
  27413. * Returns an input from the layout with the given id/name.
  27414. *
  27415. * @param {string} id - The id/name of the input.
  27416. * @return {Object} The element entry.
  27417. */
  27418. getInputLayout( id ) {
  27419. for ( const element of this.getLayout() ) {
  27420. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  27421. return element;
  27422. }
  27423. }
  27424. }
  27425. /**
  27426. * Returns an output from the layout with the given id/name.
  27427. *
  27428. * @param {string} id - The id/name of the output.
  27429. * @return {Object} The element entry.
  27430. */
  27431. getOutputLayout( id ) {
  27432. for ( const element of this.getLayout() ) {
  27433. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  27434. return element;
  27435. }
  27436. }
  27437. }
  27438. /**
  27439. * Defines a script output for the given name and value.
  27440. *
  27441. * @param {string} name - The name of the output.
  27442. * @param {Node} value - The node value.
  27443. * @return {ScriptableNode} A reference to this node.
  27444. */
  27445. setOutput( name, value ) {
  27446. const outputs = this._outputs;
  27447. if ( outputs[ name ] === undefined ) {
  27448. outputs[ name ] = scriptableValue( value );
  27449. } else {
  27450. outputs[ name ].value = value;
  27451. }
  27452. return this;
  27453. }
  27454. /**
  27455. * Returns a script output for the given name.
  27456. *
  27457. * @param {string} name - The name of the output.
  27458. * @return {ScriptableValueNode} The node value.
  27459. */
  27460. getOutput( name ) {
  27461. return this._outputs[ name ];
  27462. }
  27463. /**
  27464. * Returns a parameter for the given name
  27465. *
  27466. * @param {string} name - The name of the parameter.
  27467. * @return {ScriptableValueNode} The node value.
  27468. */
  27469. getParameter( name ) {
  27470. return this.parameters[ name ];
  27471. }
  27472. /**
  27473. * Sets a value for the given parameter name.
  27474. *
  27475. * @param {string} name - The parameter name.
  27476. * @param {any} value - The parameter value.
  27477. * @return {ScriptableNode} A reference to this node.
  27478. */
  27479. setParameter( name, value ) {
  27480. const parameters = this.parameters;
  27481. if ( value && value.isScriptableNode ) {
  27482. this.deleteParameter( name );
  27483. parameters[ name ] = value;
  27484. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  27485. } else if ( value && value.isScriptableValueNode ) {
  27486. this.deleteParameter( name );
  27487. parameters[ name ] = value;
  27488. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  27489. } else if ( parameters[ name ] === undefined ) {
  27490. parameters[ name ] = scriptableValue( value );
  27491. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  27492. } else {
  27493. parameters[ name ].value = value;
  27494. }
  27495. return this;
  27496. }
  27497. /**
  27498. * Returns the value of this node which is the value of
  27499. * the default output.
  27500. *
  27501. * @return {Node} The value.
  27502. */
  27503. getValue() {
  27504. return this.getDefaultOutput().getValue();
  27505. }
  27506. /**
  27507. * Deletes a parameter from the script.
  27508. *
  27509. * @param {string} name - The parameter to remove.
  27510. * @return {ScriptableNode} A reference to this node.
  27511. */
  27512. deleteParameter( name ) {
  27513. let valueNode = this.parameters[ name ];
  27514. if ( valueNode ) {
  27515. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  27516. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  27517. }
  27518. return this;
  27519. }
  27520. /**
  27521. * Deletes all parameters from the script.
  27522. *
  27523. * @return {ScriptableNode} A reference to this node.
  27524. */
  27525. clearParameters() {
  27526. for ( const name of Object.keys( this.parameters ) ) {
  27527. this.deleteParameter( name );
  27528. }
  27529. this.needsUpdate = true;
  27530. return this;
  27531. }
  27532. /**
  27533. * Calls a function from the script.
  27534. *
  27535. * @param {string} name - The function name.
  27536. * @param {...any} params - A list of parameters.
  27537. * @return {any} The result of the function call.
  27538. */
  27539. call( name, ...params ) {
  27540. const object = this.getObject();
  27541. const method = object[ name ];
  27542. if ( typeof method === 'function' ) {
  27543. return method( ...params );
  27544. }
  27545. }
  27546. /**
  27547. * Asynchronously calls a function from the script.
  27548. *
  27549. * @param {string} name - The function name.
  27550. * @param {...any} params - A list of parameters.
  27551. * @return {Promise<any>} The result of the function call.
  27552. */
  27553. async callAsync( name, ...params ) {
  27554. const object = this.getObject();
  27555. const method = object[ name ];
  27556. if ( typeof method === 'function' ) {
  27557. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  27558. }
  27559. }
  27560. /**
  27561. * Overwritten since the node types is inferred from the script's output.
  27562. *
  27563. * @param {NodeBuilder} builder - The current node builder
  27564. * @return {string} The node type.
  27565. */
  27566. getNodeType( builder ) {
  27567. return this.getDefaultOutputNode().getNodeType( builder );
  27568. }
  27569. /**
  27570. * Refreshes the script node.
  27571. *
  27572. * @param {?string} [output=null] - An optional output.
  27573. */
  27574. refresh( output = null ) {
  27575. if ( output !== null ) {
  27576. this.getOutput( output ).refresh();
  27577. } else {
  27578. this._refresh();
  27579. }
  27580. }
  27581. /**
  27582. * Returns an object representation of the script.
  27583. *
  27584. * @return {Object} The result object.
  27585. */
  27586. getObject() {
  27587. if ( this.needsUpdate ) this.dispose();
  27588. if ( this._object !== null ) return this._object;
  27589. //
  27590. const refresh = () => this.refresh();
  27591. const setOutput = ( id, value ) => this.setOutput( id, value );
  27592. const parameters = new Parameters( this );
  27593. const THREE = ScriptableNodeResources.get( 'THREE' );
  27594. const TSL = ScriptableNodeResources.get( 'TSL' );
  27595. const method = this.getMethod();
  27596. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  27597. this._object = method( ...params );
  27598. const layout = this._object.layout;
  27599. if ( layout ) {
  27600. if ( layout.cache === false ) {
  27601. this._local.clear();
  27602. }
  27603. // default output
  27604. this._output.outputType = layout.outputType || null;
  27605. if ( Array.isArray( layout.elements ) ) {
  27606. for ( const element of layout.elements ) {
  27607. const id = element.id || element.name;
  27608. if ( element.inputType ) {
  27609. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  27610. this.getParameter( id ).inputType = element.inputType;
  27611. }
  27612. if ( element.outputType ) {
  27613. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  27614. this.getOutput( id ).outputType = element.outputType;
  27615. }
  27616. }
  27617. }
  27618. }
  27619. return this._object;
  27620. }
  27621. deserialize( data ) {
  27622. super.deserialize( data );
  27623. for ( const name in this.parameters ) {
  27624. let valueNode = this.parameters[ name ];
  27625. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  27626. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  27627. }
  27628. }
  27629. /**
  27630. * Returns the layout of the script.
  27631. *
  27632. * @return {Object} The script's layout.
  27633. */
  27634. getLayout() {
  27635. return this.getObject().layout;
  27636. }
  27637. /**
  27638. * Returns default node output of the script.
  27639. *
  27640. * @return {Node} The default node output.
  27641. */
  27642. getDefaultOutputNode() {
  27643. const output = this.getDefaultOutput().value;
  27644. if ( output && output.isNode ) {
  27645. return output;
  27646. }
  27647. return float();
  27648. }
  27649. /**
  27650. * Returns default output of the script.
  27651. *
  27652. * @return {ScriptableValueNode} The default output.
  27653. */
  27654. getDefaultOutput() {
  27655. return this._exec()._output;
  27656. }
  27657. /**
  27658. * Returns a function created from the node's script.
  27659. *
  27660. * @return {Function} The function representing the node's code.
  27661. */
  27662. getMethod() {
  27663. if ( this.needsUpdate ) this.dispose();
  27664. if ( this._method !== null ) return this._method;
  27665. //
  27666. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  27667. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  27668. const properties = interfaceProps.join( ', ' );
  27669. const declarations = 'var ' + properties + '; var output = {};\n';
  27670. const returns = '\nreturn { ...output, ' + properties + ' };';
  27671. const code = declarations + this.codeNode.code + returns;
  27672. //
  27673. this._method = new Function( ...parametersProps, code );
  27674. return this._method;
  27675. }
  27676. /**
  27677. * Frees all internal resources.
  27678. */
  27679. dispose() {
  27680. if ( this._method === null ) return;
  27681. if ( this._object && typeof this._object.dispose === 'function' ) {
  27682. this._object.dispose();
  27683. }
  27684. this._method = null;
  27685. this._object = null;
  27686. this._source = null;
  27687. this._value = null;
  27688. this._needsOutputUpdate = true;
  27689. this._output.value = null;
  27690. this._outputs = {};
  27691. }
  27692. setup() {
  27693. return this.getDefaultOutputNode();
  27694. }
  27695. getCacheKey( force ) {
  27696. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  27697. for ( const param in this.parameters ) {
  27698. values.push( this.parameters[ param ].getCacheKey( force ) );
  27699. }
  27700. return hashArray( values );
  27701. }
  27702. set needsUpdate( value ) {
  27703. if ( value === true ) this.dispose();
  27704. }
  27705. get needsUpdate() {
  27706. return this.source !== this._source;
  27707. }
  27708. /**
  27709. * Executes the `main` function of the script.
  27710. *
  27711. * @private
  27712. * @return {ScriptableNode} A reference to this node.
  27713. */
  27714. _exec() {
  27715. if ( this.codeNode === null ) return this;
  27716. if ( this._needsOutputUpdate === true ) {
  27717. this._value = this.call( 'main' );
  27718. this._needsOutputUpdate = false;
  27719. }
  27720. this._output.value = this._value;
  27721. return this;
  27722. }
  27723. /**
  27724. * Executes the refresh.
  27725. *
  27726. * @private
  27727. */
  27728. _refresh() {
  27729. this.needsUpdate = true;
  27730. this._exec();
  27731. this._output.refresh();
  27732. }
  27733. }
  27734. /**
  27735. * TSL function for creating a scriptable node.
  27736. *
  27737. * @tsl
  27738. * @function
  27739. * @param {CodeNode} [codeNode] - The code node.
  27740. * @param {?Object} [parameters={}] - The parameters definition.
  27741. * @returns {ScriptableNode}
  27742. */
  27743. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  27744. /**
  27745. * Returns a node that represents the `z` coordinate in view space
  27746. * for the current fragment. It's a different representation of the
  27747. * default depth value.
  27748. *
  27749. * This value can be part of a computation that defines how the fog
  27750. * density increases when moving away from the camera.
  27751. *
  27752. * @param {NodeBuilder} builder - The current node builder.
  27753. * @return {Node} The viewZ node.
  27754. */
  27755. function getViewZNode( builder ) {
  27756. let viewZ;
  27757. const getViewZ = builder.context.getViewZ;
  27758. if ( getViewZ !== undefined ) {
  27759. viewZ = getViewZ( this );
  27760. }
  27761. return ( viewZ || positionView.z ).negate();
  27762. }
  27763. /**
  27764. * Constructs a new range factor node.
  27765. *
  27766. * @tsl
  27767. * @function
  27768. * @param {Node} near - Defines the near value.
  27769. * @param {Node} far - Defines the far value.
  27770. */
  27771. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  27772. const viewZ = getViewZNode( builder );
  27773. return smoothstep( near, far, viewZ );
  27774. } );
  27775. /**
  27776. * Represents an exponential squared fog. This type of fog gives
  27777. * a clear view near the camera and a faster than exponentially
  27778. * densening fog farther from the camera.
  27779. *
  27780. * @tsl
  27781. * @function
  27782. * @param {Node} density - Defines the fog density.
  27783. */
  27784. const densityFogFactor = Fn( ( [ density ], builder ) => {
  27785. const viewZ = getViewZNode( builder );
  27786. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  27787. } );
  27788. /**
  27789. * This class can be used to configure a fog for the scene.
  27790. * Nodes of this type are assigned to `Scene.fogNode`.
  27791. *
  27792. * @tsl
  27793. * @function
  27794. * @param {Node} color - Defines the color of the fog.
  27795. * @param {Node} factor - Defines how the fog is factored in the scene.
  27796. */
  27797. const fog = Fn( ( [ color, factor ] ) => {
  27798. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  27799. } );
  27800. // Deprecated
  27801. /**
  27802. * @tsl
  27803. * @function
  27804. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  27805. *
  27806. * @param {Node} color
  27807. * @param {Node} near
  27808. * @param {Node} far
  27809. * @returns {Function}
  27810. */
  27811. function rangeFog( color, near, far ) { // @deprecated, r171
  27812. warn( 'TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  27813. return fog( color, rangeFogFactor( near, far ) );
  27814. }
  27815. /**
  27816. * @tsl
  27817. * @function
  27818. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  27819. *
  27820. * @param {Node} color
  27821. * @param {Node} density
  27822. * @returns {Function}
  27823. */
  27824. function densityFog( color, density ) { // @deprecated, r171
  27825. warn( 'TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  27826. return fog( color, densityFogFactor( density ) );
  27827. }
  27828. let min = null;
  27829. let max = null;
  27830. /**
  27831. * `RangeNode` generates random instanced attribute data in a defined range.
  27832. * An exemplary use case for this utility node is to generate random per-instance
  27833. * colors:
  27834. * ```js
  27835. * const material = new MeshBasicNodeMaterial();
  27836. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  27837. * const mesh = new InstancedMesh( geometry, material, count );
  27838. * ```
  27839. * @augments Node
  27840. */
  27841. class RangeNode extends Node {
  27842. static get type() {
  27843. return 'RangeNode';
  27844. }
  27845. /**
  27846. * Constructs a new range node.
  27847. *
  27848. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27849. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27850. */
  27851. constructor( minNode = float(), maxNode = float() ) {
  27852. super();
  27853. /**
  27854. * A node defining the lower bound of the range.
  27855. *
  27856. * @type {Node<any>}
  27857. * @default float()
  27858. */
  27859. this.minNode = minNode;
  27860. /**
  27861. * A node defining the upper bound of the range.
  27862. *
  27863. * @type {Node<any>}
  27864. * @default float()
  27865. */
  27866. this.maxNode = maxNode;
  27867. }
  27868. /**
  27869. * Returns the vector length which is computed based on the range definition.
  27870. *
  27871. * @param {NodeBuilder} builder - The current node builder.
  27872. * @return {number} The vector length.
  27873. */
  27874. getVectorLength( builder ) {
  27875. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  27876. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  27877. return minLength > maxLength ? minLength : maxLength;
  27878. }
  27879. /**
  27880. * This method is overwritten since the node type is inferred from range definition.
  27881. *
  27882. * @param {NodeBuilder} builder - The current node builder.
  27883. * @return {string} The node type.
  27884. */
  27885. getNodeType( builder ) {
  27886. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  27887. }
  27888. setup( builder ) {
  27889. const object = builder.object;
  27890. let output = null;
  27891. if ( object.count > 1 ) {
  27892. const minValue = this.minNode.value;
  27893. const maxValue = this.maxNode.value;
  27894. const minLength = builder.getTypeLength( getValueType( minValue ) );
  27895. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  27896. min = min || new Vector4();
  27897. max = max || new Vector4();
  27898. min.setScalar( 0 );
  27899. max.setScalar( 0 );
  27900. if ( minLength === 1 ) min.setScalar( minValue );
  27901. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  27902. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  27903. if ( maxLength === 1 ) max.setScalar( maxValue );
  27904. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  27905. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  27906. const stride = 4;
  27907. const length = stride * object.count;
  27908. const array = new Float32Array( length );
  27909. for ( let i = 0; i < length; i ++ ) {
  27910. const index = i % stride;
  27911. const minElementValue = min.getComponent( index );
  27912. const maxElementValue = max.getComponent( index );
  27913. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  27914. }
  27915. const nodeType = this.getNodeType( builder );
  27916. if ( object.count <= 4096 ) {
  27917. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  27918. } else {
  27919. // TODO: Improve anonymous buffer attribute creation removing this part
  27920. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  27921. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  27922. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  27923. }
  27924. } else {
  27925. output = float( 0 );
  27926. }
  27927. return output;
  27928. }
  27929. }
  27930. /**
  27931. * TSL function for creating a range node.
  27932. *
  27933. * @tsl
  27934. * @function
  27935. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27936. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27937. * @returns {RangeNode}
  27938. */
  27939. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  27940. /**
  27941. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  27942. * about the currently running dispatch and/or the device it is running on.
  27943. *
  27944. * This node can only be used with a WebGPU backend.
  27945. *
  27946. * @augments Node
  27947. */
  27948. class ComputeBuiltinNode extends Node {
  27949. static get type() {
  27950. return 'ComputeBuiltinNode';
  27951. }
  27952. /**
  27953. * Constructs a new compute builtin node.
  27954. *
  27955. * @param {string} builtinName - The built-in name.
  27956. * @param {string} nodeType - The node type.
  27957. */
  27958. constructor( builtinName, nodeType ) {
  27959. super( nodeType );
  27960. /**
  27961. * The built-in name.
  27962. *
  27963. * @private
  27964. * @type {string}
  27965. */
  27966. this._builtinName = builtinName;
  27967. }
  27968. /**
  27969. * This method is overwritten since hash is derived from the built-in name.
  27970. *
  27971. * @param {NodeBuilder} builder - The current node builder.
  27972. * @return {string} The hash.
  27973. */
  27974. getHash( builder ) {
  27975. return this.getBuiltinName( builder );
  27976. }
  27977. /**
  27978. * This method is overwritten since the node type is simply derived from `nodeType`..
  27979. *
  27980. * @param {NodeBuilder} builder - The current node builder.
  27981. * @return {string} The node type.
  27982. */
  27983. getNodeType( /*builder*/ ) {
  27984. return this.nodeType;
  27985. }
  27986. /**
  27987. * Sets the builtin name.
  27988. *
  27989. * @param {string} builtinName - The built-in name.
  27990. * @return {ComputeBuiltinNode} A reference to this node.
  27991. */
  27992. setBuiltinName( builtinName ) {
  27993. this._builtinName = builtinName;
  27994. return this;
  27995. }
  27996. /**
  27997. * Returns the builtin name.
  27998. *
  27999. * @param {NodeBuilder} builder - The current node builder.
  28000. * @return {string} The builtin name.
  28001. */
  28002. getBuiltinName( /*builder*/ ) {
  28003. return this._builtinName;
  28004. }
  28005. /**
  28006. * Whether the current node builder has the builtin or not.
  28007. *
  28008. * @param {NodeBuilder} builder - The current node builder.
  28009. * @return {boolean} Whether the builder has the builtin or not.
  28010. */
  28011. hasBuiltin( builder ) {
  28012. return builder.hasBuiltin( this._builtinName );
  28013. }
  28014. generate( builder, output ) {
  28015. const builtinName = this.getBuiltinName( builder );
  28016. const nodeType = this.getNodeType( builder );
  28017. if ( builder.shaderStage === 'compute' ) {
  28018. return builder.format( builtinName, nodeType, output );
  28019. } else {
  28020. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  28021. return builder.generateConst( nodeType );
  28022. }
  28023. }
  28024. serialize( data ) {
  28025. super.serialize( data );
  28026. data.global = this.global;
  28027. data._builtinName = this._builtinName;
  28028. }
  28029. deserialize( data ) {
  28030. super.deserialize( data );
  28031. this.global = data.global;
  28032. this._builtinName = data._builtinName;
  28033. }
  28034. }
  28035. /**
  28036. * TSL function for creating a compute builtin node.
  28037. *
  28038. * @tsl
  28039. * @function
  28040. * @param {string} name - The built-in name.
  28041. * @param {string} nodeType - The node type.
  28042. * @returns {ComputeBuiltinNode}
  28043. */
  28044. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  28045. /**
  28046. * Represents the number of workgroups dispatched by the compute shader.
  28047. * ```js
  28048. * // Run 512 invocations/threads with a workgroup size of 128.
  28049. * const computeFn = Fn(() => {
  28050. *
  28051. * // numWorkgroups.x = 4
  28052. * storageBuffer.element(0).assign(numWorkgroups.x)
  28053. *
  28054. * })().compute(512, [128]);
  28055. *
  28056. * // Run 512 invocations/threads with the default workgroup size of 64.
  28057. * const computeFn = Fn(() => {
  28058. *
  28059. * // numWorkgroups.x = 8
  28060. * storageBuffer.element(0).assign(numWorkgroups.x)
  28061. *
  28062. * })().compute(512);
  28063. * ```
  28064. *
  28065. * @tsl
  28066. * @type {ComputeBuiltinNode<uvec3>}
  28067. */
  28068. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  28069. /**
  28070. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  28071. * ```js
  28072. * // Execute 12 compute threads with a workgroup size of 3.
  28073. * const computeFn = Fn( () => {
  28074. *
  28075. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  28076. *
  28077. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  28078. *
  28079. * } ).Else( () => {
  28080. *
  28081. * storageBuffer.element( instanceIndex ).assign( 0 );
  28082. *
  28083. * } );
  28084. *
  28085. * } )().compute( 12, [ 3 ] );
  28086. *
  28087. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  28088. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  28089. * ```
  28090. *
  28091. * @tsl
  28092. * @type {ComputeBuiltinNode<uvec3>}
  28093. */
  28094. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  28095. /**
  28096. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  28097. *
  28098. * @tsl
  28099. * @type {ComputeBuiltinNode<uvec3>}
  28100. */
  28101. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  28102. /**
  28103. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  28104. *
  28105. * @tsl
  28106. * @type {ComputeBuiltinNode<uvec3>}
  28107. */
  28108. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  28109. /**
  28110. * A device dependent variable that exposes the size of the current invocation's subgroup.
  28111. *
  28112. * @tsl
  28113. * @type {ComputeBuiltinNode<uint>}
  28114. */
  28115. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  28116. /**
  28117. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  28118. *
  28119. * This node can only be used with a WebGPU backend.
  28120. *
  28121. * @augments Node
  28122. */
  28123. class BarrierNode extends Node {
  28124. /**
  28125. * Constructs a new barrier node.
  28126. *
  28127. * @param {string} scope - The scope defines the behavior of the node.
  28128. */
  28129. constructor( scope ) {
  28130. super();
  28131. this.scope = scope;
  28132. }
  28133. generate( builder ) {
  28134. const { scope } = this;
  28135. const { renderer } = builder;
  28136. if ( renderer.backend.isWebGLBackend === true ) {
  28137. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  28138. } else {
  28139. builder.addLineFlowCode( `${scope}Barrier()`, this );
  28140. }
  28141. }
  28142. }
  28143. /**
  28144. * TSL function for creating a barrier node.
  28145. *
  28146. * @tsl
  28147. * @function
  28148. * @param {string} scope - The scope defines the behavior of the node..
  28149. * @returns {BarrierNode}
  28150. */
  28151. const barrier = nodeProxy( BarrierNode );
  28152. /**
  28153. * TSL function for creating a workgroup barrier. All compute shader
  28154. * invocations must wait for each invocation within a workgroup to
  28155. * complete before the barrier can be surpassed.
  28156. *
  28157. * @tsl
  28158. * @function
  28159. * @returns {BarrierNode}
  28160. */
  28161. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  28162. /**
  28163. * TSL function for creating a storage barrier. All invocations must
  28164. * wait for each access to variables within the 'storage' address space
  28165. * to complete before the barrier can be passed.
  28166. *
  28167. * @tsl
  28168. * @function
  28169. * @returns {BarrierNode}
  28170. */
  28171. const storageBarrier = () => barrier( 'storage' ).toStack();
  28172. /**
  28173. * TSL function for creating a texture barrier. All invocations must
  28174. * wait for each access to variables within the 'texture' address space
  28175. * to complete before the barrier can be passed.
  28176. *
  28177. * @tsl
  28178. * @function
  28179. * @returns {BarrierNode}
  28180. */
  28181. const textureBarrier = () => barrier( 'texture' ).toStack();
  28182. /**
  28183. * Represents an element of a 'workgroup' scoped buffer.
  28184. *
  28185. * @augments ArrayElementNode
  28186. */
  28187. class WorkgroupInfoElementNode extends ArrayElementNode {
  28188. /**
  28189. * Constructs a new workgroup info element node.
  28190. *
  28191. * @param {Node} workgroupInfoNode - The workgroup info node.
  28192. * @param {Node} indexNode - The index node that defines the element access.
  28193. */
  28194. constructor( workgroupInfoNode, indexNode ) {
  28195. super( workgroupInfoNode, indexNode );
  28196. /**
  28197. * This flag can be used for type testing.
  28198. *
  28199. * @type {boolean}
  28200. * @readonly
  28201. * @default true
  28202. */
  28203. this.isWorkgroupInfoElementNode = true;
  28204. }
  28205. generate( builder, output ) {
  28206. let snippet;
  28207. const isAssignContext = builder.context.assign;
  28208. snippet = super.generate( builder );
  28209. if ( isAssignContext !== true ) {
  28210. const type = this.getNodeType( builder );
  28211. snippet = builder.format( snippet, type, output );
  28212. }
  28213. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  28214. return snippet;
  28215. }
  28216. }
  28217. /**
  28218. * A node allowing the user to create a 'workgroup' scoped buffer within the
  28219. * context of a compute shader. Typically, workgroup scoped buffers are
  28220. * created to hold data that is transferred from a global storage scope into
  28221. * a local workgroup scope. For invocations within a workgroup, data
  28222. * access speeds on 'workgroup' scoped buffers can be significantly faster
  28223. * than similar access operations on globally accessible storage buffers.
  28224. *
  28225. * This node can only be used with a WebGPU backend.
  28226. *
  28227. * @augments Node
  28228. */
  28229. class WorkgroupInfoNode extends Node {
  28230. /**
  28231. * Constructs a new buffer scoped to type scope.
  28232. *
  28233. * @param {string} scope - TODO.
  28234. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  28235. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  28236. */
  28237. constructor( scope, bufferType, bufferCount = 0 ) {
  28238. super( bufferType );
  28239. /**
  28240. * The buffer type.
  28241. *
  28242. * @type {string}
  28243. */
  28244. this.bufferType = bufferType;
  28245. /**
  28246. * The buffer count.
  28247. *
  28248. * @type {number}
  28249. * @default 0
  28250. */
  28251. this.bufferCount = bufferCount;
  28252. /**
  28253. * This flag can be used for type testing.
  28254. *
  28255. * @type {boolean}
  28256. * @readonly
  28257. * @default true
  28258. */
  28259. this.isWorkgroupInfoNode = true;
  28260. /**
  28261. * The data type of the array buffer.
  28262. *
  28263. * @type {string}
  28264. */
  28265. this.elementType = bufferType;
  28266. /**
  28267. * TODO.
  28268. *
  28269. * @type {string}
  28270. */
  28271. this.scope = scope;
  28272. /**
  28273. * The name of the workgroup scoped buffer.
  28274. *
  28275. * @type {string}
  28276. * @default ''
  28277. */
  28278. this.name = '';
  28279. }
  28280. /**
  28281. * Sets the name of this node.
  28282. *
  28283. * @param {string} name - The name to set.
  28284. * @return {WorkgroupInfoNode} A reference to this node.
  28285. */
  28286. setName( name ) {
  28287. this.name = name;
  28288. return this;
  28289. }
  28290. /**
  28291. * Sets the name/label of this node.
  28292. *
  28293. * @deprecated
  28294. * @param {string} name - The name to set.
  28295. * @return {WorkgroupInfoNode} A reference to this node.
  28296. */
  28297. label( name ) {
  28298. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  28299. return this.setName( name );
  28300. }
  28301. /**
  28302. * Sets the scope of this node.
  28303. *
  28304. * @param {string} scope - The scope to set.
  28305. * @return {WorkgroupInfoNode} A reference to this node.
  28306. */
  28307. setScope( scope ) {
  28308. this.scope = scope;
  28309. return this;
  28310. }
  28311. /**
  28312. * The data type of the array buffer.
  28313. *
  28314. * @return {string} The element type.
  28315. */
  28316. getElementType() {
  28317. return this.elementType;
  28318. }
  28319. /**
  28320. * Overwrites the default implementation since the input type
  28321. * is inferred from the scope.
  28322. *
  28323. * @param {NodeBuilder} builder - The current node builder.
  28324. * @return {string} The input type.
  28325. */
  28326. getInputType( /*builder*/ ) {
  28327. return `${this.scope}Array`;
  28328. }
  28329. /**
  28330. * This method can be used to access elements via an index node.
  28331. *
  28332. * @param {IndexNode} indexNode - indexNode.
  28333. * @return {WorkgroupInfoElementNode} A reference to an element.
  28334. */
  28335. element( indexNode ) {
  28336. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  28337. }
  28338. generate( builder ) {
  28339. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  28340. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  28341. }
  28342. }
  28343. /**
  28344. * TSL function for creating a workgroup info node.
  28345. * Creates a new 'workgroup' scoped array buffer.
  28346. *
  28347. * @tsl
  28348. * @function
  28349. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  28350. * @param {number} [count=0] - The number of elements in the buffer.
  28351. * @returns {WorkgroupInfoNode}
  28352. */
  28353. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  28354. /**
  28355. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  28356. * within a shader. In an atomic function, any modification to an atomic variable will
  28357. * occur as an indivisible step with a defined order relative to other modifications.
  28358. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  28359. * atomic operations will not interfere with each other.
  28360. *
  28361. * This node can only be used with a WebGPU backend.
  28362. *
  28363. * @augments Node
  28364. */
  28365. class AtomicFunctionNode extends Node {
  28366. static get type() {
  28367. return 'AtomicFunctionNode';
  28368. }
  28369. /**
  28370. * Constructs a new atomic function node.
  28371. *
  28372. * @param {string} method - The signature of the atomic function to construct.
  28373. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28374. * @param {Node} valueNode - The value that mutates the atomic variable.
  28375. */
  28376. constructor( method, pointerNode, valueNode ) {
  28377. super( 'uint' );
  28378. /**
  28379. * The signature of the atomic function to construct.
  28380. *
  28381. * @type {string}
  28382. */
  28383. this.method = method;
  28384. /**
  28385. * An atomic variable or element of an atomic buffer.
  28386. *
  28387. * @type {Node}
  28388. */
  28389. this.pointerNode = pointerNode;
  28390. /**
  28391. * A value that modifies the atomic variable.
  28392. *
  28393. * @type {Node}
  28394. */
  28395. this.valueNode = valueNode;
  28396. /**
  28397. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  28398. *
  28399. * @type {boolean}
  28400. * @default true
  28401. */
  28402. this.parents = true;
  28403. }
  28404. /**
  28405. * Overwrites the default implementation to return the type of
  28406. * the pointer node.
  28407. *
  28408. * @param {NodeBuilder} builder - The current node builder.
  28409. * @return {string} The input type.
  28410. */
  28411. getInputType( builder ) {
  28412. return this.pointerNode.getNodeType( builder );
  28413. }
  28414. /**
  28415. * Overwritten since the node type is inferred from the input type.
  28416. *
  28417. * @param {NodeBuilder} builder - The current node builder.
  28418. * @return {string} The node type.
  28419. */
  28420. getNodeType( builder ) {
  28421. return this.getInputType( builder );
  28422. }
  28423. generate( builder ) {
  28424. const properties = builder.getNodeProperties( this );
  28425. const parents = properties.parents;
  28426. const method = this.method;
  28427. const type = this.getNodeType( builder );
  28428. const inputType = this.getInputType( builder );
  28429. const a = this.pointerNode;
  28430. const b = this.valueNode;
  28431. const params = [];
  28432. params.push( `&${ a.build( builder, inputType ) }` );
  28433. if ( b !== null ) {
  28434. params.push( b.build( builder, inputType ) );
  28435. }
  28436. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  28437. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  28438. if ( isVoid ) {
  28439. builder.addLineFlowCode( methodSnippet, this );
  28440. } else {
  28441. if ( properties.constNode === undefined ) {
  28442. properties.constNode = expression( methodSnippet, type ).toConst();
  28443. }
  28444. return properties.constNode.build( builder );
  28445. }
  28446. }
  28447. }
  28448. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  28449. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  28450. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  28451. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  28452. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  28453. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  28454. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  28455. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  28456. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  28457. /**
  28458. * TSL function for creating an atomic function node.
  28459. *
  28460. * @tsl
  28461. * @function
  28462. * @param {string} method - The signature of the atomic function to construct.
  28463. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28464. * @param {Node} valueNode - The value that mutates the atomic variable.
  28465. * @returns {AtomicFunctionNode}
  28466. */
  28467. const atomicNode = nodeProxy( AtomicFunctionNode );
  28468. /**
  28469. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  28470. *
  28471. * @tsl
  28472. * @function
  28473. * @param {string} method - The signature of the atomic function to construct.
  28474. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28475. * @param {Node} valueNode - The value that mutates the atomic variable.
  28476. * @returns {AtomicFunctionNode}
  28477. */
  28478. const atomicFunc = ( method, pointerNode, valueNode ) => {
  28479. return atomicNode( method, pointerNode, valueNode ).toStack();
  28480. };
  28481. /**
  28482. * Loads the value stored in the atomic variable.
  28483. *
  28484. * @tsl
  28485. * @function
  28486. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28487. * @returns {AtomicFunctionNode}
  28488. */
  28489. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  28490. /**
  28491. * Stores a value in the atomic variable.
  28492. *
  28493. * @tsl
  28494. * @function
  28495. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28496. * @param {Node} valueNode - The value that mutates the atomic variable.
  28497. * @returns {AtomicFunctionNode}
  28498. */
  28499. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  28500. /**
  28501. * Increments the value stored in the atomic variable.
  28502. *
  28503. * @tsl
  28504. * @function
  28505. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28506. * @param {Node} valueNode - The value that mutates the atomic variable.
  28507. * @returns {AtomicFunctionNode}
  28508. */
  28509. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  28510. /**
  28511. * Decrements the value stored in the atomic variable.
  28512. *
  28513. * @tsl
  28514. * @function
  28515. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28516. * @param {Node} valueNode - The value that mutates the atomic variable.
  28517. * @returns {AtomicFunctionNode}
  28518. */
  28519. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  28520. /**
  28521. * Stores in an atomic variable the maximum between its current value and a parameter.
  28522. *
  28523. * @tsl
  28524. * @function
  28525. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28526. * @param {Node} valueNode - The value that mutates the atomic variable.
  28527. * @returns {AtomicFunctionNode}
  28528. */
  28529. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  28530. /**
  28531. * Stores in an atomic variable the minimum between its current value and a parameter.
  28532. *
  28533. * @tsl
  28534. * @function
  28535. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28536. * @param {Node} valueNode - The value that mutates the atomic variable.
  28537. * @returns {AtomicFunctionNode}
  28538. */
  28539. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  28540. /**
  28541. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  28542. *
  28543. * @tsl
  28544. * @function
  28545. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28546. * @param {Node} valueNode - The value that mutates the atomic variable.
  28547. * @returns {AtomicFunctionNode}
  28548. */
  28549. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  28550. /**
  28551. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  28552. *
  28553. * @tsl
  28554. * @function
  28555. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28556. * @param {Node} valueNode - The value that mutates the atomic variable.
  28557. * @returns {AtomicFunctionNode}
  28558. */
  28559. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  28560. /**
  28561. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  28562. *
  28563. * @tsl
  28564. * @function
  28565. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28566. * @param {Node} valueNode - The value that mutates the atomic variable.
  28567. * @returns {AtomicFunctionNode}
  28568. */
  28569. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  28570. /**
  28571. * This class represents a set of built in WGSL shader functions that sync
  28572. * synchronously execute an operation across a subgroup, or 'warp', of compute
  28573. * or fragment shader invocations within a workgroup. Typically, these functions
  28574. * will synchronously execute an operation using data from all active invocations
  28575. * within the subgroup, then broadcast that result to all active invocations. In
  28576. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  28577. * (DirectX/HLSL) or warp intrinsics (CUDA).
  28578. *
  28579. * @augments TempNode
  28580. */
  28581. class SubgroupFunctionNode extends TempNode {
  28582. static get type() {
  28583. return 'SubgroupFunctionNode';
  28584. }
  28585. /**
  28586. * Constructs a new function node.
  28587. *
  28588. * @param {string} method - The subgroup/wave intrinsic method to construct.
  28589. * @param {Node} [aNode=null] - The method's first argument.
  28590. * @param {Node} [bNode=null] - The method's second argument.
  28591. */
  28592. constructor( method, aNode = null, bNode = null ) {
  28593. super();
  28594. /**
  28595. * The subgroup/wave intrinsic method to construct.
  28596. *
  28597. * @type {String}
  28598. */
  28599. this.method = method;
  28600. /**
  28601. * The method's first argument.
  28602. *
  28603. * @type {Node}
  28604. */
  28605. this.aNode = aNode;
  28606. /**
  28607. * The method's second argument.
  28608. *
  28609. * @type {Node}
  28610. */
  28611. this.bNode = bNode;
  28612. }
  28613. getInputType( builder ) {
  28614. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  28615. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  28616. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  28617. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  28618. if ( aLen > bLen ) {
  28619. return aType;
  28620. } else {
  28621. return bType;
  28622. }
  28623. }
  28624. getNodeType( builder ) {
  28625. const method = this.method;
  28626. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  28627. return 'bool';
  28628. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  28629. return 'uvec4';
  28630. } else {
  28631. return this.getInputType( builder );
  28632. }
  28633. }
  28634. generate( builder, output ) {
  28635. const method = this.method;
  28636. const type = this.getNodeType( builder );
  28637. const inputType = this.getInputType( builder );
  28638. const a = this.aNode;
  28639. const b = this.bNode;
  28640. const params = [];
  28641. if (
  28642. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  28643. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  28644. method === SubgroupFunctionNode.QUAD_BROADCAST
  28645. ) {
  28646. const bType = b.getNodeType( builder );
  28647. params.push(
  28648. a.build( builder, type ),
  28649. b.build( builder, bType === 'float' ? 'int' : type )
  28650. );
  28651. } else if (
  28652. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  28653. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  28654. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  28655. ) {
  28656. params.push(
  28657. a.build( builder, type ),
  28658. b.build( builder, 'uint' )
  28659. );
  28660. } else {
  28661. if ( a !== null ) params.push( a.build( builder, inputType ) );
  28662. if ( b !== null ) params.push( b.build( builder, inputType ) );
  28663. }
  28664. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  28665. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  28666. }
  28667. serialize( data ) {
  28668. super.serialize( data );
  28669. data.method = this.method;
  28670. }
  28671. deserialize( data ) {
  28672. super.deserialize( data );
  28673. this.method = data.method;
  28674. }
  28675. }
  28676. // 0 inputs
  28677. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  28678. // 1 input
  28679. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  28680. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  28681. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  28682. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  28683. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  28684. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  28685. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  28686. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  28687. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  28688. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  28689. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  28690. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  28691. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  28692. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  28693. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  28694. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  28695. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  28696. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  28697. // 2 inputs
  28698. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  28699. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  28700. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  28701. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  28702. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  28703. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  28704. /**
  28705. * Returns true if this invocation has the lowest subgroup_invocation_id
  28706. * among active invocations in the subgroup.
  28707. *
  28708. * @tsl
  28709. * @method
  28710. * @return {bool} The result of the computation.
  28711. */
  28712. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  28713. /**
  28714. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  28715. * is 1 if pred is true for that active invocation and 0 otherwise.
  28716. *
  28717. * @tsl
  28718. * @method
  28719. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  28720. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  28721. */
  28722. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  28723. /**
  28724. * A reduction that adds e among all active invocations and returns that result.
  28725. *
  28726. * @tsl
  28727. * @method
  28728. * @param {number} e - The value provided to the reduction by the current invocation.
  28729. * @return {number} The accumulated result of the reduction operation.
  28730. */
  28731. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  28732. /**
  28733. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  28734. *
  28735. * @tsl
  28736. * @method
  28737. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  28738. * @return {number} The accumulated result of the inclusive scan operation.
  28739. */
  28740. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  28741. /**
  28742. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  28743. *
  28744. * @tsl
  28745. * @method
  28746. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  28747. * @return {number} The accumulated result of the exclusive scan operation.
  28748. */
  28749. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  28750. /**
  28751. * A reduction that multiplies e among all active invocations and returns that result.
  28752. *
  28753. * @tsl
  28754. * @method
  28755. * @param {number} e - The value provided to the reduction by the current invocation.
  28756. * @return {number} The accumulated result of the reduction operation.
  28757. */
  28758. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  28759. /**
  28760. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  28761. *
  28762. * @tsl
  28763. * @method
  28764. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  28765. * @return {number} The accumulated result of the inclusive scan operation.
  28766. */
  28767. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  28768. /**
  28769. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  28770. *
  28771. * @tsl
  28772. * @method
  28773. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  28774. * @return {number} The accumulated result of the exclusive scan operation.
  28775. */
  28776. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  28777. /**
  28778. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  28779. *
  28780. * @tsl
  28781. * @method
  28782. * @param {number} e - The value provided to the reduction by the current invocation.
  28783. * @return {number} The result of the reduction operation.
  28784. */
  28785. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  28786. /**
  28787. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  28788. *
  28789. * @tsl
  28790. * @method
  28791. * @param {number} e - The value provided to the reduction by the current invocation.
  28792. * @return {number} The result of the reduction operation.
  28793. */
  28794. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  28795. /**
  28796. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  28797. *
  28798. * @tsl
  28799. * @method
  28800. * @param {number} e - The value provided to the reduction by the current invocation.
  28801. * @return {number} The result of the reduction operation.
  28802. */
  28803. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  28804. /**
  28805. * A reduction that performs a min of e among all active invocations and returns that result.
  28806. *
  28807. * @tsl
  28808. * @method
  28809. * @param {number} e - The value provided to the reduction by the current invocation.
  28810. * @return {number} The result of the reduction operation.
  28811. */
  28812. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  28813. /**
  28814. * A reduction that performs a max of e among all active invocations and returns that result.
  28815. *
  28816. * @tsl
  28817. * @method
  28818. * @param {number} e - The value provided to the reduction by the current invocation.
  28819. * @return {number} The result of the reduction operation.
  28820. */
  28821. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  28822. /**
  28823. * Returns true if e is true for all active invocations in the subgroup.
  28824. *
  28825. * @tsl
  28826. * @method
  28827. * @return {bool} The result of the computation.
  28828. */
  28829. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  28830. /**
  28831. * Returns true if e is true for any active invocation in the subgroup
  28832. *
  28833. * @tsl
  28834. * @method
  28835. * @return {bool} The result of the computation.
  28836. */
  28837. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  28838. /**
  28839. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  28840. *
  28841. * @tsl
  28842. * @method
  28843. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  28844. * @param {number} id - The subgroup invocation to broadcast from.
  28845. * @return {number} The broadcast value.
  28846. */
  28847. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  28848. /**
  28849. * Swaps e between invocations in the quad in the X direction.
  28850. *
  28851. * @tsl
  28852. * @method
  28853. * @param {number} e - The value to swap from the current invocation.
  28854. * @return {number} The value received from the swap operation.
  28855. */
  28856. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  28857. /**
  28858. * Swaps e between invocations in the quad in the Y direction.
  28859. *
  28860. * @tsl
  28861. * @method
  28862. * @param {number} e - The value to swap from the current invocation.
  28863. * @return {number} The value received from the swap operation.
  28864. */
  28865. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  28866. /**
  28867. * Swaps e between invocations in the quad diagonally.
  28868. *
  28869. * @tsl
  28870. * @method
  28871. * @param {number} e - The value to swap from the current invocation.
  28872. * @return {number} The value received from the swap operation.
  28873. */
  28874. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  28875. /**
  28876. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  28877. *
  28878. * @tsl
  28879. * @method
  28880. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  28881. * @param {number} id - The subgroup invocation to broadcast from.
  28882. * @return {number} The broadcast value.
  28883. */
  28884. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  28885. /**
  28886. * Returns v from the active invocation whose subgroup_invocation_id matches id
  28887. *
  28888. * @tsl
  28889. * @method
  28890. * @param {number} v - The value to return from subgroup invocation id^mask.
  28891. * @param {number} id - The subgroup invocation which returns the value v.
  28892. * @return {number} The broadcast value.
  28893. */
  28894. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  28895. /**
  28896. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  28897. *
  28898. * @tsl
  28899. * @method
  28900. * @param {number} v - The value to return from subgroup invocation id^mask.
  28901. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  28902. * @return {number} The broadcast value.
  28903. */
  28904. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  28905. /**
  28906. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  28907. *
  28908. * @tsl
  28909. * @method
  28910. * @param {number} v - The value to return from subgroup invocation id^mask.
  28911. * @param {number} delta - A value that offsets the current in.
  28912. * @return {number} The broadcast value.
  28913. */
  28914. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  28915. /**
  28916. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  28917. *
  28918. * @tsl
  28919. * @method
  28920. * @param {number} v - The value to return from subgroup invocation id^mask.
  28921. * @param {number} delta - A value that offsets the current subgroup invocation.
  28922. * @return {number} The broadcast value.
  28923. */
  28924. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  28925. /**
  28926. * Broadcasts e from the quad invocation with id equal to id.
  28927. *
  28928. * @tsl
  28929. * @method
  28930. * @param {number} e - The value to broadcast.
  28931. * @return {number} The broadcast value.
  28932. */
  28933. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  28934. let uniformsLib;
  28935. function getLightData( light ) {
  28936. uniformsLib = uniformsLib || new WeakMap();
  28937. let uniforms = uniformsLib.get( light );
  28938. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  28939. return uniforms;
  28940. }
  28941. /**
  28942. * TSL function for getting a shadow matrix uniform node for the given light.
  28943. *
  28944. * @tsl
  28945. * @function
  28946. * @param {Light} light -The light source.
  28947. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  28948. */
  28949. function lightShadowMatrix( light ) {
  28950. const data = getLightData( light );
  28951. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  28952. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  28953. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  28954. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  28955. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  28956. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  28957. light.shadow.camera.updateProjectionMatrix();
  28958. }
  28959. light.shadow.updateMatrices( light );
  28960. }
  28961. return light.shadow.matrix;
  28962. } ) );
  28963. }
  28964. /**
  28965. * TSL function for getting projected uv coordinates for the given light.
  28966. * Relevant when using maps with spot lights.
  28967. *
  28968. * @tsl
  28969. * @function
  28970. * @param {Light} light -The light source.
  28971. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  28972. * @returns {Node<vec3>} The projected uvs.
  28973. */
  28974. function lightProjectionUV( light, position = positionWorld ) {
  28975. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  28976. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  28977. return projectionUV;
  28978. }
  28979. /**
  28980. * TSL function for getting the position in world space for the given light.
  28981. *
  28982. * @tsl
  28983. * @function
  28984. * @param {Light} light -The light source.
  28985. * @returns {UniformNode<vec3>} The light's position in world space.
  28986. */
  28987. function lightPosition( light ) {
  28988. const data = getLightData( light );
  28989. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  28990. }
  28991. /**
  28992. * TSL function for getting the light target position in world space for the given light.
  28993. *
  28994. * @tsl
  28995. * @function
  28996. * @param {Light} light -The light source.
  28997. * @returns {UniformNode<vec3>} The light target position in world space.
  28998. */
  28999. function lightTargetPosition( light ) {
  29000. const data = getLightData( light );
  29001. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  29002. }
  29003. /**
  29004. * TSL function for getting the position in view space for the given light.
  29005. *
  29006. * @tsl
  29007. * @function
  29008. * @param {Light} light - The light source.
  29009. * @returns {UniformNode<vec3>} The light's position in view space.
  29010. */
  29011. function lightViewPosition( light ) {
  29012. const data = getLightData( light );
  29013. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  29014. self.value = self.value || new Vector3();
  29015. self.value.setFromMatrixPosition( light.matrixWorld );
  29016. self.value.applyMatrix4( camera.matrixWorldInverse );
  29017. } ) );
  29018. }
  29019. /**
  29020. * TSL function for getting the light target direction for the given light.
  29021. *
  29022. * @tsl
  29023. * @function
  29024. * @param {Light} light -The light source.
  29025. * @returns {Node<vec3>} The light's target direction.
  29026. */
  29027. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  29028. const sortLights = ( lights ) => {
  29029. return lights.sort( ( a, b ) => a.id - b.id );
  29030. };
  29031. const getLightNodeById = ( id, lightNodes ) => {
  29032. for ( const lightNode of lightNodes ) {
  29033. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  29034. return lightNode;
  29035. }
  29036. }
  29037. return null;
  29038. };
  29039. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  29040. const _hashData = [];
  29041. /**
  29042. * This node represents the scene's lighting and manages the lighting model's life cycle
  29043. * for the current build 3D object. It is responsible for computing the total outgoing
  29044. * light in a given lighting context.
  29045. *
  29046. * @augments Node
  29047. */
  29048. class LightsNode extends Node {
  29049. static get type() {
  29050. return 'LightsNode';
  29051. }
  29052. /**
  29053. * Constructs a new lights node.
  29054. */
  29055. constructor() {
  29056. super( 'vec3' );
  29057. /**
  29058. * A node representing the total diffuse light.
  29059. *
  29060. * @type {Node<vec3>}
  29061. */
  29062. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  29063. /**
  29064. * A node representing the total specular light.
  29065. *
  29066. * @type {Node<vec3>}
  29067. */
  29068. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  29069. /**
  29070. * A node representing the outgoing light.
  29071. *
  29072. * @type {Node<vec3>}
  29073. */
  29074. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  29075. /**
  29076. * An array representing the lights in the scene.
  29077. *
  29078. * @private
  29079. * @type {Array<Light>}
  29080. */
  29081. this._lights = [];
  29082. /**
  29083. * For each light in the scene, this node will create a
  29084. * corresponding light node.
  29085. *
  29086. * @private
  29087. * @type {?Array<LightingNode>}
  29088. * @default null
  29089. */
  29090. this._lightNodes = null;
  29091. /**
  29092. * A hash for identifying the current light nodes setup.
  29093. *
  29094. * @private
  29095. * @type {?string}
  29096. * @default null
  29097. */
  29098. this._lightNodesHash = null;
  29099. /**
  29100. * `LightsNode` sets this property to `true` by default.
  29101. *
  29102. * @type {boolean}
  29103. * @default true
  29104. */
  29105. this.global = true;
  29106. }
  29107. /**
  29108. * Overwrites the default {@link Node#customCacheKey} implementation by including
  29109. * light data into the cache key.
  29110. *
  29111. * @return {number} The custom cache key.
  29112. */
  29113. customCacheKey() {
  29114. const lights = this._lights;
  29115. for ( let i = 0; i < lights.length; i ++ ) {
  29116. const light = lights[ i ];
  29117. _hashData.push( light.id );
  29118. _hashData.push( light.castShadow ? 1 : 0 );
  29119. if ( light.isSpotLight === true ) {
  29120. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  29121. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  29122. _hashData.push( hashMap, hashColorNode );
  29123. }
  29124. }
  29125. const cacheKey = hashArray( _hashData );
  29126. _hashData.length = 0;
  29127. return cacheKey;
  29128. }
  29129. /**
  29130. * Computes a hash value for identifying the current light nodes setup.
  29131. *
  29132. * @param {NodeBuilder} builder - A reference to the current node builder.
  29133. * @return {string} The computed hash.
  29134. */
  29135. getHash( builder ) {
  29136. if ( this._lightNodesHash === null ) {
  29137. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  29138. const hash = [];
  29139. for ( const lightNode of this._lightNodes ) {
  29140. hash.push( lightNode.getHash() );
  29141. }
  29142. this._lightNodesHash = 'lights-' + hash.join( ',' );
  29143. }
  29144. return this._lightNodesHash;
  29145. }
  29146. analyze( builder ) {
  29147. const properties = builder.getNodeProperties( this );
  29148. for ( const node of properties.nodes ) {
  29149. node.build( builder );
  29150. }
  29151. properties.outputNode.build( builder );
  29152. }
  29153. /**
  29154. * Creates lighting nodes for each scene light. This makes it possible to further
  29155. * process lights in the node system.
  29156. *
  29157. * @param {NodeBuilder} builder - A reference to the current node builder.
  29158. */
  29159. setupLightsNode( builder ) {
  29160. const lightNodes = [];
  29161. const previousLightNodes = this._lightNodes;
  29162. const lights = sortLights( this._lights );
  29163. const nodeLibrary = builder.renderer.library;
  29164. for ( const light of lights ) {
  29165. if ( light.isNode ) {
  29166. lightNodes.push( nodeObject( light ) );
  29167. } else {
  29168. let lightNode = null;
  29169. if ( previousLightNodes !== null ) {
  29170. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  29171. }
  29172. if ( lightNode === null ) {
  29173. // find the corresponding node type for a given light
  29174. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  29175. if ( lightNodeClass === null ) {
  29176. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  29177. continue;
  29178. }
  29179. let lightNode = null;
  29180. if ( ! _lightsNodeRef.has( light ) ) {
  29181. lightNode = nodeObject( new lightNodeClass( light ) );
  29182. _lightsNodeRef.set( light, lightNode );
  29183. } else {
  29184. lightNode = _lightsNodeRef.get( light );
  29185. }
  29186. lightNodes.push( lightNode );
  29187. }
  29188. }
  29189. }
  29190. this._lightNodes = lightNodes;
  29191. }
  29192. /**
  29193. * Sets up a direct light in the lighting model.
  29194. *
  29195. * @param {Object} builder - The builder object containing the context and stack.
  29196. * @param {Object} lightNode - The light node.
  29197. * @param {Object} lightData - The light object containing color and direction properties.
  29198. */
  29199. setupDirectLight( builder, lightNode, lightData ) {
  29200. const { lightingModel, reflectedLight } = builder.context;
  29201. lightingModel.direct( {
  29202. ...lightData,
  29203. lightNode,
  29204. reflectedLight
  29205. }, builder );
  29206. }
  29207. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  29208. const { lightingModel, reflectedLight } = builder.context;
  29209. lightingModel.directRectArea( {
  29210. ...lightData,
  29211. lightNode,
  29212. reflectedLight
  29213. }, builder );
  29214. }
  29215. /**
  29216. * Setups the internal lights by building all respective
  29217. * light nodes.
  29218. *
  29219. * @param {NodeBuilder} builder - A reference to the current node builder.
  29220. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  29221. */
  29222. setupLights( builder, lightNodes ) {
  29223. for ( const lightNode of lightNodes ) {
  29224. lightNode.build( builder );
  29225. }
  29226. }
  29227. getLightNodes( builder ) {
  29228. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  29229. return this._lightNodes;
  29230. }
  29231. /**
  29232. * The implementation makes sure that for each light in the scene
  29233. * there is a corresponding light node. By building the light nodes
  29234. * and evaluating the lighting model the outgoing light is computed.
  29235. *
  29236. * @param {NodeBuilder} builder - A reference to the current node builder.
  29237. * @return {Node<vec3>} A node representing the outgoing light.
  29238. */
  29239. setup( builder ) {
  29240. const currentLightsNode = builder.lightsNode;
  29241. builder.lightsNode = this;
  29242. //
  29243. let outgoingLightNode = this.outgoingLightNode;
  29244. const context = builder.context;
  29245. const lightingModel = context.lightingModel;
  29246. const properties = builder.getNodeProperties( this );
  29247. if ( lightingModel ) {
  29248. const { totalDiffuseNode, totalSpecularNode } = this;
  29249. context.outgoingLight = outgoingLightNode;
  29250. const stack = builder.addStack();
  29251. //
  29252. properties.nodes = stack.nodes;
  29253. //
  29254. lightingModel.start( builder );
  29255. //
  29256. const { backdrop, backdropAlpha } = context;
  29257. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  29258. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  29259. if ( backdrop !== null ) {
  29260. if ( backdropAlpha !== null ) {
  29261. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  29262. } else {
  29263. totalDiffuse = vec3( backdrop );
  29264. }
  29265. context.material.transparent = true;
  29266. }
  29267. totalDiffuseNode.assign( totalDiffuse );
  29268. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  29269. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  29270. //
  29271. lightingModel.finish( builder );
  29272. //
  29273. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  29274. } else {
  29275. properties.nodes = [];
  29276. }
  29277. //
  29278. builder.lightsNode = currentLightsNode;
  29279. return outgoingLightNode;
  29280. }
  29281. /**
  29282. * Configures this node with an array of lights.
  29283. *
  29284. * @param {Array<Light>} lights - An array of lights.
  29285. * @return {LightsNode} A reference to this node.
  29286. */
  29287. setLights( lights ) {
  29288. this._lights = lights;
  29289. this._lightNodes = null;
  29290. this._lightNodesHash = null;
  29291. return this;
  29292. }
  29293. /**
  29294. * Returns an array of the scene's lights.
  29295. *
  29296. * @return {Array<Light>} The scene's lights.
  29297. */
  29298. getLights() {
  29299. return this._lights;
  29300. }
  29301. /**
  29302. * Whether the scene has lights or not.
  29303. *
  29304. * @type {boolean}
  29305. */
  29306. get hasLights() {
  29307. return this._lights.length > 0;
  29308. }
  29309. }
  29310. /**
  29311. * TSL function for creating an instance of `LightsNode` and configuring
  29312. * it with the given array of lights.
  29313. *
  29314. * @tsl
  29315. * @function
  29316. * @param {Array<Light>} lights - An array of lights.
  29317. * @return {LightsNode} The created lights node.
  29318. */
  29319. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  29320. /**
  29321. * Base class for all shadow nodes.
  29322. *
  29323. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  29324. * Lighting nodes might share the same shadow node type or use specific ones depending on
  29325. * their requirements.
  29326. *
  29327. * @augments Node
  29328. */
  29329. class ShadowBaseNode extends Node {
  29330. static get type() {
  29331. return 'ShadowBaseNode';
  29332. }
  29333. /**
  29334. * Constructs a new shadow base node.
  29335. *
  29336. * @param {Light} light - The shadow casting light.
  29337. */
  29338. constructor( light ) {
  29339. super();
  29340. /**
  29341. * The shadow casting light.
  29342. *
  29343. * @type {Light}
  29344. */
  29345. this.light = light;
  29346. /**
  29347. * Overwritten since shadows are updated by default per render.
  29348. *
  29349. * @type {string}
  29350. * @default 'render'
  29351. */
  29352. this.updateBeforeType = NodeUpdateType.RENDER;
  29353. /**
  29354. * This flag can be used for type testing.
  29355. *
  29356. * @type {boolean}
  29357. * @readonly
  29358. * @default true
  29359. */
  29360. this.isShadowBaseNode = true;
  29361. }
  29362. /**
  29363. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  29364. *
  29365. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  29366. */
  29367. setupShadowPosition( { context, material } ) {
  29368. // Use assign inside an Fn()
  29369. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  29370. }
  29371. }
  29372. /**
  29373. * TSL object that represents the vertex position in world space during the shadow pass.
  29374. *
  29375. * @tsl
  29376. * @type {Node<vec3>}
  29377. */
  29378. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  29379. /**
  29380. * Saves the state of the given renderer and stores it into the given state object.
  29381. *
  29382. * If not state object is provided, the function creates one.
  29383. *
  29384. * @private
  29385. * @function
  29386. * @param {Renderer} renderer - The renderer.
  29387. * @param {Object} [state={}] - The state.
  29388. * @return {Object} The state.
  29389. */
  29390. function saveRendererState( renderer, state = {} ) {
  29391. state.toneMapping = renderer.toneMapping;
  29392. state.toneMappingExposure = renderer.toneMappingExposure;
  29393. state.outputColorSpace = renderer.outputColorSpace;
  29394. state.renderTarget = renderer.getRenderTarget();
  29395. state.activeCubeFace = renderer.getActiveCubeFace();
  29396. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  29397. state.renderObjectFunction = renderer.getRenderObjectFunction();
  29398. state.pixelRatio = renderer.getPixelRatio();
  29399. state.mrt = renderer.getMRT();
  29400. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  29401. state.clearAlpha = renderer.getClearAlpha();
  29402. state.autoClear = renderer.autoClear;
  29403. state.scissorTest = renderer.getScissorTest();
  29404. return state;
  29405. }
  29406. /**
  29407. * Saves the state of the given renderer and stores it into the given state object.
  29408. * Besides, the function also resets the state of the renderer to its default values.
  29409. *
  29410. * If not state object is provided, the function creates one.
  29411. *
  29412. * @private
  29413. * @function
  29414. * @param {Renderer} renderer - The renderer.
  29415. * @param {Object} [state={}] - The state.
  29416. * @return {Object} The state.
  29417. */
  29418. function resetRendererState( renderer, state ) {
  29419. state = saveRendererState( renderer, state );
  29420. renderer.setMRT( null );
  29421. renderer.setRenderObjectFunction( null );
  29422. renderer.setClearColor( 0x000000, 1 );
  29423. renderer.autoClear = true;
  29424. return state;
  29425. }
  29426. /**
  29427. * Restores the state of the given renderer from the given state object.
  29428. *
  29429. * @private
  29430. * @function
  29431. * @param {Renderer} renderer - The renderer.
  29432. * @param {Object} state - The state to restore.
  29433. */
  29434. function restoreRendererState( renderer, state ) {
  29435. renderer.toneMapping = state.toneMapping;
  29436. renderer.toneMappingExposure = state.toneMappingExposure;
  29437. renderer.outputColorSpace = state.outputColorSpace;
  29438. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  29439. renderer.setRenderObjectFunction( state.renderObjectFunction );
  29440. renderer.setPixelRatio( state.pixelRatio );
  29441. renderer.setMRT( state.mrt );
  29442. renderer.setClearColor( state.clearColor, state.clearAlpha );
  29443. renderer.autoClear = state.autoClear;
  29444. renderer.setScissorTest( state.scissorTest );
  29445. }
  29446. /**
  29447. * Saves the state of the given scene and stores it into the given state object.
  29448. *
  29449. * If not state object is provided, the function creates one.
  29450. *
  29451. * @private
  29452. * @function
  29453. * @param {Scene} scene - The scene.
  29454. * @param {Object} [state={}] - The state.
  29455. * @return {Object} The state.
  29456. */
  29457. function saveSceneState( scene, state = {} ) {
  29458. state.background = scene.background;
  29459. state.backgroundNode = scene.backgroundNode;
  29460. state.overrideMaterial = scene.overrideMaterial;
  29461. return state;
  29462. }
  29463. /**
  29464. * Saves the state of the given scene and stores it into the given state object.
  29465. * Besides, the function also resets the state of the scene to its default values.
  29466. *
  29467. * If not state object is provided, the function creates one.
  29468. *
  29469. * @private
  29470. * @function
  29471. * @param {Scene} scene - The scene.
  29472. * @param {Object} [state={}] - The state.
  29473. * @return {Object} The state.
  29474. */
  29475. function resetSceneState( scene, state ) {
  29476. state = saveSceneState( scene, state );
  29477. scene.background = null;
  29478. scene.backgroundNode = null;
  29479. scene.overrideMaterial = null;
  29480. return state;
  29481. }
  29482. /**
  29483. * Restores the state of the given scene from the given state object.
  29484. *
  29485. * @private
  29486. * @function
  29487. * @param {Scene} scene - The scene.
  29488. * @param {Object} state - The state to restore.
  29489. */
  29490. function restoreSceneState( scene, state ) {
  29491. scene.background = state.background;
  29492. scene.backgroundNode = state.backgroundNode;
  29493. scene.overrideMaterial = state.overrideMaterial;
  29494. }
  29495. /**
  29496. * Saves the state of the given renderer and scene and stores it into the given state object.
  29497. *
  29498. * If not state object is provided, the function creates one.
  29499. *
  29500. * @private
  29501. * @function
  29502. * @param {Renderer} renderer - The renderer.
  29503. * @param {Scene} scene - The scene.
  29504. * @param {Object} [state={}] - The state.
  29505. * @return {Object} The state.
  29506. */
  29507. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  29508. state = saveRendererState( renderer, state );
  29509. state = saveSceneState( scene, state );
  29510. return state;
  29511. }
  29512. /**
  29513. * Saves the state of the given renderer and scene and stores it into the given state object.
  29514. * Besides, the function also resets the state of the renderer and scene to its default values.
  29515. *
  29516. * If not state object is provided, the function creates one.
  29517. *
  29518. * @private
  29519. * @function
  29520. * @param {Renderer} renderer - The renderer.
  29521. * @param {Scene} scene - The scene.
  29522. * @param {Object} [state={}] - The state.
  29523. * @return {Object} The state.
  29524. */
  29525. function resetRendererAndSceneState( renderer, scene, state ) {
  29526. state = resetRendererState( renderer, state );
  29527. state = resetSceneState( scene, state );
  29528. return state;
  29529. }
  29530. /**
  29531. * Restores the state of the given renderer and scene from the given state object.
  29532. *
  29533. * @private
  29534. * @function
  29535. * @param {Renderer} renderer - The renderer.
  29536. * @param {Scene} scene - The scene.
  29537. * @param {Object} state - The state to restore.
  29538. */
  29539. function restoreRendererAndSceneState( renderer, scene, state ) {
  29540. restoreRendererState( renderer, state );
  29541. restoreSceneState( scene, state );
  29542. }
  29543. var RendererUtils = /*#__PURE__*/Object.freeze({
  29544. __proto__: null,
  29545. resetRendererAndSceneState: resetRendererAndSceneState,
  29546. resetRendererState: resetRendererState,
  29547. resetSceneState: resetSceneState,
  29548. restoreRendererAndSceneState: restoreRendererAndSceneState,
  29549. restoreRendererState: restoreRendererState,
  29550. restoreSceneState: restoreSceneState,
  29551. saveRendererAndSceneState: saveRendererAndSceneState,
  29552. saveRendererState: saveRendererState,
  29553. saveSceneState: saveSceneState
  29554. });
  29555. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  29556. /**
  29557. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  29558. * with a binary `[0,1]` result.
  29559. *
  29560. * @method
  29561. * @param {Object} inputs - The input parameter object.
  29562. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29563. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29564. * @return {Node<float>} The filtering result.
  29565. */
  29566. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  29567. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  29568. if ( depthTexture.isArrayTexture ) {
  29569. basic = basic.depth( depthLayer );
  29570. }
  29571. return basic.compare( shadowCoord.z );
  29572. } );
  29573. /**
  29574. * A shadow filtering function performing PCF filtering.
  29575. *
  29576. * @method
  29577. * @param {Object} inputs - The input parameter object.
  29578. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29579. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29580. * @param {LightShadow} inputs.shadow - The light shadow.
  29581. * @return {Node<float>} The filtering result.
  29582. */
  29583. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  29584. const depthCompare = ( uv, compare ) => {
  29585. let depth = texture( depthTexture, uv );
  29586. if ( depthTexture.isArrayTexture ) {
  29587. depth = depth.depth( depthLayer );
  29588. }
  29589. return depth.compare( compare );
  29590. };
  29591. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29592. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29593. const texelSize = vec2( 1 ).div( mapSize );
  29594. const dx0 = texelSize.x.negate().mul( radius );
  29595. const dy0 = texelSize.y.negate().mul( radius );
  29596. const dx1 = texelSize.x.mul( radius );
  29597. const dy1 = texelSize.y.mul( radius );
  29598. const dx2 = dx0.div( 2 );
  29599. const dy2 = dy0.div( 2 );
  29600. const dx3 = dx1.div( 2 );
  29601. const dy3 = dy1.div( 2 );
  29602. return add(
  29603. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  29604. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  29605. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  29606. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  29607. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  29608. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  29609. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  29610. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  29611. depthCompare( shadowCoord.xy, shadowCoord.z ),
  29612. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  29613. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  29614. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  29615. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  29616. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  29617. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  29618. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  29619. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  29620. ).mul( 1 / 17 );
  29621. } );
  29622. /**
  29623. * A shadow filtering function performing PCF soft filtering.
  29624. *
  29625. * @method
  29626. * @param {Object} inputs - The input parameter object.
  29627. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29628. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29629. * @param {LightShadow} inputs.shadow - The light shadow.
  29630. * @return {Node<float>} The filtering result.
  29631. */
  29632. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  29633. const depthCompare = ( uv, compare ) => {
  29634. let depth = texture( depthTexture, uv );
  29635. if ( depthTexture.isArrayTexture ) {
  29636. depth = depth.depth( depthLayer );
  29637. }
  29638. return depth.compare( compare );
  29639. };
  29640. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29641. const texelSize = vec2( 1 ).div( mapSize );
  29642. const dx = texelSize.x;
  29643. const dy = texelSize.y;
  29644. const uv = shadowCoord.xy;
  29645. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  29646. uv.subAssign( f.mul( texelSize ) );
  29647. return add(
  29648. depthCompare( uv, shadowCoord.z ),
  29649. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  29650. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  29651. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  29652. mix(
  29653. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  29654. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  29655. f.x
  29656. ),
  29657. mix(
  29658. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  29659. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  29660. f.x
  29661. ),
  29662. mix(
  29663. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  29664. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  29665. f.y
  29666. ),
  29667. mix(
  29668. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  29669. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  29670. f.y
  29671. ),
  29672. mix(
  29673. mix(
  29674. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  29675. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  29676. f.x
  29677. ),
  29678. mix(
  29679. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  29680. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  29681. f.x
  29682. ),
  29683. f.y
  29684. )
  29685. ).mul( 1 / 9 );
  29686. } );
  29687. /**
  29688. * A shadow filtering function performing VSM filtering.
  29689. *
  29690. * @method
  29691. * @param {Object} inputs - The input parameter object.
  29692. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29693. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29694. * @return {Node<float>} The filtering result.
  29695. */
  29696. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  29697. const occlusion = float( 1 ).toVar();
  29698. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  29699. if ( depthTexture.isArrayTexture ) {
  29700. distribution = distribution.depth( depthLayer );
  29701. }
  29702. distribution = distribution.rg;
  29703. const hardShadow = step( shadowCoord.z, distribution.x );
  29704. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  29705. const distance = shadowCoord.z.sub( distribution.x );
  29706. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  29707. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  29708. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  29709. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  29710. } );
  29711. return occlusion;
  29712. } );
  29713. //
  29714. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  29715. let dist = positionWorld.sub( position ).length();
  29716. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  29717. dist = dist.saturate(); // clamp to [ 0, 1 ]
  29718. return dist;
  29719. } );
  29720. const linearShadowDistance = ( light ) => {
  29721. const camera = light.shadow.camera;
  29722. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  29723. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  29724. const referencePosition = objectPosition( light );
  29725. return linearDistance( referencePosition, nearDistance, farDistance );
  29726. };
  29727. /**
  29728. * Retrieves or creates a shadow material for the given light source.
  29729. *
  29730. * This function checks if a shadow material already exists for the provided light.
  29731. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  29732. * in the `shadowMaterialLib` for future use.
  29733. *
  29734. * @tsl
  29735. * @function
  29736. * @param {Light} light - The light source for which the shadow material is needed.
  29737. * If the light is a point light, a depth node is calculated
  29738. * using the linear shadow distance.
  29739. * @returns {NodeMaterial} The shadow material associated with the given light.
  29740. */
  29741. const getShadowMaterial = ( light ) => {
  29742. let material = shadowMaterialLib.get( light );
  29743. if ( material === undefined ) {
  29744. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  29745. material = new NodeMaterial();
  29746. material.colorNode = vec4( 0, 0, 0, 1 );
  29747. material.depthNode = depthNode;
  29748. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  29749. material.name = 'ShadowMaterial';
  29750. material.fog = false;
  29751. shadowMaterialLib.set( light, material );
  29752. }
  29753. return material;
  29754. };
  29755. //
  29756. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  29757. const _shadowRenderObjectKeys = [];
  29758. /**
  29759. * Creates a function to render shadow objects in a scene.
  29760. *
  29761. * @tsl
  29762. * @function
  29763. * @param {Renderer} renderer - The renderer.
  29764. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  29765. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  29766. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  29767. * @return {Function} A function that renders shadow objects.
  29768. *
  29769. * The returned function has the following parameters:
  29770. * @param {Object3D} object - The 3D object to render.
  29771. * @param {Scene} scene - The scene containing the object.
  29772. * @param {Camera} _camera - The camera used for rendering.
  29773. * @param {BufferGeometry} geometry - The geometry of the object.
  29774. * @param {Material} material - The material of the object.
  29775. * @param {Group} group - The group the object belongs to.
  29776. * @param {...any} params - Additional parameters for rendering.
  29777. */
  29778. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  29779. _shadowRenderObjectKeys[ 0 ] = renderer;
  29780. _shadowRenderObjectKeys[ 1 ] = shadow;
  29781. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  29782. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  29783. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  29784. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  29785. if ( useVelocity ) {
  29786. getDataFromObject( object ).useVelocity = true;
  29787. }
  29788. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  29789. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  29790. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  29791. }
  29792. };
  29793. renderObjectFunction.shadowType = shadowType;
  29794. renderObjectFunction.useVelocity = useVelocity;
  29795. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  29796. }
  29797. _shadowRenderObjectKeys[ 0 ] = null;
  29798. _shadowRenderObjectKeys[ 1 ] = null;
  29799. return renderObjectFunction;
  29800. };
  29801. /**
  29802. * Represents the shader code for the first VSM render pass.
  29803. *
  29804. * @method
  29805. * @param {Object} inputs - The input parameter object.
  29806. * @param {Node<float>} inputs.samples - The number of samples
  29807. * @param {Node<float>} inputs.radius - The radius.
  29808. * @param {Node<float>} inputs.size - The size.
  29809. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  29810. * @return {Node<vec2>} The VSM output.
  29811. */
  29812. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  29813. const mean = float( 0 ).toVar( 'meanVertical' );
  29814. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  29815. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  29816. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  29817. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  29818. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  29819. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  29820. if ( shadowPass.value.isArrayTexture ) {
  29821. depth = depth.depth( depthLayer );
  29822. }
  29823. depth = depth.x;
  29824. mean.addAssign( depth );
  29825. squaredMean.addAssign( depth.mul( depth ) );
  29826. } );
  29827. mean.divAssign( samples );
  29828. squaredMean.divAssign( samples );
  29829. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  29830. return vec2( mean, std_dev );
  29831. } );
  29832. /**
  29833. * Represents the shader code for the second VSM render pass.
  29834. *
  29835. * @method
  29836. * @param {Object} inputs - The input parameter object.
  29837. * @param {Node<float>} inputs.samples - The number of samples
  29838. * @param {Node<float>} inputs.radius - The radius.
  29839. * @param {Node<float>} inputs.size - The size.
  29840. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  29841. * @return {Node<vec2>} The VSM output.
  29842. */
  29843. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  29844. const mean = float( 0 ).toVar( 'meanHorizontal' );
  29845. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  29846. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  29847. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  29848. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  29849. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  29850. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  29851. if ( shadowPass.value.isArrayTexture ) {
  29852. distribution = distribution.depth( depthLayer );
  29853. }
  29854. mean.addAssign( distribution.x );
  29855. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  29856. } );
  29857. mean.divAssign( samples );
  29858. squaredMean.divAssign( samples );
  29859. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  29860. return vec2( mean, std_dev );
  29861. } );
  29862. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  29863. //
  29864. let _rendererState;
  29865. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  29866. /**
  29867. * Represents the default shadow implementation for lighting nodes.
  29868. *
  29869. * @augments ShadowBaseNode
  29870. */
  29871. class ShadowNode extends ShadowBaseNode {
  29872. static get type() {
  29873. return 'ShadowNode';
  29874. }
  29875. /**
  29876. * Constructs a new shadow node.
  29877. *
  29878. * @param {Light} light - The shadow casting light.
  29879. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  29880. */
  29881. constructor( light, shadow = null ) {
  29882. super( light );
  29883. /**
  29884. * The light shadow which defines the properties light's
  29885. * shadow.
  29886. *
  29887. * @type {?LightShadow}
  29888. * @default null
  29889. */
  29890. this.shadow = shadow || light.shadow;
  29891. /**
  29892. * A reference to the shadow map which is a render target.
  29893. *
  29894. * @type {?RenderTarget}
  29895. * @default null
  29896. */
  29897. this.shadowMap = null;
  29898. /**
  29899. * Only relevant for VSM shadows. Render target for the
  29900. * first VSM render pass.
  29901. *
  29902. * @type {?RenderTarget}
  29903. * @default null
  29904. */
  29905. this.vsmShadowMapVertical = null;
  29906. /**
  29907. * Only relevant for VSM shadows. Render target for the
  29908. * second VSM render pass.
  29909. *
  29910. * @type {?RenderTarget}
  29911. * @default null
  29912. */
  29913. this.vsmShadowMapHorizontal = null;
  29914. /**
  29915. * Only relevant for VSM shadows. Node material which
  29916. * is used to render the first VSM pass.
  29917. *
  29918. * @type {?NodeMaterial}
  29919. * @default null
  29920. */
  29921. this.vsmMaterialVertical = null;
  29922. /**
  29923. * Only relevant for VSM shadows. Node material which
  29924. * is used to render the second VSM pass.
  29925. *
  29926. * @type {?NodeMaterial}
  29927. * @default null
  29928. */
  29929. this.vsmMaterialHorizontal = null;
  29930. /**
  29931. * A reference to the output node which defines the
  29932. * final result of this shadow node.
  29933. *
  29934. * @type {?Node}
  29935. * @private
  29936. * @default null
  29937. */
  29938. this._node = null;
  29939. this._cameraFrameId = new WeakMap();
  29940. /**
  29941. * This flag can be used for type testing.
  29942. *
  29943. * @type {boolean}
  29944. * @readonly
  29945. * @default true
  29946. */
  29947. this.isShadowNode = true;
  29948. /**
  29949. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  29950. *
  29951. * @type {number}
  29952. * @readonly
  29953. * @default true
  29954. */
  29955. this.depthLayer = 0;
  29956. }
  29957. /**
  29958. * Setups the shadow filtering.
  29959. *
  29960. * @param {NodeBuilder} builder - A reference to the current node builder.
  29961. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  29962. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  29963. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29964. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  29965. * @param {LightShadow} inputs.shadow - The light shadow.
  29966. * @return {Node<float>} The result node of the shadow filtering.
  29967. */
  29968. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  29969. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  29970. .and( shadowCoord.x.lessThanEqual( 1 ) )
  29971. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  29972. .and( shadowCoord.y.lessThanEqual( 1 ) )
  29973. .and( shadowCoord.z.lessThanEqual( 1 ) );
  29974. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  29975. return frustumTest.select( shadowNode, float( 1 ) );
  29976. }
  29977. /**
  29978. * Setups the shadow coordinates.
  29979. *
  29980. * @param {NodeBuilder} builder - A reference to the current node builder.
  29981. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  29982. * @return {Node<vec3>} The shadow coordinates.
  29983. */
  29984. setupShadowCoord( builder, shadowPosition ) {
  29985. const { shadow } = this;
  29986. const { renderer } = builder;
  29987. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  29988. let shadowCoord = shadowPosition;
  29989. let coordZ;
  29990. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  29991. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  29992. coordZ = shadowCoord.z;
  29993. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  29994. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  29995. }
  29996. } else {
  29997. const w = shadowCoord.w;
  29998. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  29999. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  30000. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  30001. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  30002. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  30003. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  30004. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  30005. }
  30006. shadowCoord = vec3(
  30007. shadowCoord.x,
  30008. shadowCoord.y.oneMinus(), // follow webgpu standards
  30009. coordZ.add( bias )
  30010. );
  30011. return shadowCoord;
  30012. }
  30013. /**
  30014. * Returns the shadow filtering function for the given shadow type.
  30015. *
  30016. * @param {number} type - The shadow type.
  30017. * @return {Function} The filtering function.
  30018. */
  30019. getShadowFilterFn( type ) {
  30020. return _shadowFilterLib[ type ];
  30021. }
  30022. setupRenderTarget( shadow, builder ) {
  30023. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  30024. depthTexture.name = 'ShadowDepthTexture';
  30025. depthTexture.compareFunction = LessCompare;
  30026. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  30027. shadowMap.texture.name = 'ShadowMap';
  30028. shadowMap.texture.type = shadow.mapType;
  30029. shadowMap.depthTexture = depthTexture;
  30030. return { shadowMap, depthTexture };
  30031. }
  30032. /**
  30033. * Setups the shadow output node.
  30034. *
  30035. * @param {NodeBuilder} builder - A reference to the current node builder.
  30036. * @return {Node<vec3>} The shadow output node.
  30037. */
  30038. setupShadow( builder ) {
  30039. const { renderer, camera } = builder;
  30040. const { light, shadow } = this;
  30041. const shadowMapType = renderer.shadowMap.type;
  30042. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  30043. shadow.camera.coordinateSystem = camera.coordinateSystem;
  30044. shadow.camera.updateProjectionMatrix();
  30045. // VSM
  30046. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  30047. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  30048. if ( shadowMap.depth > 1 ) {
  30049. if ( ! shadowMap._vsmShadowMapVertical ) {
  30050. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  30051. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  30052. }
  30053. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  30054. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  30055. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  30056. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  30057. }
  30058. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  30059. } else {
  30060. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  30061. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  30062. }
  30063. let shadowPassVertical = texture( depthTexture );
  30064. if ( depthTexture.isArrayTexture ) {
  30065. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  30066. }
  30067. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  30068. if ( depthTexture.isArrayTexture ) {
  30069. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  30070. }
  30071. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  30072. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30073. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30074. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  30075. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  30076. material.name = 'VSMVertical';
  30077. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  30078. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  30079. material.name = 'VSMHorizontal';
  30080. }
  30081. //
  30082. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  30083. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  30084. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  30085. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  30086. //
  30087. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  30088. if ( filterFn === null ) {
  30089. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  30090. }
  30091. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  30092. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  30093. let shadowColor = texture( shadowMap.texture, shadowCoord );
  30094. if ( depthTexture.isArrayTexture ) {
  30095. shadowColor = shadowColor.depth( this.depthLayer );
  30096. }
  30097. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  30098. this.shadowMap = shadowMap;
  30099. this.shadow.map = shadowMap;
  30100. // Shadow Output + Inspector
  30101. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  30102. return shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  30103. return texture( this.shadowMap.texture );
  30104. } ).toInspector( `${ inspectName } / Depth`, () => {
  30105. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).x.oneMinus();
  30106. } );
  30107. }
  30108. /**
  30109. * The implementation performs the setup of the output node. An output is only
  30110. * produces if shadow mapping is globally enabled in the renderer.
  30111. *
  30112. * @param {NodeBuilder} builder - A reference to the current node builder.
  30113. * @return {ShaderCallNodeInternal} The output node.
  30114. */
  30115. setup( builder ) {
  30116. if ( builder.renderer.shadowMap.enabled === false ) return;
  30117. return Fn( () => {
  30118. let node = this._node;
  30119. this.setupShadowPosition( builder );
  30120. if ( node === null ) {
  30121. this._node = node = this.setupShadow( builder );
  30122. }
  30123. if ( builder.material.shadowNode ) { // @deprecated, r171
  30124. warn( 'NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  30125. }
  30126. if ( builder.material.receivedShadowNode ) {
  30127. node = builder.material.receivedShadowNode( node );
  30128. }
  30129. return node;
  30130. } )();
  30131. }
  30132. /**
  30133. * Renders the shadow. The logic of this function could be included
  30134. * into {@link ShadowNode#updateShadow} however more specialized shadow
  30135. * nodes might require a custom shadow map rendering. By having a
  30136. * dedicated method, it's easier to overwrite the default behavior.
  30137. *
  30138. * @param {NodeFrame} frame - A reference to the current node frame.
  30139. */
  30140. renderShadow( frame ) {
  30141. const { shadow, shadowMap, light } = this;
  30142. const { renderer, scene } = frame;
  30143. shadow.updateMatrices( light );
  30144. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  30145. const currentSceneName = scene.name;
  30146. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  30147. renderer.render( scene, shadow.camera );
  30148. scene.name = currentSceneName;
  30149. }
  30150. /**
  30151. * Updates the shadow.
  30152. *
  30153. * @param {NodeFrame} frame - A reference to the current node frame.
  30154. */
  30155. updateShadow( frame ) {
  30156. const { shadowMap, light, shadow } = this;
  30157. const { renderer, scene, camera } = frame;
  30158. const shadowType = renderer.shadowMap.type;
  30159. const depthVersion = shadowMap.depthTexture.version;
  30160. this._depthVersionCached = depthVersion;
  30161. const _shadowCameraLayer = shadow.camera.layers.mask;
  30162. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  30163. shadow.camera.layers.mask = camera.layers.mask;
  30164. }
  30165. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  30166. const currentMRT = renderer.getMRT();
  30167. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  30168. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  30169. scene.overrideMaterial = getShadowMaterial( light );
  30170. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  30171. renderer.setClearColor( 0x000000, 0 );
  30172. renderer.setRenderTarget( shadowMap );
  30173. this.renderShadow( frame );
  30174. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  30175. // vsm blur pass
  30176. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  30177. this.vsmPass( renderer );
  30178. }
  30179. shadow.camera.layers.mask = _shadowCameraLayer;
  30180. restoreRendererAndSceneState( renderer, scene, _rendererState );
  30181. }
  30182. /**
  30183. * For VSM additional render passes are required.
  30184. *
  30185. * @param {Renderer} renderer - A reference to the current renderer.
  30186. */
  30187. vsmPass( renderer ) {
  30188. const { shadow } = this;
  30189. const depth = this.shadowMap.depth;
  30190. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  30191. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  30192. renderer.setRenderTarget( this.vsmShadowMapVertical );
  30193. _quadMesh.material = this.vsmMaterialVertical;
  30194. _quadMesh.render( renderer );
  30195. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  30196. _quadMesh.material = this.vsmMaterialHorizontal;
  30197. _quadMesh.render( renderer );
  30198. }
  30199. /**
  30200. * Frees the internal resources of this shadow node.
  30201. */
  30202. dispose() {
  30203. this.shadowMap.dispose();
  30204. this.shadowMap = null;
  30205. if ( this.vsmShadowMapVertical !== null ) {
  30206. this.vsmShadowMapVertical.dispose();
  30207. this.vsmShadowMapVertical = null;
  30208. this.vsmMaterialVertical.dispose();
  30209. this.vsmMaterialVertical = null;
  30210. }
  30211. if ( this.vsmShadowMapHorizontal !== null ) {
  30212. this.vsmShadowMapHorizontal.dispose();
  30213. this.vsmShadowMapHorizontal = null;
  30214. this.vsmMaterialHorizontal.dispose();
  30215. this.vsmMaterialHorizontal = null;
  30216. }
  30217. super.dispose();
  30218. }
  30219. /**
  30220. * The implementation performs the update of the shadow map if necessary.
  30221. *
  30222. * @param {NodeFrame} frame - A reference to the current node frame.
  30223. */
  30224. updateBefore( frame ) {
  30225. const { shadow } = this;
  30226. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  30227. if ( needsUpdate ) {
  30228. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  30229. needsUpdate = false;
  30230. }
  30231. this._cameraFrameId[ frame.camera ] = frame.frameId;
  30232. }
  30233. if ( needsUpdate ) {
  30234. this.updateShadow( frame );
  30235. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  30236. shadow.needsUpdate = false;
  30237. }
  30238. }
  30239. }
  30240. }
  30241. /**
  30242. * TSL function for creating an instance of `ShadowNode`.
  30243. *
  30244. * @tsl
  30245. * @function
  30246. * @param {Light} light - The shadow casting light.
  30247. * @param {?LightShadow} [shadow] - The light shadow.
  30248. * @return {ShadowNode} The created shadow node.
  30249. */
  30250. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  30251. const _clearColor$1 = /*@__PURE__*/ new Color();
  30252. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  30253. // vector suitable for 2D texture mapping. This code uses the following layout for the
  30254. // 2D texture:
  30255. //
  30256. // xzXZ
  30257. // y Y
  30258. //
  30259. // Y - Positive y direction
  30260. // y - Negative y direction
  30261. // X - Positive x direction
  30262. // x - Negative x direction
  30263. // Z - Positive z direction
  30264. // z - Negative z direction
  30265. //
  30266. // Source and test bed:
  30267. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  30268. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  30269. const v = pos.toVar();
  30270. // Number of texels to avoid at the edge of each square
  30271. const absV = abs( v );
  30272. // Intersect unit cube
  30273. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  30274. absV.mulAssign( scaleToCube );
  30275. // Apply scale to avoid seams
  30276. // two texels less per square (one texel will do for NEAREST)
  30277. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  30278. // Unwrap
  30279. // space: -1 ... 1 range for each square
  30280. //
  30281. // #X## dim := ( 4 , 2 )
  30282. // # # center := ( 1 , 1 )
  30283. const planar = vec2( v.xy ).toVar();
  30284. const almostATexel = texelSizeY.mul( 1.5 );
  30285. const almostOne = almostATexel.oneMinus();
  30286. If( absV.z.greaterThanEqual( almostOne ), () => {
  30287. If( v.z.greaterThan( 0.0 ), () => {
  30288. planar.x.assign( sub( 4.0, v.x ) );
  30289. } );
  30290. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  30291. const signX = sign( v.x );
  30292. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  30293. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  30294. const signY = sign( v.y );
  30295. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  30296. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  30297. } );
  30298. // Transform to UV space
  30299. // scale := 0.5 / dim
  30300. // translate := ( center + 0.5 ) / dim
  30301. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  30302. } ).setLayout( {
  30303. name: 'cubeToUV',
  30304. type: 'vec2',
  30305. inputs: [
  30306. { name: 'pos', type: 'vec3' },
  30307. { name: 'texelSizeY', type: 'float' }
  30308. ]
  30309. } );
  30310. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  30311. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  30312. } );
  30313. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  30314. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30315. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  30316. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  30317. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  30318. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  30319. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  30320. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  30321. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  30322. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  30323. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  30324. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  30325. .mul( 1.0 / 9.0 );
  30326. } );
  30327. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  30328. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  30329. // the vector from the light to the world-space position of the fragment.
  30330. const lightToPosition = shadowCoord.xyz.toVar();
  30331. const lightToPositionLength = lightToPosition.length();
  30332. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  30333. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  30334. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  30335. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  30336. const result = float( 1.0 ).toVar();
  30337. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  30338. // dp = normalized distance from light to fragment position
  30339. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  30340. dp.addAssign( bias );
  30341. // bd3D = base direction 3D
  30342. const bd3D = lightToPosition.normalize();
  30343. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  30344. // percentage-closer filtering
  30345. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  30346. } );
  30347. return result;
  30348. } );
  30349. const _viewport = /*@__PURE__*/ new Vector4();
  30350. const _viewportSize = /*@__PURE__*/ new Vector2();
  30351. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  30352. /**
  30353. * Represents the shadow implementation for point light nodes.
  30354. *
  30355. * @augments ShadowNode
  30356. */
  30357. class PointShadowNode extends ShadowNode {
  30358. static get type() {
  30359. return 'PointShadowNode';
  30360. }
  30361. /**
  30362. * Constructs a new point shadow node.
  30363. *
  30364. * @param {PointLight} light - The shadow casting point light.
  30365. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  30366. */
  30367. constructor( light, shadow = null ) {
  30368. super( light, shadow );
  30369. }
  30370. /**
  30371. * Overwrites the default implementation to return point light shadow specific
  30372. * filtering functions.
  30373. *
  30374. * @param {number} type - The shadow type.
  30375. * @return {Function} The filtering function.
  30376. */
  30377. getShadowFilterFn( type ) {
  30378. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  30379. }
  30380. /**
  30381. * Overwrites the default implementation so the unaltered shadow position is used.
  30382. *
  30383. * @param {NodeBuilder} builder - A reference to the current node builder.
  30384. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  30385. * @return {Node<vec3>} The shadow coordinates.
  30386. */
  30387. setupShadowCoord( builder, shadowPosition ) {
  30388. return shadowPosition;
  30389. }
  30390. /**
  30391. * Overwrites the default implementation to only use point light specific
  30392. * shadow filter functions.
  30393. *
  30394. * @param {NodeBuilder} builder - A reference to the current node builder.
  30395. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  30396. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  30397. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  30398. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30399. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  30400. * @param {LightShadow} inputs.shadow - The light shadow.
  30401. * @return {Node<float>} The result node of the shadow filtering.
  30402. */
  30403. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  30404. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  30405. }
  30406. /**
  30407. * Overwrites the default implementation with point light specific
  30408. * rendering code.
  30409. *
  30410. * @param {NodeFrame} frame - A reference to the current node frame.
  30411. */
  30412. renderShadow( frame ) {
  30413. const { shadow, shadowMap, light } = this;
  30414. const { renderer, scene } = frame;
  30415. const shadowFrameExtents = shadow.getFrameExtents();
  30416. _shadowMapSize.copy( shadow.mapSize );
  30417. _shadowMapSize.multiply( shadowFrameExtents );
  30418. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  30419. _viewportSize.copy( shadow.mapSize );
  30420. //
  30421. const previousAutoClear = renderer.autoClear;
  30422. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  30423. const previousClearAlpha = renderer.getClearAlpha();
  30424. renderer.autoClear = false;
  30425. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  30426. renderer.clear();
  30427. const viewportCount = shadow.getViewportCount();
  30428. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  30429. const viewport = shadow.getViewport( vp );
  30430. const x = _viewportSize.x * viewport.x;
  30431. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  30432. _viewport.set(
  30433. x,
  30434. y,
  30435. _viewportSize.x * viewport.z,
  30436. _viewportSize.y * viewport.w
  30437. );
  30438. shadowMap.viewport.copy( _viewport );
  30439. shadow.updateMatrices( light, vp );
  30440. const currentSceneName = scene.name;
  30441. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ vp + 1 }`;
  30442. renderer.render( scene, shadow.camera );
  30443. scene.name = currentSceneName;
  30444. }
  30445. //
  30446. renderer.autoClear = previousAutoClear;
  30447. renderer.setClearColor( previousClearColor, previousClearAlpha );
  30448. }
  30449. }
  30450. /**
  30451. * TSL function for creating an instance of `PointShadowNode`.
  30452. *
  30453. * @tsl
  30454. * @function
  30455. * @param {PointLight} light - The shadow casting point light.
  30456. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  30457. * @return {PointShadowNode} The created point shadow node.
  30458. */
  30459. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  30460. /**
  30461. * Base class for analytic light nodes.
  30462. *
  30463. * @augments LightingNode
  30464. */
  30465. class AnalyticLightNode extends LightingNode {
  30466. static get type() {
  30467. return 'AnalyticLightNode';
  30468. }
  30469. /**
  30470. * Constructs a new analytic light node.
  30471. *
  30472. * @param {?Light} [light=null] - The light source.
  30473. */
  30474. constructor( light = null ) {
  30475. super();
  30476. /**
  30477. * The light source.
  30478. *
  30479. * @type {?Light}
  30480. * @default null
  30481. */
  30482. this.light = light;
  30483. /**
  30484. * The light's color value.
  30485. *
  30486. * @type {Color}
  30487. */
  30488. this.color = new Color();
  30489. /**
  30490. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  30491. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  30492. *
  30493. * @type {Node}
  30494. */
  30495. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  30496. /**
  30497. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  30498. * The final color node is represented by a different node when using shadows.
  30499. *
  30500. * @type {?Node}
  30501. * @default null
  30502. */
  30503. this.baseColorNode = null;
  30504. /**
  30505. * Represents the light's shadow.
  30506. *
  30507. * @type {?ShadowNode}
  30508. * @default null
  30509. */
  30510. this.shadowNode = null;
  30511. /**
  30512. * Represents the light's shadow color.
  30513. *
  30514. * @type {?Node}
  30515. * @default null
  30516. */
  30517. this.shadowColorNode = null;
  30518. /**
  30519. * This flag can be used for type testing.
  30520. *
  30521. * @type {boolean}
  30522. * @readonly
  30523. * @default true
  30524. */
  30525. this.isAnalyticLightNode = true;
  30526. /**
  30527. * Overwritten since analytic light nodes are updated
  30528. * once per frame.
  30529. *
  30530. * @type {string}
  30531. * @default 'frame'
  30532. */
  30533. this.updateType = NodeUpdateType.FRAME;
  30534. }
  30535. getHash() {
  30536. return this.light.uuid;
  30537. }
  30538. /**
  30539. * Returns a node representing a direction vector which points from the current
  30540. * position in view space to the light's position in view space.
  30541. *
  30542. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30543. * @return {Node<vec3>} The light vector node.
  30544. */
  30545. getLightVector( builder ) {
  30546. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  30547. }
  30548. /**
  30549. * Sets up the direct lighting for the analytic light node.
  30550. *
  30551. * @abstract
  30552. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30553. * @return {Object|undefined} The direct light data (color and direction).
  30554. */
  30555. setupDirect( /*builder*/ ) { }
  30556. /**
  30557. * Sets up the direct rect area lighting for the analytic light node.
  30558. *
  30559. * @abstract
  30560. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30561. * @return {Object|undefined} The direct rect area light data.
  30562. */
  30563. setupDirectRectArea( /*builder*/ ) { }
  30564. /**
  30565. * Setups the shadow node for this light. The method exists so concrete light classes
  30566. * can setup different types of shadow nodes.
  30567. *
  30568. * @return {ShadowNode} The created shadow node.
  30569. */
  30570. setupShadowNode() {
  30571. return shadow( this.light );
  30572. }
  30573. /**
  30574. * Setups the shadow for this light. This method is only executed if the light
  30575. * cast shadows and the current build object receives shadows. It incorporates
  30576. * shadows into the lighting computation.
  30577. *
  30578. * @param {NodeBuilder} builder - The current node builder.
  30579. */
  30580. setupShadow( builder ) {
  30581. const { renderer } = builder;
  30582. if ( renderer.shadowMap.enabled === false ) return;
  30583. let shadowColorNode = this.shadowColorNode;
  30584. if ( shadowColorNode === null ) {
  30585. const customShadowNode = this.light.shadow.shadowNode;
  30586. let shadowNode;
  30587. if ( customShadowNode !== undefined ) {
  30588. shadowNode = nodeObject( customShadowNode );
  30589. } else {
  30590. shadowNode = this.setupShadowNode();
  30591. }
  30592. this.shadowNode = shadowNode;
  30593. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  30594. this.baseColorNode = this.colorNode;
  30595. }
  30596. //
  30597. this.colorNode = shadowColorNode;
  30598. }
  30599. /**
  30600. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  30601. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  30602. * invocate the respective interface methods.
  30603. *
  30604. * @param {NodeBuilder} builder - The current node builder.
  30605. */
  30606. setup( builder ) {
  30607. this.colorNode = this.baseColorNode || this.colorNode;
  30608. if ( this.light.castShadow ) {
  30609. if ( builder.object.receiveShadow ) {
  30610. this.setupShadow( builder );
  30611. }
  30612. } else if ( this.shadowNode !== null ) {
  30613. this.shadowNode.dispose();
  30614. this.shadowNode = null;
  30615. this.shadowColorNode = null;
  30616. }
  30617. const directLightData = this.setupDirect( builder );
  30618. const directRectAreaLightData = this.setupDirectRectArea( builder );
  30619. if ( directLightData ) {
  30620. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  30621. }
  30622. if ( directRectAreaLightData ) {
  30623. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  30624. }
  30625. }
  30626. /**
  30627. * The update method is used to update light uniforms per frame.
  30628. * Potentially overwritten in concrete light nodes to update light
  30629. * specific uniforms.
  30630. *
  30631. * @param {NodeFrame} frame - A reference to the current node frame.
  30632. */
  30633. update( /*frame*/ ) {
  30634. const { light } = this;
  30635. this.color.copy( light.color ).multiplyScalar( light.intensity );
  30636. }
  30637. }
  30638. /**
  30639. * Represents a `discard` shader operation in TSL.
  30640. *
  30641. * @method
  30642. * @param {Object} inputs - The input parameter object.
  30643. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  30644. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  30645. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  30646. * @return {Node<float>} The distance falloff.
  30647. */
  30648. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  30649. // based upon Frostbite 3 Moving to Physically-based Rendering
  30650. // page 32, equation 26: E[window1]
  30651. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  30652. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  30653. return cutoffDistance.greaterThan( 0 ).select(
  30654. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  30655. distanceFalloff
  30656. );
  30657. } ); // validated
  30658. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  30659. const lightDirection = lightVector.normalize();
  30660. const lightDistance = lightVector.length();
  30661. const attenuation = getDistanceAttenuation( {
  30662. lightDistance,
  30663. cutoffDistance,
  30664. decayExponent
  30665. } );
  30666. const lightColor = color.mul( attenuation );
  30667. return { lightDirection, lightColor };
  30668. };
  30669. /**
  30670. * Module for representing point lights as nodes.
  30671. *
  30672. * @augments AnalyticLightNode
  30673. */
  30674. class PointLightNode extends AnalyticLightNode {
  30675. static get type() {
  30676. return 'PointLightNode';
  30677. }
  30678. /**
  30679. * Constructs a new point light node.
  30680. *
  30681. * @param {?PointLight} [light=null] - The point light source.
  30682. */
  30683. constructor( light = null ) {
  30684. super( light );
  30685. /**
  30686. * Uniform node representing the cutoff distance.
  30687. *
  30688. * @type {UniformNode<float>}
  30689. */
  30690. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  30691. /**
  30692. * Uniform node representing the decay exponent.
  30693. *
  30694. * @type {UniformNode<float>}
  30695. */
  30696. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  30697. }
  30698. /**
  30699. * Overwritten to updated point light specific uniforms.
  30700. *
  30701. * @param {NodeFrame} frame - A reference to the current node frame.
  30702. */
  30703. update( frame ) {
  30704. const { light } = this;
  30705. super.update( frame );
  30706. this.cutoffDistanceNode.value = light.distance;
  30707. this.decayExponentNode.value = light.decay;
  30708. }
  30709. /**
  30710. * Overwritten to setup point light specific shadow.
  30711. *
  30712. * @return {PointShadowNode}
  30713. */
  30714. setupShadowNode() {
  30715. return pointShadow( this.light );
  30716. }
  30717. setupDirect( builder ) {
  30718. return directPointLight( {
  30719. color: this.colorNode,
  30720. lightVector: this.getLightVector( builder ),
  30721. cutoffDistance: this.cutoffDistanceNode,
  30722. decayExponent: this.decayExponentNode
  30723. } );
  30724. }
  30725. }
  30726. /**
  30727. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  30728. *
  30729. * @tsl
  30730. * @function
  30731. * @param {Node<vec2>} coord - The uv coordinates.
  30732. * @return {Node<float>} The result data.
  30733. */
  30734. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  30735. const uv = coord.mul( 2.0 );
  30736. const cx = uv.x.floor();
  30737. const cy = uv.y.floor();
  30738. const result = cx.add( cy ).mod( 2.0 );
  30739. return result.sign();
  30740. } );
  30741. /**
  30742. * Generates a circle based on the uv coordinates.
  30743. *
  30744. * @tsl
  30745. * @function
  30746. * @param {Node<vec2>} coord - The uv to generate the circle.
  30747. * @return {Node<float>} The circle shape.
  30748. */
  30749. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  30750. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  30751. let alpha;
  30752. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  30753. const dlen = float( len2.fwidth() ).toVar();
  30754. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  30755. } else {
  30756. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  30757. }
  30758. return alpha;
  30759. } );
  30760. // Three.js Transpiler
  30761. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  30762. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  30763. const f = float( f_immutable ).toVar();
  30764. const t = float( t_immutable ).toVar();
  30765. const b = bool( b_immutable ).toVar();
  30766. return select( b, t, f );
  30767. } ).setLayout( {
  30768. name: 'mx_select',
  30769. type: 'float',
  30770. inputs: [
  30771. { name: 'b', type: 'bool' },
  30772. { name: 't', type: 'float' },
  30773. { name: 'f', type: 'float' }
  30774. ]
  30775. } );
  30776. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  30777. const b = bool( b_immutable ).toVar();
  30778. const val = float( val_immutable ).toVar();
  30779. return select( b, val.negate(), val );
  30780. } ).setLayout( {
  30781. name: 'mx_negate_if',
  30782. type: 'float',
  30783. inputs: [
  30784. { name: 'val', type: 'float' },
  30785. { name: 'b', type: 'bool' }
  30786. ]
  30787. } );
  30788. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  30789. const x = float( x_immutable ).toVar();
  30790. return int( floor( x ) );
  30791. } ).setLayout( {
  30792. name: 'mx_floor',
  30793. type: 'int',
  30794. inputs: [
  30795. { name: 'x', type: 'float' }
  30796. ]
  30797. } );
  30798. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  30799. const x = float( x_immutable ).toVar();
  30800. i.assign( mx_floor( x ) );
  30801. return x.sub( float( i ) );
  30802. } );
  30803. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  30804. const t = float( t_immutable ).toVar();
  30805. const s = float( s_immutable ).toVar();
  30806. const v3 = float( v3_immutable ).toVar();
  30807. const v2 = float( v2_immutable ).toVar();
  30808. const v1 = float( v1_immutable ).toVar();
  30809. const v0 = float( v0_immutable ).toVar();
  30810. const s1 = float( sub( 1.0, s ) ).toVar();
  30811. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  30812. } ).setLayout( {
  30813. name: 'mx_bilerp_0',
  30814. type: 'float',
  30815. inputs: [
  30816. { name: 'v0', type: 'float' },
  30817. { name: 'v1', type: 'float' },
  30818. { name: 'v2', type: 'float' },
  30819. { name: 'v3', type: 'float' },
  30820. { name: 's', type: 'float' },
  30821. { name: 't', type: 'float' }
  30822. ]
  30823. } );
  30824. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  30825. const t = float( t_immutable ).toVar();
  30826. const s = float( s_immutable ).toVar();
  30827. const v3 = vec3( v3_immutable ).toVar();
  30828. const v2 = vec3( v2_immutable ).toVar();
  30829. const v1 = vec3( v1_immutable ).toVar();
  30830. const v0 = vec3( v0_immutable ).toVar();
  30831. const s1 = float( sub( 1.0, s ) ).toVar();
  30832. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  30833. } ).setLayout( {
  30834. name: 'mx_bilerp_1',
  30835. type: 'vec3',
  30836. inputs: [
  30837. { name: 'v0', type: 'vec3' },
  30838. { name: 'v1', type: 'vec3' },
  30839. { name: 'v2', type: 'vec3' },
  30840. { name: 'v3', type: 'vec3' },
  30841. { name: 's', type: 'float' },
  30842. { name: 't', type: 'float' }
  30843. ]
  30844. } );
  30845. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  30846. 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 ] ) => {
  30847. const r = float( r_immutable ).toVar();
  30848. const t = float( t_immutable ).toVar();
  30849. const s = float( s_immutable ).toVar();
  30850. const v7 = float( v7_immutable ).toVar();
  30851. const v6 = float( v6_immutable ).toVar();
  30852. const v5 = float( v5_immutable ).toVar();
  30853. const v4 = float( v4_immutable ).toVar();
  30854. const v3 = float( v3_immutable ).toVar();
  30855. const v2 = float( v2_immutable ).toVar();
  30856. const v1 = float( v1_immutable ).toVar();
  30857. const v0 = float( v0_immutable ).toVar();
  30858. const s1 = float( sub( 1.0, s ) ).toVar();
  30859. const t1 = float( sub( 1.0, t ) ).toVar();
  30860. const r1 = float( sub( 1.0, r ) ).toVar();
  30861. 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 ) ) ) ) ) );
  30862. } ).setLayout( {
  30863. name: 'mx_trilerp_0',
  30864. type: 'float',
  30865. inputs: [
  30866. { name: 'v0', type: 'float' },
  30867. { name: 'v1', type: 'float' },
  30868. { name: 'v2', type: 'float' },
  30869. { name: 'v3', type: 'float' },
  30870. { name: 'v4', type: 'float' },
  30871. { name: 'v5', type: 'float' },
  30872. { name: 'v6', type: 'float' },
  30873. { name: 'v7', type: 'float' },
  30874. { name: 's', type: 'float' },
  30875. { name: 't', type: 'float' },
  30876. { name: 'r', type: 'float' }
  30877. ]
  30878. } );
  30879. 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 ] ) => {
  30880. const r = float( r_immutable ).toVar();
  30881. const t = float( t_immutable ).toVar();
  30882. const s = float( s_immutable ).toVar();
  30883. const v7 = vec3( v7_immutable ).toVar();
  30884. const v6 = vec3( v6_immutable ).toVar();
  30885. const v5 = vec3( v5_immutable ).toVar();
  30886. const v4 = vec3( v4_immutable ).toVar();
  30887. const v3 = vec3( v3_immutable ).toVar();
  30888. const v2 = vec3( v2_immutable ).toVar();
  30889. const v1 = vec3( v1_immutable ).toVar();
  30890. const v0 = vec3( v0_immutable ).toVar();
  30891. const s1 = float( sub( 1.0, s ) ).toVar();
  30892. const t1 = float( sub( 1.0, t ) ).toVar();
  30893. const r1 = float( sub( 1.0, r ) ).toVar();
  30894. 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 ) ) ) ) ) );
  30895. } ).setLayout( {
  30896. name: 'mx_trilerp_1',
  30897. type: 'vec3',
  30898. inputs: [
  30899. { name: 'v0', type: 'vec3' },
  30900. { name: 'v1', type: 'vec3' },
  30901. { name: 'v2', type: 'vec3' },
  30902. { name: 'v3', type: 'vec3' },
  30903. { name: 'v4', type: 'vec3' },
  30904. { name: 'v5', type: 'vec3' },
  30905. { name: 'v6', type: 'vec3' },
  30906. { name: 'v7', type: 'vec3' },
  30907. { name: 's', type: 'float' },
  30908. { name: 't', type: 'float' },
  30909. { name: 'r', type: 'float' }
  30910. ]
  30911. } );
  30912. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  30913. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30914. const y = float( y_immutable ).toVar();
  30915. const x = float( x_immutable ).toVar();
  30916. const hash = uint( hash_immutable ).toVar();
  30917. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  30918. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  30919. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  30920. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30921. } ).setLayout( {
  30922. name: 'mx_gradient_float_0',
  30923. type: 'float',
  30924. inputs: [
  30925. { name: 'hash', type: 'uint' },
  30926. { name: 'x', type: 'float' },
  30927. { name: 'y', type: 'float' }
  30928. ]
  30929. } );
  30930. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30931. const z = float( z_immutable ).toVar();
  30932. const y = float( y_immutable ).toVar();
  30933. const x = float( x_immutable ).toVar();
  30934. const hash = uint( hash_immutable ).toVar();
  30935. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  30936. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  30937. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  30938. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30939. } ).setLayout( {
  30940. name: 'mx_gradient_float_1',
  30941. type: 'float',
  30942. inputs: [
  30943. { name: 'hash', type: 'uint' },
  30944. { name: 'x', type: 'float' },
  30945. { name: 'y', type: 'float' },
  30946. { name: 'z', type: 'float' }
  30947. ]
  30948. } );
  30949. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  30950. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30951. const y = float( y_immutable ).toVar();
  30952. const x = float( x_immutable ).toVar();
  30953. const hash = uvec3( hash_immutable ).toVar();
  30954. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  30955. } ).setLayout( {
  30956. name: 'mx_gradient_vec3_0',
  30957. type: 'vec3',
  30958. inputs: [
  30959. { name: 'hash', type: 'uvec3' },
  30960. { name: 'x', type: 'float' },
  30961. { name: 'y', type: 'float' }
  30962. ]
  30963. } );
  30964. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30965. const z = float( z_immutable ).toVar();
  30966. const y = float( y_immutable ).toVar();
  30967. const x = float( x_immutable ).toVar();
  30968. const hash = uvec3( hash_immutable ).toVar();
  30969. 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 ) );
  30970. } ).setLayout( {
  30971. name: 'mx_gradient_vec3_1',
  30972. type: 'vec3',
  30973. inputs: [
  30974. { name: 'hash', type: 'uvec3' },
  30975. { name: 'x', type: 'float' },
  30976. { name: 'y', type: 'float' },
  30977. { name: 'z', type: 'float' }
  30978. ]
  30979. } );
  30980. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  30981. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30982. const v = float( v_immutable ).toVar();
  30983. return mul( 0.6616, v );
  30984. } ).setLayout( {
  30985. name: 'mx_gradient_scale2d_0',
  30986. type: 'float',
  30987. inputs: [
  30988. { name: 'v', type: 'float' }
  30989. ]
  30990. } );
  30991. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30992. const v = float( v_immutable ).toVar();
  30993. return mul( 0.9820, v );
  30994. } ).setLayout( {
  30995. name: 'mx_gradient_scale3d_0',
  30996. type: 'float',
  30997. inputs: [
  30998. { name: 'v', type: 'float' }
  30999. ]
  31000. } );
  31001. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31002. const v = vec3( v_immutable ).toVar();
  31003. return mul( 0.6616, v );
  31004. } ).setLayout( {
  31005. name: 'mx_gradient_scale2d_1',
  31006. type: 'vec3',
  31007. inputs: [
  31008. { name: 'v', type: 'vec3' }
  31009. ]
  31010. } );
  31011. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  31012. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31013. const v = vec3( v_immutable ).toVar();
  31014. return mul( 0.9820, v );
  31015. } ).setLayout( {
  31016. name: 'mx_gradient_scale3d_1',
  31017. type: 'vec3',
  31018. inputs: [
  31019. { name: 'v', type: 'vec3' }
  31020. ]
  31021. } );
  31022. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  31023. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  31024. const k = int( k_immutable ).toVar();
  31025. const x = uint( x_immutable ).toVar();
  31026. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  31027. } ).setLayout( {
  31028. name: 'mx_rotl32',
  31029. type: 'uint',
  31030. inputs: [
  31031. { name: 'x', type: 'uint' },
  31032. { name: 'k', type: 'int' }
  31033. ]
  31034. } );
  31035. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  31036. a.subAssign( c );
  31037. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  31038. c.addAssign( b );
  31039. b.subAssign( a );
  31040. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  31041. a.addAssign( c );
  31042. c.subAssign( b );
  31043. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  31044. b.addAssign( a );
  31045. a.subAssign( c );
  31046. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  31047. c.addAssign( b );
  31048. b.subAssign( a );
  31049. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  31050. a.addAssign( c );
  31051. c.subAssign( b );
  31052. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  31053. b.addAssign( a );
  31054. } );
  31055. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  31056. const c = uint( c_immutable ).toVar();
  31057. const b = uint( b_immutable ).toVar();
  31058. const a = uint( a_immutable ).toVar();
  31059. c.bitXorAssign( b );
  31060. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  31061. a.bitXorAssign( c );
  31062. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  31063. b.bitXorAssign( a );
  31064. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  31065. c.bitXorAssign( b );
  31066. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  31067. a.bitXorAssign( c );
  31068. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  31069. b.bitXorAssign( a );
  31070. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  31071. c.bitXorAssign( b );
  31072. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  31073. return c;
  31074. } ).setLayout( {
  31075. name: 'mx_bjfinal',
  31076. type: 'uint',
  31077. inputs: [
  31078. { name: 'a', type: 'uint' },
  31079. { name: 'b', type: 'uint' },
  31080. { name: 'c', type: 'uint' }
  31081. ]
  31082. } );
  31083. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  31084. const bits = uint( bits_immutable ).toVar();
  31085. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  31086. } ).setLayout( {
  31087. name: 'mx_bits_to_01',
  31088. type: 'float',
  31089. inputs: [
  31090. { name: 'bits', type: 'uint' }
  31091. ]
  31092. } );
  31093. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  31094. const t = float( t_immutable ).toVar();
  31095. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  31096. } ).setLayout( {
  31097. name: 'mx_fade',
  31098. type: 'float',
  31099. inputs: [
  31100. { name: 't', type: 'float' }
  31101. ]
  31102. } );
  31103. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  31104. const x = int( x_immutable ).toVar();
  31105. const len = uint( uint( 1 ) ).toVar();
  31106. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  31107. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  31108. } ).setLayout( {
  31109. name: 'mx_hash_int_0',
  31110. type: 'uint',
  31111. inputs: [
  31112. { name: 'x', type: 'int' }
  31113. ]
  31114. } );
  31115. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  31116. const y = int( y_immutable ).toVar();
  31117. const x = int( x_immutable ).toVar();
  31118. const len = uint( uint( 2 ) ).toVar();
  31119. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31120. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31121. a.addAssign( uint( x ) );
  31122. b.addAssign( uint( y ) );
  31123. return mx_bjfinal( a, b, c );
  31124. } ).setLayout( {
  31125. name: 'mx_hash_int_1',
  31126. type: 'uint',
  31127. inputs: [
  31128. { name: 'x', type: 'int' },
  31129. { name: 'y', type: 'int' }
  31130. ]
  31131. } );
  31132. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  31133. const z = int( z_immutable ).toVar();
  31134. const y = int( y_immutable ).toVar();
  31135. const x = int( x_immutable ).toVar();
  31136. const len = uint( uint( 3 ) ).toVar();
  31137. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31138. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31139. a.addAssign( uint( x ) );
  31140. b.addAssign( uint( y ) );
  31141. c.addAssign( uint( z ) );
  31142. return mx_bjfinal( a, b, c );
  31143. } ).setLayout( {
  31144. name: 'mx_hash_int_2',
  31145. type: 'uint',
  31146. inputs: [
  31147. { name: 'x', type: 'int' },
  31148. { name: 'y', type: 'int' },
  31149. { name: 'z', type: 'int' }
  31150. ]
  31151. } );
  31152. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  31153. const xx = int( xx_immutable ).toVar();
  31154. const z = int( z_immutable ).toVar();
  31155. const y = int( y_immutable ).toVar();
  31156. const x = int( x_immutable ).toVar();
  31157. const len = uint( uint( 4 ) ).toVar();
  31158. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31159. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31160. a.addAssign( uint( x ) );
  31161. b.addAssign( uint( y ) );
  31162. c.addAssign( uint( z ) );
  31163. mx_bjmix( a, b, c );
  31164. a.addAssign( uint( xx ) );
  31165. return mx_bjfinal( a, b, c );
  31166. } ).setLayout( {
  31167. name: 'mx_hash_int_3',
  31168. type: 'uint',
  31169. inputs: [
  31170. { name: 'x', type: 'int' },
  31171. { name: 'y', type: 'int' },
  31172. { name: 'z', type: 'int' },
  31173. { name: 'xx', type: 'int' }
  31174. ]
  31175. } );
  31176. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  31177. const yy = int( yy_immutable ).toVar();
  31178. const xx = int( xx_immutable ).toVar();
  31179. const z = int( z_immutable ).toVar();
  31180. const y = int( y_immutable ).toVar();
  31181. const x = int( x_immutable ).toVar();
  31182. const len = uint( uint( 5 ) ).toVar();
  31183. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31184. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31185. a.addAssign( uint( x ) );
  31186. b.addAssign( uint( y ) );
  31187. c.addAssign( uint( z ) );
  31188. mx_bjmix( a, b, c );
  31189. a.addAssign( uint( xx ) );
  31190. b.addAssign( uint( yy ) );
  31191. return mx_bjfinal( a, b, c );
  31192. } ).setLayout( {
  31193. name: 'mx_hash_int_4',
  31194. type: 'uint',
  31195. inputs: [
  31196. { name: 'x', type: 'int' },
  31197. { name: 'y', type: 'int' },
  31198. { name: 'z', type: 'int' },
  31199. { name: 'xx', type: 'int' },
  31200. { name: 'yy', type: 'int' }
  31201. ]
  31202. } );
  31203. 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 ] );
  31204. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  31205. const y = int( y_immutable ).toVar();
  31206. const x = int( x_immutable ).toVar();
  31207. const h = uint( mx_hash_int( x, y ) ).toVar();
  31208. const result = uvec3().toVar();
  31209. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  31210. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  31211. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  31212. return result;
  31213. } ).setLayout( {
  31214. name: 'mx_hash_vec3_0',
  31215. type: 'uvec3',
  31216. inputs: [
  31217. { name: 'x', type: 'int' },
  31218. { name: 'y', type: 'int' }
  31219. ]
  31220. } );
  31221. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  31222. const z = int( z_immutable ).toVar();
  31223. const y = int( y_immutable ).toVar();
  31224. const x = int( x_immutable ).toVar();
  31225. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  31226. const result = uvec3().toVar();
  31227. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  31228. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  31229. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  31230. return result;
  31231. } ).setLayout( {
  31232. name: 'mx_hash_vec3_1',
  31233. type: 'uvec3',
  31234. inputs: [
  31235. { name: 'x', type: 'int' },
  31236. { name: 'y', type: 'int' },
  31237. { name: 'z', type: 'int' }
  31238. ]
  31239. } );
  31240. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  31241. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31242. const p = vec2( p_immutable ).toVar();
  31243. const X = int().toVar(), Y = int().toVar();
  31244. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31245. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31246. const u = float( mx_fade( fx ) ).toVar();
  31247. const v = float( mx_fade( fy ) ).toVar();
  31248. 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();
  31249. return mx_gradient_scale2d( result );
  31250. } ).setLayout( {
  31251. name: 'mx_perlin_noise_float_0',
  31252. type: 'float',
  31253. inputs: [
  31254. { name: 'p', type: 'vec2' }
  31255. ]
  31256. } );
  31257. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31258. const p = vec3( p_immutable ).toVar();
  31259. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31260. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31261. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31262. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  31263. const u = float( mx_fade( fx ) ).toVar();
  31264. const v = float( mx_fade( fy ) ).toVar();
  31265. const w = float( mx_fade( fz ) ).toVar();
  31266. 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();
  31267. return mx_gradient_scale3d( result );
  31268. } ).setLayout( {
  31269. name: 'mx_perlin_noise_float_1',
  31270. type: 'float',
  31271. inputs: [
  31272. { name: 'p', type: 'vec3' }
  31273. ]
  31274. } );
  31275. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  31276. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31277. const p = vec2( p_immutable ).toVar();
  31278. const X = int().toVar(), Y = int().toVar();
  31279. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31280. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31281. const u = float( mx_fade( fx ) ).toVar();
  31282. const v = float( mx_fade( fy ) ).toVar();
  31283. 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();
  31284. return mx_gradient_scale2d( result );
  31285. } ).setLayout( {
  31286. name: 'mx_perlin_noise_vec3_0',
  31287. type: 'vec3',
  31288. inputs: [
  31289. { name: 'p', type: 'vec2' }
  31290. ]
  31291. } );
  31292. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31293. const p = vec3( p_immutable ).toVar();
  31294. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31295. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31296. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31297. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  31298. const u = float( mx_fade( fx ) ).toVar();
  31299. const v = float( mx_fade( fy ) ).toVar();
  31300. const w = float( mx_fade( fz ) ).toVar();
  31301. 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();
  31302. return mx_gradient_scale3d( result );
  31303. } ).setLayout( {
  31304. name: 'mx_perlin_noise_vec3_1',
  31305. type: 'vec3',
  31306. inputs: [
  31307. { name: 'p', type: 'vec3' }
  31308. ]
  31309. } );
  31310. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  31311. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31312. const p = float( p_immutable ).toVar();
  31313. const ix = int( mx_floor( p ) ).toVar();
  31314. return mx_bits_to_01( mx_hash_int( ix ) );
  31315. } ).setLayout( {
  31316. name: 'mx_cell_noise_float_0',
  31317. type: 'float',
  31318. inputs: [
  31319. { name: 'p', type: 'float' }
  31320. ]
  31321. } );
  31322. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31323. const p = vec2( p_immutable ).toVar();
  31324. const ix = int( mx_floor( p.x ) ).toVar();
  31325. const iy = int( mx_floor( p.y ) ).toVar();
  31326. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  31327. } ).setLayout( {
  31328. name: 'mx_cell_noise_float_1',
  31329. type: 'float',
  31330. inputs: [
  31331. { name: 'p', type: 'vec2' }
  31332. ]
  31333. } );
  31334. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31335. const p = vec3( p_immutable ).toVar();
  31336. const ix = int( mx_floor( p.x ) ).toVar();
  31337. const iy = int( mx_floor( p.y ) ).toVar();
  31338. const iz = int( mx_floor( p.z ) ).toVar();
  31339. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  31340. } ).setLayout( {
  31341. name: 'mx_cell_noise_float_2',
  31342. type: 'float',
  31343. inputs: [
  31344. { name: 'p', type: 'vec3' }
  31345. ]
  31346. } );
  31347. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31348. const p = vec4( p_immutable ).toVar();
  31349. const ix = int( mx_floor( p.x ) ).toVar();
  31350. const iy = int( mx_floor( p.y ) ).toVar();
  31351. const iz = int( mx_floor( p.z ) ).toVar();
  31352. const iw = int( mx_floor( p.w ) ).toVar();
  31353. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  31354. } ).setLayout( {
  31355. name: 'mx_cell_noise_float_3',
  31356. type: 'float',
  31357. inputs: [
  31358. { name: 'p', type: 'vec4' }
  31359. ]
  31360. } );
  31361. 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 ] );
  31362. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31363. const p = float( p_immutable ).toVar();
  31364. const ix = int( mx_floor( p ) ).toVar();
  31365. 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 ) ) ) );
  31366. } ).setLayout( {
  31367. name: 'mx_cell_noise_vec3_0',
  31368. type: 'vec3',
  31369. inputs: [
  31370. { name: 'p', type: 'float' }
  31371. ]
  31372. } );
  31373. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31374. const p = vec2( p_immutable ).toVar();
  31375. const ix = int( mx_floor( p.x ) ).toVar();
  31376. const iy = int( mx_floor( p.y ) ).toVar();
  31377. 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 ) ) ) );
  31378. } ).setLayout( {
  31379. name: 'mx_cell_noise_vec3_1',
  31380. type: 'vec3',
  31381. inputs: [
  31382. { name: 'p', type: 'vec2' }
  31383. ]
  31384. } );
  31385. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31386. const p = vec3( p_immutable ).toVar();
  31387. const ix = int( mx_floor( p.x ) ).toVar();
  31388. const iy = int( mx_floor( p.y ) ).toVar();
  31389. const iz = int( mx_floor( p.z ) ).toVar();
  31390. 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 ) ) ) );
  31391. } ).setLayout( {
  31392. name: 'mx_cell_noise_vec3_2',
  31393. type: 'vec3',
  31394. inputs: [
  31395. { name: 'p', type: 'vec3' }
  31396. ]
  31397. } );
  31398. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31399. const p = vec4( p_immutable ).toVar();
  31400. const ix = int( mx_floor( p.x ) ).toVar();
  31401. const iy = int( mx_floor( p.y ) ).toVar();
  31402. const iz = int( mx_floor( p.z ) ).toVar();
  31403. const iw = int( mx_floor( p.w ) ).toVar();
  31404. 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 ) ) ) );
  31405. } ).setLayout( {
  31406. name: 'mx_cell_noise_vec3_3',
  31407. type: 'vec3',
  31408. inputs: [
  31409. { name: 'p', type: 'vec4' }
  31410. ]
  31411. } );
  31412. 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 ] );
  31413. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31414. const diminish = float( diminish_immutable ).toVar();
  31415. const lacunarity = float( lacunarity_immutable ).toVar();
  31416. const octaves = int( octaves_immutable ).toVar();
  31417. const p = vec3( p_immutable ).toVar();
  31418. const result = float( 0.0 ).toVar();
  31419. const amplitude = float( 1.0 ).toVar();
  31420. Loop( octaves, () => {
  31421. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  31422. amplitude.mulAssign( diminish );
  31423. p.mulAssign( lacunarity );
  31424. } );
  31425. return result;
  31426. } ).setLayout( {
  31427. name: 'mx_fractal_noise_float',
  31428. type: 'float',
  31429. inputs: [
  31430. { name: 'p', type: 'vec3' },
  31431. { name: 'octaves', type: 'int' },
  31432. { name: 'lacunarity', type: 'float' },
  31433. { name: 'diminish', type: 'float' }
  31434. ]
  31435. } );
  31436. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31437. const diminish = float( diminish_immutable ).toVar();
  31438. const lacunarity = float( lacunarity_immutable ).toVar();
  31439. const octaves = int( octaves_immutable ).toVar();
  31440. const p = vec3( p_immutable ).toVar();
  31441. const result = vec3( 0.0 ).toVar();
  31442. const amplitude = float( 1.0 ).toVar();
  31443. Loop( octaves, () => {
  31444. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  31445. amplitude.mulAssign( diminish );
  31446. p.mulAssign( lacunarity );
  31447. } );
  31448. return result;
  31449. } ).setLayout( {
  31450. name: 'mx_fractal_noise_vec3',
  31451. type: 'vec3',
  31452. inputs: [
  31453. { name: 'p', type: 'vec3' },
  31454. { name: 'octaves', type: 'int' },
  31455. { name: 'lacunarity', type: 'float' },
  31456. { name: 'diminish', type: 'float' }
  31457. ]
  31458. } );
  31459. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31460. const diminish = float( diminish_immutable ).toVar();
  31461. const lacunarity = float( lacunarity_immutable ).toVar();
  31462. const octaves = int( octaves_immutable ).toVar();
  31463. const p = vec3( p_immutable ).toVar();
  31464. 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 ) );
  31465. } ).setLayout( {
  31466. name: 'mx_fractal_noise_vec2',
  31467. type: 'vec2',
  31468. inputs: [
  31469. { name: 'p', type: 'vec3' },
  31470. { name: 'octaves', type: 'int' },
  31471. { name: 'lacunarity', type: 'float' },
  31472. { name: 'diminish', type: 'float' }
  31473. ]
  31474. } );
  31475. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31476. const diminish = float( diminish_immutable ).toVar();
  31477. const lacunarity = float( lacunarity_immutable ).toVar();
  31478. const octaves = int( octaves_immutable ).toVar();
  31479. const p = vec3( p_immutable ).toVar();
  31480. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  31481. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  31482. return vec4( c, f );
  31483. } ).setLayout( {
  31484. name: 'mx_fractal_noise_vec4',
  31485. type: 'vec4',
  31486. inputs: [
  31487. { name: 'p', type: 'vec3' },
  31488. { name: 'octaves', type: 'int' },
  31489. { name: 'lacunarity', type: 'float' },
  31490. { name: 'diminish', type: 'float' }
  31491. ]
  31492. } );
  31493. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  31494. const metric = int( metric_immutable ).toVar();
  31495. const jitter = float( jitter_immutable ).toVar();
  31496. const yoff = int( yoff_immutable ).toVar();
  31497. const xoff = int( xoff_immutable ).toVar();
  31498. const y = int( y_immutable ).toVar();
  31499. const x = int( x_immutable ).toVar();
  31500. const p = vec2( p_immutable ).toVar();
  31501. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  31502. const off = vec2( tmp.x, tmp.y ).toVar();
  31503. off.subAssign( 0.5 );
  31504. off.mulAssign( jitter );
  31505. off.addAssign( 0.5 );
  31506. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  31507. const diff = vec2( cellpos.sub( p ) ).toVar();
  31508. If( metric.equal( int( 2 ) ), () => {
  31509. return abs( diff.x ).add( abs( diff.y ) );
  31510. } );
  31511. If( metric.equal( int( 3 ) ), () => {
  31512. return max$1( abs( diff.x ), abs( diff.y ) );
  31513. } );
  31514. return dot( diff, diff );
  31515. } ).setLayout( {
  31516. name: 'mx_worley_distance_0',
  31517. type: 'float',
  31518. inputs: [
  31519. { name: 'p', type: 'vec2' },
  31520. { name: 'x', type: 'int' },
  31521. { name: 'y', type: 'int' },
  31522. { name: 'xoff', type: 'int' },
  31523. { name: 'yoff', type: 'int' },
  31524. { name: 'jitter', type: 'float' },
  31525. { name: 'metric', type: 'int' }
  31526. ]
  31527. } );
  31528. 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 ] ) => {
  31529. const metric = int( metric_immutable ).toVar();
  31530. const jitter = float( jitter_immutable ).toVar();
  31531. const zoff = int( zoff_immutable ).toVar();
  31532. const yoff = int( yoff_immutable ).toVar();
  31533. const xoff = int( xoff_immutable ).toVar();
  31534. const z = int( z_immutable ).toVar();
  31535. const y = int( y_immutable ).toVar();
  31536. const x = int( x_immutable ).toVar();
  31537. const p = vec3( p_immutable ).toVar();
  31538. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  31539. off.subAssign( 0.5 );
  31540. off.mulAssign( jitter );
  31541. off.addAssign( 0.5 );
  31542. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  31543. const diff = vec3( cellpos.sub( p ) ).toVar();
  31544. If( metric.equal( int( 2 ) ), () => {
  31545. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  31546. } );
  31547. If( metric.equal( int( 3 ) ), () => {
  31548. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  31549. } );
  31550. return dot( diff, diff );
  31551. } ).setLayout( {
  31552. name: 'mx_worley_distance_1',
  31553. type: 'float',
  31554. inputs: [
  31555. { name: 'p', type: 'vec3' },
  31556. { name: 'x', type: 'int' },
  31557. { name: 'y', type: 'int' },
  31558. { name: 'z', type: 'int' },
  31559. { name: 'xoff', type: 'int' },
  31560. { name: 'yoff', type: 'int' },
  31561. { name: 'zoff', type: 'int' },
  31562. { name: 'jitter', type: 'float' },
  31563. { name: 'metric', type: 'int' }
  31564. ]
  31565. } );
  31566. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  31567. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31568. const metric = int( metric_immutable ).toVar();
  31569. const jitter = float( jitter_immutable ).toVar();
  31570. const p = vec2( p_immutable ).toVar();
  31571. const X = int().toVar(), Y = int().toVar();
  31572. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31573. const sqdist = float( 1e6 ).toVar();
  31574. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31575. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31576. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31577. sqdist.assign( min$1( sqdist, dist ) );
  31578. } );
  31579. } );
  31580. If( metric.equal( int( 0 ) ), () => {
  31581. sqdist.assign( sqrt( sqdist ) );
  31582. } );
  31583. return sqdist;
  31584. } ).setLayout( {
  31585. name: 'mx_worley_noise_float_0',
  31586. type: 'float',
  31587. inputs: [
  31588. { name: 'p', type: 'vec2' },
  31589. { name: 'jitter', type: 'float' },
  31590. { name: 'metric', type: 'int' }
  31591. ]
  31592. } );
  31593. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31594. const metric = int( metric_immutable ).toVar();
  31595. const jitter = float( jitter_immutable ).toVar();
  31596. const p = vec2( p_immutable ).toVar();
  31597. const X = int().toVar(), Y = int().toVar();
  31598. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31599. const sqdist = vec2( 1e6, 1e6 ).toVar();
  31600. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31601. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31602. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31603. If( dist.lessThan( sqdist.x ), () => {
  31604. sqdist.y.assign( sqdist.x );
  31605. sqdist.x.assign( dist );
  31606. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31607. sqdist.y.assign( dist );
  31608. } );
  31609. } );
  31610. } );
  31611. If( metric.equal( int( 0 ) ), () => {
  31612. sqdist.assign( sqrt( sqdist ) );
  31613. } );
  31614. return sqdist;
  31615. } ).setLayout( {
  31616. name: 'mx_worley_noise_vec2_0',
  31617. type: 'vec2',
  31618. inputs: [
  31619. { name: 'p', type: 'vec2' },
  31620. { name: 'jitter', type: 'float' },
  31621. { name: 'metric', type: 'int' }
  31622. ]
  31623. } );
  31624. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31625. const metric = int( metric_immutable ).toVar();
  31626. const jitter = float( jitter_immutable ).toVar();
  31627. const p = vec2( p_immutable ).toVar();
  31628. const X = int().toVar(), Y = int().toVar();
  31629. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31630. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  31631. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31632. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31633. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31634. If( dist.lessThan( sqdist.x ), () => {
  31635. sqdist.z.assign( sqdist.y );
  31636. sqdist.y.assign( sqdist.x );
  31637. sqdist.x.assign( dist );
  31638. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31639. sqdist.z.assign( sqdist.y );
  31640. sqdist.y.assign( dist );
  31641. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  31642. sqdist.z.assign( dist );
  31643. } );
  31644. } );
  31645. } );
  31646. If( metric.equal( int( 0 ) ), () => {
  31647. sqdist.assign( sqrt( sqdist ) );
  31648. } );
  31649. return sqdist;
  31650. } ).setLayout( {
  31651. name: 'mx_worley_noise_vec3_0',
  31652. type: 'vec3',
  31653. inputs: [
  31654. { name: 'p', type: 'vec2' },
  31655. { name: 'jitter', type: 'float' },
  31656. { name: 'metric', type: 'int' }
  31657. ]
  31658. } );
  31659. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31660. const metric = int( metric_immutable ).toVar();
  31661. const jitter = float( jitter_immutable ).toVar();
  31662. const p = vec3( p_immutable ).toVar();
  31663. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31664. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31665. const sqdist = float( 1e6 ).toVar();
  31666. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31667. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31668. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31669. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31670. sqdist.assign( min$1( sqdist, dist ) );
  31671. } );
  31672. } );
  31673. } );
  31674. If( metric.equal( int( 0 ) ), () => {
  31675. sqdist.assign( sqrt( sqdist ) );
  31676. } );
  31677. return sqdist;
  31678. } ).setLayout( {
  31679. name: 'mx_worley_noise_float_1',
  31680. type: 'float',
  31681. inputs: [
  31682. { name: 'p', type: 'vec3' },
  31683. { name: 'jitter', type: 'float' },
  31684. { name: 'metric', type: 'int' }
  31685. ]
  31686. } );
  31687. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  31688. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31689. const metric = int( metric_immutable ).toVar();
  31690. const jitter = float( jitter_immutable ).toVar();
  31691. const p = vec3( p_immutable ).toVar();
  31692. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31693. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31694. const sqdist = vec2( 1e6, 1e6 ).toVar();
  31695. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31696. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31697. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31698. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31699. If( dist.lessThan( sqdist.x ), () => {
  31700. sqdist.y.assign( sqdist.x );
  31701. sqdist.x.assign( dist );
  31702. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31703. sqdist.y.assign( dist );
  31704. } );
  31705. } );
  31706. } );
  31707. } );
  31708. If( metric.equal( int( 0 ) ), () => {
  31709. sqdist.assign( sqrt( sqdist ) );
  31710. } );
  31711. return sqdist;
  31712. } ).setLayout( {
  31713. name: 'mx_worley_noise_vec2_1',
  31714. type: 'vec2',
  31715. inputs: [
  31716. { name: 'p', type: 'vec3' },
  31717. { name: 'jitter', type: 'float' },
  31718. { name: 'metric', type: 'int' }
  31719. ]
  31720. } );
  31721. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  31722. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31723. const metric = int( metric_immutable ).toVar();
  31724. const jitter = float( jitter_immutable ).toVar();
  31725. const p = vec3( p_immutable ).toVar();
  31726. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31727. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31728. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  31729. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31730. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31731. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31732. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31733. If( dist.lessThan( sqdist.x ), () => {
  31734. sqdist.z.assign( sqdist.y );
  31735. sqdist.y.assign( sqdist.x );
  31736. sqdist.x.assign( dist );
  31737. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31738. sqdist.z.assign( sqdist.y );
  31739. sqdist.y.assign( dist );
  31740. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  31741. sqdist.z.assign( dist );
  31742. } );
  31743. } );
  31744. } );
  31745. } );
  31746. If( metric.equal( int( 0 ) ), () => {
  31747. sqdist.assign( sqrt( sqdist ) );
  31748. } );
  31749. return sqdist;
  31750. } ).setLayout( {
  31751. name: 'mx_worley_noise_vec3_1',
  31752. type: 'vec3',
  31753. inputs: [
  31754. { name: 'p', type: 'vec3' },
  31755. { name: 'jitter', type: 'float' },
  31756. { name: 'metric', type: 'int' }
  31757. ]
  31758. } );
  31759. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  31760. // Unified Noise 2D
  31761. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  31762. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  31763. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  31764. octaves_immutable, lacunarity_immutable, diminish_immutable
  31765. ] ) => {
  31766. const noiseType = int( noiseType_immutable ).toVar();
  31767. const texcoord = vec2( texcoord_immutable ).toVar();
  31768. const freq = vec2( freq_immutable ).toVar();
  31769. const offset = vec2( offset_immutable ).toVar();
  31770. const jitter = float( jitter_immutable ).toVar();
  31771. const outmin = float( outmin_immutable ).toVar();
  31772. const outmax = float( outmax_immutable ).toVar();
  31773. const clampoutput = bool( clampoutput_immutable ).toVar();
  31774. const octaves = int( octaves_immutable ).toVar();
  31775. const lacunarity = float( lacunarity_immutable ).toVar();
  31776. const diminish = float( diminish_immutable ).toVar();
  31777. // Compute input position
  31778. const p = texcoord.mul( freq ).add( offset );
  31779. const result = float( 0.0 ).toVar();
  31780. // Perlin
  31781. If( noiseType.equal( int( 0 ) ), () => {
  31782. result.assign( mx_perlin_noise_vec3( p ) );
  31783. } );
  31784. // Cell
  31785. If( noiseType.equal( int( 1 ) ), () => {
  31786. result.assign( mx_cell_noise_vec3( p ) );
  31787. } );
  31788. // Worley (metric=0 = euclidean)
  31789. If( noiseType.equal( int( 2 ) ), () => {
  31790. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  31791. } );
  31792. // Fractal (use vec3(p, 0.0) for 2D input)
  31793. If( noiseType.equal( int( 3 ) ), () => {
  31794. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  31795. } );
  31796. // Remap output to [outmin, outmax]
  31797. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  31798. // Clamp if requested
  31799. If( clampoutput, () => {
  31800. result.assign( clamp( result, outmin, outmax ) );
  31801. } );
  31802. return result;
  31803. } ).setLayout( {
  31804. name: 'mx_unifiednoise2d',
  31805. type: 'float',
  31806. inputs: [
  31807. { name: 'noiseType', type: 'int' },
  31808. { name: 'texcoord', type: 'vec2' },
  31809. { name: 'freq', type: 'vec2' },
  31810. { name: 'offset', type: 'vec2' },
  31811. { name: 'jitter', type: 'float' },
  31812. { name: 'outmin', type: 'float' },
  31813. { name: 'outmax', type: 'float' },
  31814. { name: 'clampoutput', type: 'bool' },
  31815. { name: 'octaves', type: 'int' },
  31816. { name: 'lacunarity', type: 'float' },
  31817. { name: 'diminish', type: 'float' }
  31818. ]
  31819. } );
  31820. // Unified Noise 3D
  31821. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  31822. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  31823. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  31824. octaves_immutable, lacunarity_immutable, diminish_immutable
  31825. ] ) => {
  31826. const noiseType = int( noiseType_immutable ).toVar();
  31827. const position = vec3( position_immutable ).toVar();
  31828. const freq = vec3( freq_immutable ).toVar();
  31829. const offset = vec3( offset_immutable ).toVar();
  31830. const jitter = float( jitter_immutable ).toVar();
  31831. const outmin = float( outmin_immutable ).toVar();
  31832. const outmax = float( outmax_immutable ).toVar();
  31833. const clampoutput = bool( clampoutput_immutable ).toVar();
  31834. const octaves = int( octaves_immutable ).toVar();
  31835. const lacunarity = float( lacunarity_immutable ).toVar();
  31836. const diminish = float( diminish_immutable ).toVar();
  31837. // Compute input position
  31838. const p = position.mul( freq ).add( offset );
  31839. const result = float( 0.0 ).toVar();
  31840. // Perlin
  31841. If( noiseType.equal( int( 0 ) ), () => {
  31842. result.assign( mx_perlin_noise_vec3( p ) );
  31843. } );
  31844. // Cell
  31845. If( noiseType.equal( int( 1 ) ), () => {
  31846. result.assign( mx_cell_noise_vec3( p ) );
  31847. } );
  31848. // Worley (metric=0 = euclidean)
  31849. If( noiseType.equal( int( 2 ) ), () => {
  31850. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  31851. } );
  31852. // Fractal
  31853. If( noiseType.equal( int( 3 ) ), () => {
  31854. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  31855. } );
  31856. // Remap output to [outmin, outmax]
  31857. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  31858. // Clamp if requested
  31859. If( clampoutput, () => {
  31860. result.assign( clamp( result, outmin, outmax ) );
  31861. } );
  31862. return result;
  31863. } ).setLayout( {
  31864. name: 'mx_unifiednoise3d',
  31865. type: 'float',
  31866. inputs: [
  31867. { name: 'noiseType', type: 'int' },
  31868. { name: 'position', type: 'vec3' },
  31869. { name: 'freq', type: 'vec3' },
  31870. { name: 'offset', type: 'vec3' },
  31871. { name: 'jitter', type: 'float' },
  31872. { name: 'outmin', type: 'float' },
  31873. { name: 'outmax', type: 'float' },
  31874. { name: 'clampoutput', type: 'bool' },
  31875. { name: 'octaves', type: 'int' },
  31876. { name: 'lacunarity', type: 'float' },
  31877. { name: 'diminish', type: 'float' }
  31878. ]
  31879. } );
  31880. // Three.js Transpiler
  31881. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  31882. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  31883. const s = hsv.y;
  31884. const v = hsv.z;
  31885. const result = vec3().toVar();
  31886. If( s.lessThan( 0.0001 ), () => {
  31887. result.assign( vec3( v, v, v ) );
  31888. } ).Else( () => {
  31889. let h = hsv.x;
  31890. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  31891. const hi = int( trunc( h ) );
  31892. const f = h.sub( float( hi ) );
  31893. const p = v.mul( s.oneMinus() );
  31894. const q = v.mul( s.mul( f ).oneMinus() );
  31895. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  31896. If( hi.equal( int( 0 ) ), () => {
  31897. result.assign( vec3( v, t, p ) );
  31898. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  31899. result.assign( vec3( q, v, p ) );
  31900. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  31901. result.assign( vec3( p, v, t ) );
  31902. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  31903. result.assign( vec3( p, q, v ) );
  31904. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  31905. result.assign( vec3( t, p, v ) );
  31906. } ).Else( () => {
  31907. result.assign( vec3( v, p, q ) );
  31908. } );
  31909. } );
  31910. return result;
  31911. } ).setLayout( {
  31912. name: 'mx_hsvtorgb',
  31913. type: 'vec3',
  31914. inputs: [
  31915. { name: 'hsv', type: 'vec3' }
  31916. ]
  31917. } );
  31918. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  31919. const c = vec3( c_immutable ).toVar();
  31920. const r = float( c.x ).toVar();
  31921. const g = float( c.y ).toVar();
  31922. const b = float( c.z ).toVar();
  31923. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  31924. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  31925. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  31926. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  31927. v.assign( maxcomp );
  31928. If( maxcomp.greaterThan( 0.0 ), () => {
  31929. s.assign( delta.div( maxcomp ) );
  31930. } ).Else( () => {
  31931. s.assign( 0.0 );
  31932. } );
  31933. If( s.lessThanEqual( 0.0 ), () => {
  31934. h.assign( 0.0 );
  31935. } ).Else( () => {
  31936. If( r.greaterThanEqual( maxcomp ), () => {
  31937. h.assign( g.sub( b ).div( delta ) );
  31938. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  31939. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  31940. } ).Else( () => {
  31941. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  31942. } );
  31943. h.mulAssign( 1.0 / 6.0 );
  31944. If( h.lessThan( 0.0 ), () => {
  31945. h.addAssign( 1.0 );
  31946. } );
  31947. } );
  31948. return vec3( h, s, v );
  31949. } ).setLayout( {
  31950. name: 'mx_rgbtohsv',
  31951. type: 'vec3',
  31952. inputs: [
  31953. { name: 'c', type: 'vec3' }
  31954. ]
  31955. } );
  31956. // Three.js Transpiler
  31957. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  31958. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  31959. const color = vec3( color_immutable ).toVar();
  31960. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  31961. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  31962. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  31963. return mix( linSeg, powSeg, isAbove );
  31964. } ).setLayout( {
  31965. name: 'mx_srgb_texture_to_lin_rec709',
  31966. type: 'vec3',
  31967. inputs: [
  31968. { name: 'color', type: 'vec3' }
  31969. ]
  31970. } );
  31971. const mx_aastep = ( threshold, value ) => {
  31972. threshold = float( threshold );
  31973. value = float( value );
  31974. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  31975. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  31976. };
  31977. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  31978. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  31979. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  31980. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  31981. const mx_ramp4 = (
  31982. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  31983. ) => {
  31984. const u = texcoord.x.clamp();
  31985. const v = texcoord.y.clamp();
  31986. const top = mix( valuetl, valuetr, u );
  31987. const bottom = mix( valuebl, valuebr, u );
  31988. return mix( top, bottom, v );
  31989. };
  31990. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  31991. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  31992. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  31993. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  31994. const mx_safepower = ( in1, in2 = 1 ) => {
  31995. in1 = float( in1 );
  31996. return in1.abs().pow( in2 ).mul( in1.sign() );
  31997. };
  31998. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  31999. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  32000. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  32001. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  32002. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  32003. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  32004. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  32005. return noise_vec4.mul( amplitude ).add( pivot );
  32006. };
  32007. 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 );
  32008. 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 );
  32009. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32010. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32011. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32012. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  32013. 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 );
  32014. 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 );
  32015. 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 );
  32016. 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 );
  32017. // === Moved from MaterialXLoader.js ===
  32018. // Math ops
  32019. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  32020. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  32021. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  32022. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  32023. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  32024. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  32025. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  32026. const mx_timer = () => time;
  32027. const mx_frame = () => frameId;
  32028. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  32029. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  32030. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  32031. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  32032. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  32033. const mx_separate = ( in1, channelOrOut = null ) => {
  32034. if ( typeof channelOrOut === 'string' ) {
  32035. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  32036. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  32037. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  32038. }
  32039. if ( typeof channelOrOut === 'number' ) {
  32040. return in1.element( channelOrOut );
  32041. }
  32042. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  32043. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  32044. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  32045. }
  32046. return in1;
  32047. };
  32048. const mx_place2d = (
  32049. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  32050. ) => {
  32051. let uv = texcoord;
  32052. if ( pivot ) uv = uv.sub( pivot );
  32053. if ( scale ) uv = uv.mul( scale );
  32054. if ( rotate ) {
  32055. const rad = rotate.mul( Math.PI / 180.0 );
  32056. const cosR = rad.cos();
  32057. const sinR = rad.sin();
  32058. uv = vec2(
  32059. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  32060. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  32061. );
  32062. }
  32063. if ( pivot ) uv = uv.add( pivot );
  32064. if ( offset ) uv = uv.add( offset );
  32065. return uv;
  32066. };
  32067. const mx_rotate2d = ( input, amount ) => {
  32068. input = vec2( input );
  32069. amount = float( amount );
  32070. const radians = amount.mul( Math.PI / 180.0 );
  32071. return rotate( input, radians );
  32072. };
  32073. const mx_rotate3d = ( input, amount, axis ) => {
  32074. input = vec3( input );
  32075. amount = float( amount );
  32076. axis = vec3( axis );
  32077. const radians = amount.mul( Math.PI / 180.0 );
  32078. const nAxis = axis.normalize();
  32079. const cosA = radians.cos();
  32080. const sinA = radians.sin();
  32081. const oneMinusCosA = float( 1 ).sub( cosA );
  32082. const rot =
  32083. input.mul( cosA )
  32084. .add( nAxis.cross( input ).mul( sinA ) )
  32085. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  32086. return rot;
  32087. };
  32088. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  32089. input = vec3( input );
  32090. scale = float( scale );
  32091. return bumpMap( input, scale );
  32092. };
  32093. /**
  32094. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  32095. *
  32096. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  32097. *
  32098. * ```js
  32099. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  32100. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  32101. * ```
  32102. *
  32103. * @tsl
  32104. * @function
  32105. * @param {Node<vec3>} normal - The normal to correct.
  32106. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  32107. * @param {Node<vec3>} cubePos - The cube position.
  32108. * @return {Node<vec3>} The parallax corrected normal.
  32109. */
  32110. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  32111. const nDir = normalize( normal ).toVar();
  32112. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  32113. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  32114. const rbminmax = vec3().toVar();
  32115. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  32116. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  32117. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  32118. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  32119. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  32120. return boxIntersection.sub( cubePos );
  32121. } );
  32122. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  32123. // normal is assumed to have unit length
  32124. const x = normal.x, y = normal.y, z = normal.z;
  32125. // band 0
  32126. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  32127. // band 1
  32128. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  32129. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  32130. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  32131. // band 2
  32132. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  32133. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  32134. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  32135. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  32136. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  32137. return result;
  32138. } );
  32139. // constants
  32140. var TSL = /*#__PURE__*/Object.freeze({
  32141. __proto__: null,
  32142. BRDF_GGX: BRDF_GGX,
  32143. BRDF_Lambert: BRDF_Lambert,
  32144. BasicPointShadowFilter: BasicPointShadowFilter,
  32145. BasicShadowFilter: BasicShadowFilter,
  32146. Break: Break,
  32147. Const: Const,
  32148. Continue: Continue,
  32149. DFGApprox: DFGApprox,
  32150. D_GGX: D_GGX,
  32151. Discard: Discard,
  32152. EPSILON: EPSILON,
  32153. F_Schlick: F_Schlick,
  32154. Fn: Fn,
  32155. HALF_PI: HALF_PI,
  32156. INFINITY: INFINITY,
  32157. If: If,
  32158. Loop: Loop,
  32159. NodeAccess: NodeAccess,
  32160. NodeShaderStage: NodeShaderStage,
  32161. NodeType: NodeType,
  32162. NodeUpdateType: NodeUpdateType,
  32163. OnMaterialUpdate: OnMaterialUpdate,
  32164. OnObjectUpdate: OnObjectUpdate,
  32165. PCFShadowFilter: PCFShadowFilter,
  32166. PCFSoftShadowFilter: PCFSoftShadowFilter,
  32167. PI: PI,
  32168. PI2: PI2,
  32169. PointShadowFilter: PointShadowFilter,
  32170. Return: Return,
  32171. Schlick_to_F0: Schlick_to_F0,
  32172. ScriptableNodeResources: ScriptableNodeResources,
  32173. ShaderNode: ShaderNode,
  32174. Stack: Stack,
  32175. Switch: Switch,
  32176. TBNViewMatrix: TBNViewMatrix,
  32177. TWO_PI: TWO_PI,
  32178. VSMShadowFilter: VSMShadowFilter,
  32179. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  32180. Var: Var,
  32181. VarIntent: VarIntent,
  32182. abs: abs,
  32183. acesFilmicToneMapping: acesFilmicToneMapping,
  32184. acos: acos,
  32185. add: add,
  32186. addMethodChaining: addMethodChaining,
  32187. addNodeElement: addNodeElement,
  32188. agxToneMapping: agxToneMapping,
  32189. all: all,
  32190. alphaT: alphaT,
  32191. and: and,
  32192. anisotropy: anisotropy,
  32193. anisotropyB: anisotropyB,
  32194. anisotropyT: anisotropyT,
  32195. any: any,
  32196. append: append,
  32197. array: array,
  32198. arrayBuffer: arrayBuffer,
  32199. asin: asin,
  32200. assign: assign,
  32201. atan: atan,
  32202. atan2: atan2,
  32203. atomicAdd: atomicAdd,
  32204. atomicAnd: atomicAnd,
  32205. atomicFunc: atomicFunc,
  32206. atomicLoad: atomicLoad,
  32207. atomicMax: atomicMax,
  32208. atomicMin: atomicMin,
  32209. atomicOr: atomicOr,
  32210. atomicStore: atomicStore,
  32211. atomicSub: atomicSub,
  32212. atomicXor: atomicXor,
  32213. attenuationColor: attenuationColor,
  32214. attenuationDistance: attenuationDistance,
  32215. attribute: attribute,
  32216. attributeArray: attributeArray,
  32217. backgroundBlurriness: backgroundBlurriness,
  32218. backgroundIntensity: backgroundIntensity,
  32219. backgroundRotation: backgroundRotation,
  32220. batch: batch,
  32221. bentNormalView: bentNormalView,
  32222. billboarding: billboarding,
  32223. bitAnd: bitAnd,
  32224. bitNot: bitNot,
  32225. bitOr: bitOr,
  32226. bitXor: bitXor,
  32227. bitangentGeometry: bitangentGeometry,
  32228. bitangentLocal: bitangentLocal,
  32229. bitangentView: bitangentView,
  32230. bitangentWorld: bitangentWorld,
  32231. bitcast: bitcast,
  32232. blendBurn: blendBurn,
  32233. blendColor: blendColor,
  32234. blendDodge: blendDodge,
  32235. blendOverlay: blendOverlay,
  32236. blendScreen: blendScreen,
  32237. blur: blur,
  32238. bool: bool,
  32239. buffer: buffer,
  32240. bufferAttribute: bufferAttribute,
  32241. builtin: builtin,
  32242. bumpMap: bumpMap,
  32243. burn: burn,
  32244. bvec2: bvec2,
  32245. bvec3: bvec3,
  32246. bvec4: bvec4,
  32247. bypass: bypass,
  32248. cache: cache,
  32249. call: call,
  32250. cameraFar: cameraFar,
  32251. cameraIndex: cameraIndex,
  32252. cameraNear: cameraNear,
  32253. cameraNormalMatrix: cameraNormalMatrix,
  32254. cameraPosition: cameraPosition,
  32255. cameraProjectionMatrix: cameraProjectionMatrix,
  32256. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  32257. cameraViewMatrix: cameraViewMatrix,
  32258. cameraViewport: cameraViewport,
  32259. cameraWorldMatrix: cameraWorldMatrix,
  32260. cbrt: cbrt,
  32261. cdl: cdl,
  32262. ceil: ceil,
  32263. checker: checker,
  32264. cineonToneMapping: cineonToneMapping,
  32265. clamp: clamp,
  32266. clearcoat: clearcoat,
  32267. clearcoatNormalView: clearcoatNormalView,
  32268. clearcoatRoughness: clearcoatRoughness,
  32269. code: code,
  32270. color: color,
  32271. colorSpaceToWorking: colorSpaceToWorking,
  32272. colorToDirection: colorToDirection,
  32273. compute: compute,
  32274. computeKernel: computeKernel,
  32275. computeSkinning: computeSkinning,
  32276. context: context,
  32277. convert: convert,
  32278. convertColorSpace: convertColorSpace,
  32279. convertToTexture: convertToTexture,
  32280. cos: cos,
  32281. cross: cross,
  32282. cubeTexture: cubeTexture,
  32283. cubeTextureBase: cubeTextureBase,
  32284. cubeToUV: cubeToUV,
  32285. dFdx: dFdx,
  32286. dFdy: dFdy,
  32287. dashSize: dashSize,
  32288. debug: debug,
  32289. decrement: decrement,
  32290. decrementBefore: decrementBefore,
  32291. defaultBuildStages: defaultBuildStages,
  32292. defaultShaderStages: defaultShaderStages,
  32293. defined: defined,
  32294. degrees: degrees,
  32295. deltaTime: deltaTime,
  32296. densityFog: densityFog,
  32297. densityFogFactor: densityFogFactor,
  32298. depth: depth,
  32299. depthPass: depthPass,
  32300. determinant: determinant,
  32301. difference: difference,
  32302. diffuseColor: diffuseColor,
  32303. directPointLight: directPointLight,
  32304. directionToColor: directionToColor,
  32305. directionToFaceDirection: directionToFaceDirection,
  32306. dispersion: dispersion,
  32307. distance: distance,
  32308. div: div,
  32309. dodge: dodge,
  32310. dot: dot,
  32311. drawIndex: drawIndex,
  32312. dynamicBufferAttribute: dynamicBufferAttribute,
  32313. element: element,
  32314. emissive: emissive,
  32315. equal: equal,
  32316. equals: equals,
  32317. equirectUV: equirectUV,
  32318. exp: exp,
  32319. exp2: exp2,
  32320. expression: expression,
  32321. faceDirection: faceDirection,
  32322. faceForward: faceForward,
  32323. faceforward: faceforward,
  32324. float: float,
  32325. floatBitsToInt: floatBitsToInt,
  32326. floatBitsToUint: floatBitsToUint,
  32327. floor: floor,
  32328. fog: fog,
  32329. fract: fract,
  32330. frameGroup: frameGroup,
  32331. frameId: frameId,
  32332. frontFacing: frontFacing,
  32333. fwidth: fwidth,
  32334. gain: gain,
  32335. gapSize: gapSize,
  32336. getConstNodeType: getConstNodeType,
  32337. getCurrentStack: getCurrentStack,
  32338. getDirection: getDirection,
  32339. getDistanceAttenuation: getDistanceAttenuation,
  32340. getGeometryRoughness: getGeometryRoughness,
  32341. getNormalFromDepth: getNormalFromDepth,
  32342. getParallaxCorrectNormal: getParallaxCorrectNormal,
  32343. getRoughness: getRoughness,
  32344. getScreenPosition: getScreenPosition,
  32345. getShIrradianceAt: getShIrradianceAt,
  32346. getShadowMaterial: getShadowMaterial,
  32347. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  32348. getTextureIndex: getTextureIndex,
  32349. getViewPosition: getViewPosition,
  32350. globalId: globalId,
  32351. glsl: glsl,
  32352. glslFn: glslFn,
  32353. grayscale: grayscale,
  32354. greaterThan: greaterThan,
  32355. greaterThanEqual: greaterThanEqual,
  32356. hash: hash,
  32357. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  32358. highpModelViewMatrix: highpModelViewMatrix,
  32359. hue: hue,
  32360. increment: increment,
  32361. incrementBefore: incrementBefore,
  32362. inspector: inspector,
  32363. instance: instance,
  32364. instanceIndex: instanceIndex,
  32365. instancedArray: instancedArray,
  32366. instancedBufferAttribute: instancedBufferAttribute,
  32367. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  32368. instancedMesh: instancedMesh,
  32369. int: int,
  32370. intBitsToFloat: intBitsToFloat,
  32371. inverse: inverse,
  32372. inverseSqrt: inverseSqrt,
  32373. inversesqrt: inversesqrt,
  32374. invocationLocalIndex: invocationLocalIndex,
  32375. invocationSubgroupIndex: invocationSubgroupIndex,
  32376. ior: ior,
  32377. iridescence: iridescence,
  32378. iridescenceIOR: iridescenceIOR,
  32379. iridescenceThickness: iridescenceThickness,
  32380. isolate: isolate,
  32381. ivec2: ivec2,
  32382. ivec3: ivec3,
  32383. ivec4: ivec4,
  32384. js: js,
  32385. label: label,
  32386. length: length,
  32387. lengthSq: lengthSq,
  32388. lessThan: lessThan,
  32389. lessThanEqual: lessThanEqual,
  32390. lightPosition: lightPosition,
  32391. lightProjectionUV: lightProjectionUV,
  32392. lightShadowMatrix: lightShadowMatrix,
  32393. lightTargetDirection: lightTargetDirection,
  32394. lightTargetPosition: lightTargetPosition,
  32395. lightViewPosition: lightViewPosition,
  32396. lightingContext: lightingContext,
  32397. lights: lights,
  32398. linearDepth: linearDepth,
  32399. linearToneMapping: linearToneMapping,
  32400. localId: localId,
  32401. log: log,
  32402. log2: log2,
  32403. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  32404. luminance: luminance,
  32405. mat2: mat2,
  32406. mat3: mat3,
  32407. mat4: mat4,
  32408. matcapUV: matcapUV,
  32409. materialAO: materialAO,
  32410. materialAlphaTest: materialAlphaTest,
  32411. materialAnisotropy: materialAnisotropy,
  32412. materialAnisotropyVector: materialAnisotropyVector,
  32413. materialAttenuationColor: materialAttenuationColor,
  32414. materialAttenuationDistance: materialAttenuationDistance,
  32415. materialClearcoat: materialClearcoat,
  32416. materialClearcoatNormal: materialClearcoatNormal,
  32417. materialClearcoatRoughness: materialClearcoatRoughness,
  32418. materialColor: materialColor,
  32419. materialDispersion: materialDispersion,
  32420. materialEmissive: materialEmissive,
  32421. materialEnvIntensity: materialEnvIntensity,
  32422. materialEnvRotation: materialEnvRotation,
  32423. materialIOR: materialIOR,
  32424. materialIridescence: materialIridescence,
  32425. materialIridescenceIOR: materialIridescenceIOR,
  32426. materialIridescenceThickness: materialIridescenceThickness,
  32427. materialLightMap: materialLightMap,
  32428. materialLineDashOffset: materialLineDashOffset,
  32429. materialLineDashSize: materialLineDashSize,
  32430. materialLineGapSize: materialLineGapSize,
  32431. materialLineScale: materialLineScale,
  32432. materialLineWidth: materialLineWidth,
  32433. materialMetalness: materialMetalness,
  32434. materialNormal: materialNormal,
  32435. materialOpacity: materialOpacity,
  32436. materialPointSize: materialPointSize,
  32437. materialReference: materialReference,
  32438. materialReflectivity: materialReflectivity,
  32439. materialRefractionRatio: materialRefractionRatio,
  32440. materialRotation: materialRotation,
  32441. materialRoughness: materialRoughness,
  32442. materialSheen: materialSheen,
  32443. materialSheenRoughness: materialSheenRoughness,
  32444. materialShininess: materialShininess,
  32445. materialSpecular: materialSpecular,
  32446. materialSpecularColor: materialSpecularColor,
  32447. materialSpecularIntensity: materialSpecularIntensity,
  32448. materialSpecularStrength: materialSpecularStrength,
  32449. materialThickness: materialThickness,
  32450. materialTransmission: materialTransmission,
  32451. max: max$1,
  32452. maxMipLevel: maxMipLevel,
  32453. mediumpModelViewMatrix: mediumpModelViewMatrix,
  32454. metalness: metalness,
  32455. min: min$1,
  32456. mix: mix,
  32457. mixElement: mixElement,
  32458. mod: mod,
  32459. modInt: modInt,
  32460. modelDirection: modelDirection,
  32461. modelNormalMatrix: modelNormalMatrix,
  32462. modelPosition: modelPosition,
  32463. modelRadius: modelRadius,
  32464. modelScale: modelScale,
  32465. modelViewMatrix: modelViewMatrix,
  32466. modelViewPosition: modelViewPosition,
  32467. modelViewProjection: modelViewProjection,
  32468. modelWorldMatrix: modelWorldMatrix,
  32469. modelWorldMatrixInverse: modelWorldMatrixInverse,
  32470. morphReference: morphReference,
  32471. mrt: mrt,
  32472. mul: mul,
  32473. mx_aastep: mx_aastep,
  32474. mx_add: mx_add,
  32475. mx_atan2: mx_atan2,
  32476. mx_cell_noise_float: mx_cell_noise_float,
  32477. mx_contrast: mx_contrast,
  32478. mx_divide: mx_divide,
  32479. mx_fractal_noise_float: mx_fractal_noise_float,
  32480. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  32481. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  32482. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  32483. mx_frame: mx_frame,
  32484. mx_heighttonormal: mx_heighttonormal,
  32485. mx_hsvtorgb: mx_hsvtorgb,
  32486. mx_ifequal: mx_ifequal,
  32487. mx_ifgreater: mx_ifgreater,
  32488. mx_ifgreatereq: mx_ifgreatereq,
  32489. mx_invert: mx_invert,
  32490. mx_modulo: mx_modulo,
  32491. mx_multiply: mx_multiply,
  32492. mx_noise_float: mx_noise_float,
  32493. mx_noise_vec3: mx_noise_vec3,
  32494. mx_noise_vec4: mx_noise_vec4,
  32495. mx_place2d: mx_place2d,
  32496. mx_power: mx_power,
  32497. mx_ramp4: mx_ramp4,
  32498. mx_ramplr: mx_ramplr,
  32499. mx_ramptb: mx_ramptb,
  32500. mx_rgbtohsv: mx_rgbtohsv,
  32501. mx_rotate2d: mx_rotate2d,
  32502. mx_rotate3d: mx_rotate3d,
  32503. mx_safepower: mx_safepower,
  32504. mx_separate: mx_separate,
  32505. mx_splitlr: mx_splitlr,
  32506. mx_splittb: mx_splittb,
  32507. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  32508. mx_subtract: mx_subtract,
  32509. mx_timer: mx_timer,
  32510. mx_transform_uv: mx_transform_uv,
  32511. mx_unifiednoise2d: mx_unifiednoise2d,
  32512. mx_unifiednoise3d: mx_unifiednoise3d,
  32513. mx_worley_noise_float: mx_worley_noise_float,
  32514. mx_worley_noise_vec2: mx_worley_noise_vec2,
  32515. mx_worley_noise_vec3: mx_worley_noise_vec3,
  32516. negate: negate,
  32517. neutralToneMapping: neutralToneMapping,
  32518. nodeArray: nodeArray,
  32519. nodeImmutable: nodeImmutable,
  32520. nodeObject: nodeObject,
  32521. nodeObjectIntent: nodeObjectIntent,
  32522. nodeObjects: nodeObjects,
  32523. nodeProxy: nodeProxy,
  32524. nodeProxyIntent: nodeProxyIntent,
  32525. normalFlat: normalFlat,
  32526. normalGeometry: normalGeometry,
  32527. normalLocal: normalLocal,
  32528. normalMap: normalMap,
  32529. normalView: normalView,
  32530. normalViewGeometry: normalViewGeometry,
  32531. normalWorld: normalWorld,
  32532. normalWorldGeometry: normalWorldGeometry,
  32533. normalize: normalize,
  32534. not: not,
  32535. notEqual: notEqual,
  32536. numWorkgroups: numWorkgroups,
  32537. objectDirection: objectDirection,
  32538. objectGroup: objectGroup,
  32539. objectPosition: objectPosition,
  32540. objectRadius: objectRadius,
  32541. objectScale: objectScale,
  32542. objectViewPosition: objectViewPosition,
  32543. objectWorldMatrix: objectWorldMatrix,
  32544. oneMinus: oneMinus,
  32545. or: or,
  32546. orthographicDepthToViewZ: orthographicDepthToViewZ,
  32547. oscSawtooth: oscSawtooth,
  32548. oscSine: oscSine,
  32549. oscSquare: oscSquare,
  32550. oscTriangle: oscTriangle,
  32551. output: output,
  32552. outputStruct: outputStruct,
  32553. overlay: overlay,
  32554. overloadingFn: overloadingFn,
  32555. parabola: parabola,
  32556. parallaxDirection: parallaxDirection,
  32557. parallaxUV: parallaxUV,
  32558. parameter: parameter,
  32559. pass: pass,
  32560. passTexture: passTexture,
  32561. pcurve: pcurve,
  32562. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  32563. pmremTexture: pmremTexture,
  32564. pointShadow: pointShadow,
  32565. pointUV: pointUV,
  32566. pointWidth: pointWidth,
  32567. positionGeometry: positionGeometry,
  32568. positionLocal: positionLocal,
  32569. positionPrevious: positionPrevious,
  32570. positionView: positionView,
  32571. positionViewDirection: positionViewDirection,
  32572. positionWorld: positionWorld,
  32573. positionWorldDirection: positionWorldDirection,
  32574. posterize: posterize,
  32575. pow: pow,
  32576. pow2: pow2,
  32577. pow3: pow3,
  32578. pow4: pow4,
  32579. premultiplyAlpha: premultiplyAlpha,
  32580. property: property,
  32581. quadBroadcast: quadBroadcast,
  32582. quadSwapDiagonal: quadSwapDiagonal,
  32583. quadSwapX: quadSwapX,
  32584. quadSwapY: quadSwapY,
  32585. radians: radians,
  32586. rand: rand,
  32587. range: range,
  32588. rangeFog: rangeFog,
  32589. rangeFogFactor: rangeFogFactor,
  32590. reciprocal: reciprocal,
  32591. reference: reference,
  32592. referenceBuffer: referenceBuffer,
  32593. reflect: reflect,
  32594. reflectVector: reflectVector,
  32595. reflectView: reflectView,
  32596. reflector: reflector,
  32597. refract: refract,
  32598. refractVector: refractVector,
  32599. refractView: refractView,
  32600. reinhardToneMapping: reinhardToneMapping,
  32601. remap: remap,
  32602. remapClamp: remapClamp,
  32603. renderGroup: renderGroup,
  32604. renderOutput: renderOutput,
  32605. rendererReference: rendererReference,
  32606. rotate: rotate,
  32607. rotateUV: rotateUV,
  32608. roughness: roughness,
  32609. round: round,
  32610. rtt: rtt,
  32611. sRGBTransferEOTF: sRGBTransferEOTF,
  32612. sRGBTransferOETF: sRGBTransferOETF,
  32613. sample: sample,
  32614. sampler: sampler,
  32615. samplerComparison: samplerComparison,
  32616. saturate: saturate,
  32617. saturation: saturation,
  32618. screen: screen,
  32619. screenCoordinate: screenCoordinate,
  32620. screenDPR: screenDPR,
  32621. screenSize: screenSize,
  32622. screenUV: screenUV,
  32623. scriptable: scriptable,
  32624. scriptableValue: scriptableValue,
  32625. select: select,
  32626. setCurrentStack: setCurrentStack,
  32627. setName: setName,
  32628. shaderStages: shaderStages,
  32629. shadow: shadow,
  32630. shadowPositionWorld: shadowPositionWorld,
  32631. shapeCircle: shapeCircle,
  32632. sharedUniformGroup: sharedUniformGroup,
  32633. sheen: sheen,
  32634. sheenRoughness: sheenRoughness,
  32635. shiftLeft: shiftLeft,
  32636. shiftRight: shiftRight,
  32637. shininess: shininess,
  32638. sign: sign,
  32639. sin: sin,
  32640. sinc: sinc,
  32641. skinning: skinning,
  32642. smoothstep: smoothstep,
  32643. smoothstepElement: smoothstepElement,
  32644. specularColor: specularColor,
  32645. specularF90: specularF90,
  32646. spherizeUV: spherizeUV,
  32647. split: split,
  32648. spritesheetUV: spritesheetUV,
  32649. sqrt: sqrt,
  32650. stack: stack,
  32651. step: step,
  32652. stepElement: stepElement,
  32653. storage: storage,
  32654. storageBarrier: storageBarrier,
  32655. storageObject: storageObject,
  32656. storageTexture: storageTexture,
  32657. string: string,
  32658. struct: struct,
  32659. sub: sub,
  32660. subBuild: subBuild,
  32661. subgroupAdd: subgroupAdd,
  32662. subgroupAll: subgroupAll,
  32663. subgroupAnd: subgroupAnd,
  32664. subgroupAny: subgroupAny,
  32665. subgroupBallot: subgroupBallot,
  32666. subgroupBroadcast: subgroupBroadcast,
  32667. subgroupBroadcastFirst: subgroupBroadcastFirst,
  32668. subgroupElect: subgroupElect,
  32669. subgroupExclusiveAdd: subgroupExclusiveAdd,
  32670. subgroupExclusiveMul: subgroupExclusiveMul,
  32671. subgroupInclusiveAdd: subgroupInclusiveAdd,
  32672. subgroupInclusiveMul: subgroupInclusiveMul,
  32673. subgroupIndex: subgroupIndex,
  32674. subgroupMax: subgroupMax,
  32675. subgroupMin: subgroupMin,
  32676. subgroupMul: subgroupMul,
  32677. subgroupOr: subgroupOr,
  32678. subgroupShuffle: subgroupShuffle,
  32679. subgroupShuffleDown: subgroupShuffleDown,
  32680. subgroupShuffleUp: subgroupShuffleUp,
  32681. subgroupShuffleXor: subgroupShuffleXor,
  32682. subgroupSize: subgroupSize,
  32683. subgroupXor: subgroupXor,
  32684. tan: tan,
  32685. tangentGeometry: tangentGeometry,
  32686. tangentLocal: tangentLocal,
  32687. tangentView: tangentView,
  32688. tangentWorld: tangentWorld,
  32689. texture: texture,
  32690. texture3D: texture3D,
  32691. textureBarrier: textureBarrier,
  32692. textureBicubic: textureBicubic,
  32693. textureBicubicLevel: textureBicubicLevel,
  32694. textureCubeUV: textureCubeUV,
  32695. textureLevel: textureLevel,
  32696. textureLoad: textureLoad,
  32697. textureSize: textureSize,
  32698. textureStore: textureStore,
  32699. thickness: thickness,
  32700. time: time,
  32701. toneMapping: toneMapping,
  32702. toneMappingExposure: toneMappingExposure,
  32703. toonOutlinePass: toonOutlinePass,
  32704. transformDirection: transformDirection,
  32705. transformNormal: transformNormal,
  32706. transformNormalToView: transformNormalToView,
  32707. transformedClearcoatNormalView: transformedClearcoatNormalView,
  32708. transformedNormalView: transformedNormalView,
  32709. transformedNormalWorld: transformedNormalWorld,
  32710. transmission: transmission,
  32711. transpose: transpose,
  32712. triNoise3D: triNoise3D,
  32713. triplanarTexture: triplanarTexture,
  32714. triplanarTextures: triplanarTextures,
  32715. trunc: trunc,
  32716. uint: uint,
  32717. uintBitsToFloat: uintBitsToFloat,
  32718. uniform: uniform,
  32719. uniformArray: uniformArray,
  32720. uniformCubeTexture: uniformCubeTexture,
  32721. uniformFlow: uniformFlow,
  32722. uniformGroup: uniformGroup,
  32723. uniformTexture: uniformTexture,
  32724. unpremultiplyAlpha: unpremultiplyAlpha,
  32725. userData: userData,
  32726. uv: uv$1,
  32727. uvec2: uvec2,
  32728. uvec3: uvec3,
  32729. uvec4: uvec4,
  32730. varying: varying,
  32731. varyingProperty: varyingProperty,
  32732. vec2: vec2,
  32733. vec3: vec3,
  32734. vec4: vec4,
  32735. vectorComponents: vectorComponents,
  32736. velocity: velocity,
  32737. vertexColor: vertexColor,
  32738. vertexIndex: vertexIndex,
  32739. vertexStage: vertexStage,
  32740. vibrance: vibrance,
  32741. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  32742. viewZToOrthographicDepth: viewZToOrthographicDepth,
  32743. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  32744. viewport: viewport,
  32745. viewportCoordinate: viewportCoordinate,
  32746. viewportDepthTexture: viewportDepthTexture,
  32747. viewportLinearDepth: viewportLinearDepth,
  32748. viewportMipTexture: viewportMipTexture,
  32749. viewportResolution: viewportResolution,
  32750. viewportSafeUV: viewportSafeUV,
  32751. viewportSharedTexture: viewportSharedTexture,
  32752. viewportSize: viewportSize,
  32753. viewportTexture: viewportTexture,
  32754. viewportUV: viewportUV,
  32755. wgsl: wgsl,
  32756. wgslFn: wgslFn,
  32757. workgroupArray: workgroupArray,
  32758. workgroupBarrier: workgroupBarrier,
  32759. workgroupId: workgroupId,
  32760. workingToColorSpace: workingToColorSpace,
  32761. xor: xor
  32762. });
  32763. const _clearColor = /*@__PURE__*/ new Color4();
  32764. /**
  32765. * This renderer module manages the background.
  32766. *
  32767. * @private
  32768. * @augments DataMap
  32769. */
  32770. class Background extends DataMap {
  32771. /**
  32772. * Constructs a new background management component.
  32773. *
  32774. * @param {Renderer} renderer - The renderer.
  32775. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  32776. */
  32777. constructor( renderer, nodes ) {
  32778. super();
  32779. /**
  32780. * The renderer.
  32781. *
  32782. * @type {Renderer}
  32783. */
  32784. this.renderer = renderer;
  32785. /**
  32786. * Renderer component for managing nodes related logic.
  32787. *
  32788. * @type {Nodes}
  32789. */
  32790. this.nodes = nodes;
  32791. }
  32792. /**
  32793. * Updates the background for the given scene. Depending on how `Scene.background`
  32794. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  32795. * or add a mesh to the render list for rendering the background as a textured plane
  32796. * or skybox.
  32797. *
  32798. * @param {Scene} scene - The scene.
  32799. * @param {RenderList} renderList - The current render list.
  32800. * @param {RenderContext} renderContext - The current render context.
  32801. */
  32802. update( scene, renderList, renderContext ) {
  32803. const renderer = this.renderer;
  32804. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  32805. let forceClear = false;
  32806. if ( background === null ) {
  32807. // no background settings, use clear color configuration from the renderer
  32808. renderer._clearColor.getRGB( _clearColor );
  32809. _clearColor.a = renderer._clearColor.a;
  32810. } else if ( background.isColor === true ) {
  32811. // background is an opaque color
  32812. background.getRGB( _clearColor );
  32813. _clearColor.a = 1;
  32814. forceClear = true;
  32815. } else if ( background.isNode === true ) {
  32816. const sceneData = this.get( scene );
  32817. const backgroundNode = background;
  32818. _clearColor.copy( renderer._clearColor );
  32819. let backgroundMesh = sceneData.backgroundMesh;
  32820. if ( backgroundMesh === undefined ) {
  32821. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  32822. // @TODO: Add Texture2D support using node context
  32823. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  32824. getTextureLevel: () => backgroundBlurriness
  32825. } );
  32826. let viewProj = modelViewProjection;
  32827. viewProj = viewProj.setZ( viewProj.w );
  32828. const nodeMaterial = new NodeMaterial();
  32829. nodeMaterial.name = 'Background.material';
  32830. nodeMaterial.side = BackSide;
  32831. nodeMaterial.depthTest = false;
  32832. nodeMaterial.depthWrite = false;
  32833. nodeMaterial.allowOverride = false;
  32834. nodeMaterial.fog = false;
  32835. nodeMaterial.lights = false;
  32836. nodeMaterial.vertexNode = viewProj;
  32837. nodeMaterial.colorNode = backgroundMeshNode;
  32838. sceneData.backgroundMeshNode = backgroundMeshNode;
  32839. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  32840. backgroundMesh.frustumCulled = false;
  32841. backgroundMesh.name = 'Background.mesh';
  32842. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  32843. this.matrixWorld.copyPosition( camera.matrixWorld );
  32844. };
  32845. function onBackgroundDispose() {
  32846. background.removeEventListener( 'dispose', onBackgroundDispose );
  32847. backgroundMesh.material.dispose();
  32848. backgroundMesh.geometry.dispose();
  32849. }
  32850. background.addEventListener( 'dispose', onBackgroundDispose );
  32851. }
  32852. const backgroundCacheKey = backgroundNode.getCacheKey();
  32853. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  32854. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  32855. sceneData.backgroundMeshNode.needsUpdate = true;
  32856. backgroundMesh.material.needsUpdate = true;
  32857. sceneData.backgroundCacheKey = backgroundCacheKey;
  32858. }
  32859. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  32860. } else {
  32861. error( 'Renderer: Unsupported background configuration.', background );
  32862. }
  32863. //
  32864. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  32865. if ( environmentBlendMode === 'additive' ) {
  32866. _clearColor.set( 0, 0, 0, 1 );
  32867. } else if ( environmentBlendMode === 'alpha-blend' ) {
  32868. _clearColor.set( 0, 0, 0, 0 );
  32869. }
  32870. //
  32871. if ( renderer.autoClear === true || forceClear === true ) {
  32872. const clearColorValue = renderContext.clearColorValue;
  32873. clearColorValue.r = _clearColor.r;
  32874. clearColorValue.g = _clearColor.g;
  32875. clearColorValue.b = _clearColor.b;
  32876. clearColorValue.a = _clearColor.a;
  32877. // premultiply alpha
  32878. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  32879. clearColorValue.r *= clearColorValue.a;
  32880. clearColorValue.g *= clearColorValue.a;
  32881. clearColorValue.b *= clearColorValue.a;
  32882. }
  32883. //
  32884. renderContext.depthClearValue = renderer._clearDepth;
  32885. renderContext.stencilClearValue = renderer._clearStencil;
  32886. renderContext.clearColor = renderer.autoClearColor === true;
  32887. renderContext.clearDepth = renderer.autoClearDepth === true;
  32888. renderContext.clearStencil = renderer.autoClearStencil === true;
  32889. } else {
  32890. renderContext.clearColor = false;
  32891. renderContext.clearDepth = false;
  32892. renderContext.clearStencil = false;
  32893. }
  32894. }
  32895. }
  32896. let _id$6 = 0;
  32897. /**
  32898. * A bind group represents a collection of bindings and thus a collection
  32899. * or resources. Bind groups are assigned to pipelines to provide them
  32900. * with the required resources (like uniform buffers or textures).
  32901. *
  32902. * @private
  32903. */
  32904. class BindGroup {
  32905. /**
  32906. * Constructs a new bind group.
  32907. *
  32908. * @param {string} name - The bind group's name.
  32909. * @param {Array<Binding>} bindings - An array of bindings.
  32910. * @param {number} index - The group index.
  32911. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  32912. */
  32913. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  32914. /**
  32915. * The bind group's name.
  32916. *
  32917. * @type {string}
  32918. */
  32919. this.name = name;
  32920. /**
  32921. * An array of bindings.
  32922. *
  32923. * @type {Array<Binding>}
  32924. */
  32925. this.bindings = bindings;
  32926. /**
  32927. * The group index.
  32928. *
  32929. * @type {number}
  32930. */
  32931. this.index = index;
  32932. /**
  32933. * An array of reference bindings.
  32934. *
  32935. * @type {Array<Binding>}
  32936. */
  32937. this.bindingsReference = bindingsReference;
  32938. /**
  32939. * The group's ID.
  32940. *
  32941. * @type {number}
  32942. */
  32943. this.id = _id$6 ++;
  32944. }
  32945. }
  32946. /**
  32947. * This module represents the state of a node builder after it was
  32948. * used to build the nodes for a render object. The state holds the
  32949. * results of the build for further processing in the renderer.
  32950. *
  32951. * Render objects with identical cache keys share the same node builder state.
  32952. *
  32953. * @private
  32954. */
  32955. class NodeBuilderState {
  32956. /**
  32957. * Constructs a new node builder state.
  32958. *
  32959. * @param {string} vertexShader - The native vertex shader code.
  32960. * @param {string} fragmentShader - The native fragment shader code.
  32961. * @param {string} computeShader - The native compute shader code.
  32962. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  32963. * @param {Array<BindGroup>} bindings - An array of bind groups.
  32964. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  32965. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  32966. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  32967. * @param {NodeMaterialObserver} observer - A node material observer.
  32968. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  32969. */
  32970. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  32971. /**
  32972. * The native vertex shader code.
  32973. *
  32974. * @type {string}
  32975. */
  32976. this.vertexShader = vertexShader;
  32977. /**
  32978. * The native fragment shader code.
  32979. *
  32980. * @type {string}
  32981. */
  32982. this.fragmentShader = fragmentShader;
  32983. /**
  32984. * The native compute shader code.
  32985. *
  32986. * @type {string}
  32987. */
  32988. this.computeShader = computeShader;
  32989. /**
  32990. * An array with transform attribute objects.
  32991. * Only relevant when using compute shaders with WebGL 2.
  32992. *
  32993. * @type {Array<Object>}
  32994. */
  32995. this.transforms = transforms;
  32996. /**
  32997. * An array of node attributes representing
  32998. * the attributes of the shaders.
  32999. *
  33000. * @type {Array<NodeAttribute>}
  33001. */
  33002. this.nodeAttributes = nodeAttributes;
  33003. /**
  33004. * An array of bind groups representing the uniform or storage
  33005. * buffers, texture or samplers of the shader.
  33006. *
  33007. * @type {Array<BindGroup>}
  33008. */
  33009. this.bindings = bindings;
  33010. /**
  33011. * An array of nodes that implement their `update()` method.
  33012. *
  33013. * @type {Array<Node>}
  33014. */
  33015. this.updateNodes = updateNodes;
  33016. /**
  33017. * An array of nodes that implement their `updateBefore()` method.
  33018. *
  33019. * @type {Array<Node>}
  33020. */
  33021. this.updateBeforeNodes = updateBeforeNodes;
  33022. /**
  33023. * An array of nodes that implement their `updateAfter()` method.
  33024. *
  33025. * @type {Array<Node>}
  33026. */
  33027. this.updateAfterNodes = updateAfterNodes;
  33028. /**
  33029. * A node material observer.
  33030. *
  33031. * @type {NodeMaterialObserver}
  33032. */
  33033. this.observer = observer;
  33034. /**
  33035. * How often this state is used by render objects.
  33036. *
  33037. * @type {number}
  33038. */
  33039. this.usedTimes = 0;
  33040. }
  33041. /**
  33042. * This method is used to create a array of bind groups based
  33043. * on the existing bind groups of this state. Shared groups are
  33044. * not cloned.
  33045. *
  33046. * @return {Array<BindGroup>} A array of bind groups.
  33047. */
  33048. createBindings() {
  33049. const bindings = [];
  33050. for ( const instanceGroup of this.bindings ) {
  33051. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  33052. if ( shared !== true ) {
  33053. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup.bindingsReference );
  33054. bindings.push( bindingsGroup );
  33055. for ( const instanceBinding of instanceGroup.bindings ) {
  33056. bindingsGroup.bindings.push( instanceBinding.clone() );
  33057. }
  33058. } else {
  33059. bindings.push( instanceGroup );
  33060. }
  33061. }
  33062. return bindings;
  33063. }
  33064. }
  33065. /**
  33066. * {@link NodeBuilder} is going to create instances of this class during the build process
  33067. * of nodes. They represent the final shader attributes that are going to be generated
  33068. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  33069. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  33070. */
  33071. class NodeAttribute {
  33072. /**
  33073. * Constructs a new node attribute.
  33074. *
  33075. * @param {string} name - The name of the attribute.
  33076. * @param {string} type - The type of the attribute.
  33077. * @param {?Node} node - An optional reference to the node.
  33078. */
  33079. constructor( name, type, node = null ) {
  33080. /**
  33081. * This flag can be used for type testing.
  33082. *
  33083. * @type {boolean}
  33084. * @readonly
  33085. * @default true
  33086. */
  33087. this.isNodeAttribute = true;
  33088. /**
  33089. * The name of the attribute.
  33090. *
  33091. * @type {string}
  33092. */
  33093. this.name = name;
  33094. /**
  33095. * The type of the attribute.
  33096. *
  33097. * @type {string}
  33098. */
  33099. this.type = type;
  33100. /**
  33101. * An optional reference to the node.
  33102. *
  33103. * @type {?Node}
  33104. * @default null
  33105. */
  33106. this.node = node;
  33107. }
  33108. }
  33109. /**
  33110. * {@link NodeBuilder} is going to create instances of this class during the build process
  33111. * of nodes. They represent the final shader uniforms that are going to be generated
  33112. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  33113. * for this purpose.
  33114. */
  33115. class NodeUniform {
  33116. /**
  33117. * Constructs a new node uniform.
  33118. *
  33119. * @param {string} name - The name of the uniform.
  33120. * @param {string} type - The type of the uniform.
  33121. * @param {UniformNode} node - An reference to the node.
  33122. */
  33123. constructor( name, type, node ) {
  33124. /**
  33125. * This flag can be used for type testing.
  33126. *
  33127. * @type {boolean}
  33128. * @readonly
  33129. * @default true
  33130. */
  33131. this.isNodeUniform = true;
  33132. /**
  33133. * The name of the uniform.
  33134. *
  33135. * @type {string}
  33136. */
  33137. this.name = name;
  33138. /**
  33139. * The type of the uniform.
  33140. *
  33141. * @type {string}
  33142. */
  33143. this.type = type;
  33144. /**
  33145. * An reference to the node.
  33146. *
  33147. * @type {UniformNode}
  33148. */
  33149. this.node = node;
  33150. }
  33151. /**
  33152. * The value of the uniform node.
  33153. *
  33154. * @type {any}
  33155. */
  33156. get value() {
  33157. return this.node.value;
  33158. }
  33159. set value( val ) {
  33160. this.node.value = val;
  33161. }
  33162. /**
  33163. * The id of the uniform node.
  33164. *
  33165. * @type {number}
  33166. */
  33167. get id() {
  33168. return this.node.id;
  33169. }
  33170. /**
  33171. * The uniform node's group.
  33172. *
  33173. * @type {UniformGroupNode}
  33174. */
  33175. get groupNode() {
  33176. return this.node.groupNode;
  33177. }
  33178. }
  33179. /**
  33180. * {@link NodeBuilder} is going to create instances of this class during the build process
  33181. * of nodes. They represent the final shader variables that are going to be generated
  33182. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  33183. * this purpose.
  33184. */
  33185. class NodeVar {
  33186. /**
  33187. * Constructs a new node variable.
  33188. *
  33189. * @param {string} name - The name of the variable.
  33190. * @param {string} type - The type of the variable.
  33191. * @param {boolean} [readOnly=false] - The read-only flag.
  33192. * @param {?number} [count=null] - The size.
  33193. */
  33194. constructor( name, type, readOnly = false, count = null ) {
  33195. /**
  33196. * This flag can be used for type testing.
  33197. *
  33198. * @type {boolean}
  33199. * @readonly
  33200. * @default true
  33201. */
  33202. this.isNodeVar = true;
  33203. /**
  33204. * The name of the variable.
  33205. *
  33206. * @type {string}
  33207. */
  33208. this.name = name;
  33209. /**
  33210. * The type of the variable.
  33211. *
  33212. * @type {string}
  33213. */
  33214. this.type = type;
  33215. /**
  33216. * The read-only flag.
  33217. *
  33218. * @type {boolean}
  33219. */
  33220. this.readOnly = readOnly;
  33221. /**
  33222. * The size.
  33223. *
  33224. * @type {?number}
  33225. */
  33226. this.count = count;
  33227. }
  33228. }
  33229. /**
  33230. * {@link NodeBuilder} is going to create instances of this class during the build process
  33231. * of nodes. They represent the final shader varyings that are going to be generated
  33232. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  33233. * this purpose.
  33234. *
  33235. * @augments NodeVar
  33236. */
  33237. class NodeVarying extends NodeVar {
  33238. /**
  33239. * Constructs a new node varying.
  33240. *
  33241. * @param {string} name - The name of the varying.
  33242. * @param {string} type - The type of the varying.
  33243. * @param {?string} interpolationType - The interpolation type of the varying.
  33244. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  33245. */
  33246. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  33247. super( name, type );
  33248. /**
  33249. * Whether this varying requires interpolation or not. This property can be used
  33250. * to check if the varying can be optimized for a variable.
  33251. *
  33252. * @type {boolean}
  33253. * @default false
  33254. */
  33255. this.needsInterpolation = false;
  33256. /**
  33257. * This flag can be used for type testing.
  33258. *
  33259. * @type {boolean}
  33260. * @readonly
  33261. * @default true
  33262. */
  33263. this.isNodeVarying = true;
  33264. /**
  33265. * The interpolation type of the varying data.
  33266. *
  33267. * @type {?string}
  33268. * @default null
  33269. */
  33270. this.interpolationType = interpolationType;
  33271. /**
  33272. * The interpolation sampling type of varying data.
  33273. *
  33274. * @type {?string}
  33275. * @default null
  33276. */
  33277. this.interpolationSampling = interpolationSampling;
  33278. }
  33279. }
  33280. /**
  33281. * {@link NodeBuilder} is going to create instances of this class during the build process
  33282. * of nodes. They represent user-defined, native shader code portions that are going to be
  33283. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  33284. * for this purpose.
  33285. */
  33286. class NodeCode {
  33287. /**
  33288. * Constructs a new code node.
  33289. *
  33290. * @param {string} name - The name of the code.
  33291. * @param {string} type - The node type.
  33292. * @param {string} [code=''] - The native shader code.
  33293. */
  33294. constructor( name, type, code = '' ) {
  33295. /**
  33296. * The name of the code.
  33297. *
  33298. * @type {string}
  33299. */
  33300. this.name = name;
  33301. /**
  33302. * The node type.
  33303. *
  33304. * @type {string}
  33305. */
  33306. this.type = type;
  33307. /**
  33308. * The native shader code.
  33309. *
  33310. * @type {string}
  33311. * @default ''
  33312. */
  33313. this.code = code;
  33314. Object.defineProperty( this, 'isNodeCode', { value: true } );
  33315. }
  33316. }
  33317. let _id$5 = 0;
  33318. /**
  33319. * This utility class is used in {@link NodeBuilder} as an internal
  33320. * cache data structure for node data.
  33321. */
  33322. class NodeCache {
  33323. /**
  33324. * Constructs a new node cache.
  33325. *
  33326. * @param {?NodeCache} parent - A reference to a parent cache.
  33327. */
  33328. constructor( parent = null ) {
  33329. /**
  33330. * The id of the cache.
  33331. *
  33332. * @type {number}
  33333. * @readonly
  33334. */
  33335. this.id = _id$5 ++;
  33336. /**
  33337. * A weak map for managing node data.
  33338. *
  33339. * @type {WeakMap<Node, Object>}
  33340. */
  33341. this.nodesData = new WeakMap();
  33342. /**
  33343. * Reference to a parent node cache.
  33344. *
  33345. * @type {?NodeCache}
  33346. * @default null
  33347. */
  33348. this.parent = parent;
  33349. }
  33350. /**
  33351. * Returns the data for the given node.
  33352. *
  33353. * @param {Node} node - The node.
  33354. * @return {?Object} The data for the node.
  33355. */
  33356. getData( node ) {
  33357. let data = this.nodesData.get( node );
  33358. if ( data === undefined && this.parent !== null ) {
  33359. data = this.parent.getData( node );
  33360. }
  33361. return data;
  33362. }
  33363. /**
  33364. * Sets the data for a given node.
  33365. *
  33366. * @param {Node} node - The node.
  33367. * @param {Object} data - The data that should be cached.
  33368. */
  33369. setData( node, data ) {
  33370. this.nodesData.set( node, data );
  33371. }
  33372. }
  33373. class StructType {
  33374. constructor( name, members ) {
  33375. this.name = name;
  33376. this.members = members;
  33377. this.output = false;
  33378. }
  33379. }
  33380. /**
  33381. * Abstract base class for uniforms.
  33382. *
  33383. * @abstract
  33384. * @private
  33385. */
  33386. class Uniform {
  33387. /**
  33388. * Constructs a new uniform.
  33389. *
  33390. * @param {string} name - The uniform's name.
  33391. * @param {any} value - The uniform's value.
  33392. */
  33393. constructor( name, value ) {
  33394. /**
  33395. * The uniform's name.
  33396. *
  33397. * @type {string}
  33398. */
  33399. this.name = name;
  33400. /**
  33401. * The uniform's value.
  33402. *
  33403. * @type {any}
  33404. */
  33405. this.value = value;
  33406. /**
  33407. * Used to build the uniform buffer according to the STD140 layout.
  33408. * Derived uniforms will set this property to a data type specific
  33409. * value.
  33410. *
  33411. * @type {number}
  33412. */
  33413. this.boundary = 0;
  33414. /**
  33415. * The item size. Derived uniforms will set this property to a data
  33416. * type specific value.
  33417. *
  33418. * @type {number}
  33419. */
  33420. this.itemSize = 0;
  33421. /**
  33422. * This property is set by {@link UniformsGroup} and marks
  33423. * the start position in the uniform buffer.
  33424. *
  33425. * @type {number}
  33426. */
  33427. this.offset = 0;
  33428. }
  33429. /**
  33430. * Sets the uniform's value.
  33431. *
  33432. * @param {any} value - The value to set.
  33433. */
  33434. setValue( value ) {
  33435. this.value = value;
  33436. }
  33437. /**
  33438. * Returns the uniform's value.
  33439. *
  33440. * @return {any} The value.
  33441. */
  33442. getValue() {
  33443. return this.value;
  33444. }
  33445. }
  33446. /**
  33447. * Represents a Number uniform.
  33448. *
  33449. * @private
  33450. * @augments Uniform
  33451. */
  33452. class NumberUniform extends Uniform {
  33453. /**
  33454. * Constructs a new Number uniform.
  33455. *
  33456. * @param {string} name - The uniform's name.
  33457. * @param {number} value - The uniform's value.
  33458. */
  33459. constructor( name, value = 0 ) {
  33460. super( name, value );
  33461. /**
  33462. * This flag can be used for type testing.
  33463. *
  33464. * @type {boolean}
  33465. * @readonly
  33466. * @default true
  33467. */
  33468. this.isNumberUniform = true;
  33469. this.boundary = 4;
  33470. this.itemSize = 1;
  33471. }
  33472. }
  33473. /**
  33474. * Represents a Vector2 uniform.
  33475. *
  33476. * @private
  33477. * @augments Uniform
  33478. */
  33479. class Vector2Uniform extends Uniform {
  33480. /**
  33481. * Constructs a new Number uniform.
  33482. *
  33483. * @param {string} name - The uniform's name.
  33484. * @param {Vector2} value - The uniform's value.
  33485. */
  33486. constructor( name, value = new Vector2() ) {
  33487. super( name, value );
  33488. /**
  33489. * This flag can be used for type testing.
  33490. *
  33491. * @type {boolean}
  33492. * @readonly
  33493. * @default true
  33494. */
  33495. this.isVector2Uniform = true;
  33496. this.boundary = 8;
  33497. this.itemSize = 2;
  33498. }
  33499. }
  33500. /**
  33501. * Represents a Vector3 uniform.
  33502. *
  33503. * @private
  33504. * @augments Uniform
  33505. */
  33506. class Vector3Uniform extends Uniform {
  33507. /**
  33508. * Constructs a new Number uniform.
  33509. *
  33510. * @param {string} name - The uniform's name.
  33511. * @param {Vector3} value - The uniform's value.
  33512. */
  33513. constructor( name, value = new Vector3() ) {
  33514. super( name, value );
  33515. /**
  33516. * This flag can be used for type testing.
  33517. *
  33518. * @type {boolean}
  33519. * @readonly
  33520. * @default true
  33521. */
  33522. this.isVector3Uniform = true;
  33523. this.boundary = 16;
  33524. this.itemSize = 3;
  33525. }
  33526. }
  33527. /**
  33528. * Represents a Vector4 uniform.
  33529. *
  33530. * @private
  33531. * @augments Uniform
  33532. */
  33533. class Vector4Uniform extends Uniform {
  33534. /**
  33535. * Constructs a new Number uniform.
  33536. *
  33537. * @param {string} name - The uniform's name.
  33538. * @param {Vector4} value - The uniform's value.
  33539. */
  33540. constructor( name, value = new Vector4() ) {
  33541. super( name, value );
  33542. /**
  33543. * This flag can be used for type testing.
  33544. *
  33545. * @type {boolean}
  33546. * @readonly
  33547. * @default true
  33548. */
  33549. this.isVector4Uniform = true;
  33550. this.boundary = 16;
  33551. this.itemSize = 4;
  33552. }
  33553. }
  33554. /**
  33555. * Represents a Color uniform.
  33556. *
  33557. * @private
  33558. * @augments Uniform
  33559. */
  33560. class ColorUniform extends Uniform {
  33561. /**
  33562. * Constructs a new Number uniform.
  33563. *
  33564. * @param {string} name - The uniform's name.
  33565. * @param {Color} value - The uniform's value.
  33566. */
  33567. constructor( name, value = new Color() ) {
  33568. super( name, value );
  33569. /**
  33570. * This flag can be used for type testing.
  33571. *
  33572. * @type {boolean}
  33573. * @readonly
  33574. * @default true
  33575. */
  33576. this.isColorUniform = true;
  33577. this.boundary = 16;
  33578. this.itemSize = 3;
  33579. }
  33580. }
  33581. /**
  33582. * Represents a Matrix2 uniform.
  33583. *
  33584. * @private
  33585. * @augments Uniform
  33586. */
  33587. class Matrix2Uniform extends Uniform {
  33588. /**
  33589. * Constructs a new Number uniform.
  33590. *
  33591. * @param {string} name - The uniform's name.
  33592. * @param {Matrix2} value - The uniform's value.
  33593. */
  33594. constructor( name, value = new Matrix2() ) {
  33595. super( name, value );
  33596. /**
  33597. * This flag can be used for type testing.
  33598. *
  33599. * @type {boolean}
  33600. * @readonly
  33601. * @default true
  33602. */
  33603. this.isMatrix2Uniform = true;
  33604. this.boundary = 8;
  33605. this.itemSize = 4;
  33606. }
  33607. }
  33608. /**
  33609. * Represents a Matrix3 uniform.
  33610. *
  33611. * @private
  33612. * @augments Uniform
  33613. */
  33614. class Matrix3Uniform extends Uniform {
  33615. /**
  33616. * Constructs a new Number uniform.
  33617. *
  33618. * @param {string} name - The uniform's name.
  33619. * @param {Matrix3} value - The uniform's value.
  33620. */
  33621. constructor( name, value = new Matrix3() ) {
  33622. super( name, value );
  33623. /**
  33624. * This flag can be used for type testing.
  33625. *
  33626. * @type {boolean}
  33627. * @readonly
  33628. * @default true
  33629. */
  33630. this.isMatrix3Uniform = true;
  33631. this.boundary = 48;
  33632. this.itemSize = 12;
  33633. }
  33634. }
  33635. /**
  33636. * Represents a Matrix4 uniform.
  33637. *
  33638. * @private
  33639. * @augments Uniform
  33640. */
  33641. class Matrix4Uniform extends Uniform {
  33642. /**
  33643. * Constructs a new Number uniform.
  33644. *
  33645. * @param {string} name - The uniform's name.
  33646. * @param {Matrix4} value - The uniform's value.
  33647. */
  33648. constructor( name, value = new Matrix4() ) {
  33649. super( name, value );
  33650. /**
  33651. * This flag can be used for type testing.
  33652. *
  33653. * @type {boolean}
  33654. * @readonly
  33655. * @default true
  33656. */
  33657. this.isMatrix4Uniform = true;
  33658. this.boundary = 64;
  33659. this.itemSize = 16;
  33660. }
  33661. }
  33662. /**
  33663. * A special form of Number uniform binding type.
  33664. * It's value is managed by a node object.
  33665. *
  33666. * @private
  33667. * @augments NumberUniform
  33668. */
  33669. class NumberNodeUniform extends NumberUniform {
  33670. /**
  33671. * Constructs a new node-based Number uniform.
  33672. *
  33673. * @param {NodeUniform} nodeUniform - The node uniform.
  33674. */
  33675. constructor( nodeUniform ) {
  33676. super( nodeUniform.name, nodeUniform.value );
  33677. /**
  33678. * The node uniform.
  33679. *
  33680. * @type {NodeUniform}
  33681. */
  33682. this.nodeUniform = nodeUniform;
  33683. }
  33684. /**
  33685. * Overwritten to return the value of the node uniform.
  33686. *
  33687. * @return {number} The value.
  33688. */
  33689. getValue() {
  33690. return this.nodeUniform.value;
  33691. }
  33692. /**
  33693. * Returns the node uniform data type.
  33694. *
  33695. * @return {string} The data type.
  33696. */
  33697. getType() {
  33698. return this.nodeUniform.type;
  33699. }
  33700. }
  33701. /**
  33702. * A special form of Vector2 uniform binding type.
  33703. * It's value is managed by a node object.
  33704. *
  33705. * @private
  33706. * @augments Vector2Uniform
  33707. */
  33708. class Vector2NodeUniform extends Vector2Uniform {
  33709. /**
  33710. * Constructs a new node-based Vector2 uniform.
  33711. *
  33712. * @param {NodeUniform} nodeUniform - The node uniform.
  33713. */
  33714. constructor( nodeUniform ) {
  33715. super( nodeUniform.name, nodeUniform.value );
  33716. /**
  33717. * The node uniform.
  33718. *
  33719. * @type {NodeUniform}
  33720. */
  33721. this.nodeUniform = nodeUniform;
  33722. }
  33723. /**
  33724. * Overwritten to return the value of the node uniform.
  33725. *
  33726. * @return {Vector2} The value.
  33727. */
  33728. getValue() {
  33729. return this.nodeUniform.value;
  33730. }
  33731. /**
  33732. * Returns the node uniform data type.
  33733. *
  33734. * @return {string} The data type.
  33735. */
  33736. getType() {
  33737. return this.nodeUniform.type;
  33738. }
  33739. }
  33740. /**
  33741. * A special form of Vector3 uniform binding type.
  33742. * It's value is managed by a node object.
  33743. *
  33744. * @private
  33745. * @augments Vector3Uniform
  33746. */
  33747. class Vector3NodeUniform extends Vector3Uniform {
  33748. /**
  33749. * Constructs a new node-based Vector3 uniform.
  33750. *
  33751. * @param {NodeUniform} nodeUniform - The node uniform.
  33752. */
  33753. constructor( nodeUniform ) {
  33754. super( nodeUniform.name, nodeUniform.value );
  33755. /**
  33756. * The node uniform.
  33757. *
  33758. * @type {NodeUniform}
  33759. */
  33760. this.nodeUniform = nodeUniform;
  33761. }
  33762. /**
  33763. * Overwritten to return the value of the node uniform.
  33764. *
  33765. * @return {Vector3} The value.
  33766. */
  33767. getValue() {
  33768. return this.nodeUniform.value;
  33769. }
  33770. /**
  33771. * Returns the node uniform data type.
  33772. *
  33773. * @return {string} The data type.
  33774. */
  33775. getType() {
  33776. return this.nodeUniform.type;
  33777. }
  33778. }
  33779. /**
  33780. * A special form of Vector4 uniform binding type.
  33781. * It's value is managed by a node object.
  33782. *
  33783. * @private
  33784. * @augments Vector4Uniform
  33785. */
  33786. class Vector4NodeUniform extends Vector4Uniform {
  33787. /**
  33788. * Constructs a new node-based Vector4 uniform.
  33789. *
  33790. * @param {NodeUniform} nodeUniform - The node uniform.
  33791. */
  33792. constructor( nodeUniform ) {
  33793. super( nodeUniform.name, nodeUniform.value );
  33794. /**
  33795. * The node uniform.
  33796. *
  33797. * @type {NodeUniform}
  33798. */
  33799. this.nodeUniform = nodeUniform;
  33800. }
  33801. /**
  33802. * Overwritten to return the value of the node uniform.
  33803. *
  33804. * @return {Vector4} The value.
  33805. */
  33806. getValue() {
  33807. return this.nodeUniform.value;
  33808. }
  33809. /**
  33810. * Returns the node uniform data type.
  33811. *
  33812. * @return {string} The data type.
  33813. */
  33814. getType() {
  33815. return this.nodeUniform.type;
  33816. }
  33817. }
  33818. /**
  33819. * A special form of Color uniform binding type.
  33820. * It's value is managed by a node object.
  33821. *
  33822. * @private
  33823. * @augments ColorUniform
  33824. */
  33825. class ColorNodeUniform extends ColorUniform {
  33826. /**
  33827. * Constructs a new node-based Color uniform.
  33828. *
  33829. * @param {NodeUniform} nodeUniform - The node uniform.
  33830. */
  33831. constructor( nodeUniform ) {
  33832. super( nodeUniform.name, nodeUniform.value );
  33833. /**
  33834. * The node uniform.
  33835. *
  33836. * @type {NodeUniform}
  33837. */
  33838. this.nodeUniform = nodeUniform;
  33839. }
  33840. /**
  33841. * Overwritten to return the value of the node uniform.
  33842. *
  33843. * @return {Color} The value.
  33844. */
  33845. getValue() {
  33846. return this.nodeUniform.value;
  33847. }
  33848. /**
  33849. * Returns the node uniform data type.
  33850. *
  33851. * @return {string} The data type.
  33852. */
  33853. getType() {
  33854. return this.nodeUniform.type;
  33855. }
  33856. }
  33857. /**
  33858. * A special form of Matrix2 uniform binding type.
  33859. * It's value is managed by a node object.
  33860. *
  33861. * @private
  33862. * @augments Matrix2Uniform
  33863. */
  33864. class Matrix2NodeUniform extends Matrix2Uniform {
  33865. /**
  33866. * Constructs a new node-based Matrix2 uniform.
  33867. *
  33868. * @param {NodeUniform} nodeUniform - The node uniform.
  33869. */
  33870. constructor( nodeUniform ) {
  33871. super( nodeUniform.name, nodeUniform.value );
  33872. /**
  33873. * The node uniform.
  33874. *
  33875. * @type {NodeUniform}
  33876. */
  33877. this.nodeUniform = nodeUniform;
  33878. }
  33879. /**
  33880. * Overwritten to return the value of the node uniform.
  33881. *
  33882. * @return {Matrix2} The value.
  33883. */
  33884. getValue() {
  33885. return this.nodeUniform.value;
  33886. }
  33887. /**
  33888. * Returns the node uniform data type.
  33889. *
  33890. * @return {string} The data type.
  33891. */
  33892. getType() {
  33893. return this.nodeUniform.type;
  33894. }
  33895. }
  33896. /**
  33897. * A special form of Matrix3 uniform binding type.
  33898. * It's value is managed by a node object.
  33899. *
  33900. * @private
  33901. * @augments Matrix3Uniform
  33902. */
  33903. class Matrix3NodeUniform extends Matrix3Uniform {
  33904. /**
  33905. * Constructs a new node-based Matrix3 uniform.
  33906. *
  33907. * @param {NodeUniform} nodeUniform - The node uniform.
  33908. */
  33909. constructor( nodeUniform ) {
  33910. super( nodeUniform.name, nodeUniform.value );
  33911. /**
  33912. * The node uniform.
  33913. *
  33914. * @type {NodeUniform}
  33915. */
  33916. this.nodeUniform = nodeUniform;
  33917. }
  33918. /**
  33919. * Overwritten to return the value of the node uniform.
  33920. *
  33921. * @return {Matrix3} The value.
  33922. */
  33923. getValue() {
  33924. return this.nodeUniform.value;
  33925. }
  33926. /**
  33927. * Returns the node uniform data type.
  33928. *
  33929. * @return {string} The data type.
  33930. */
  33931. getType() {
  33932. return this.nodeUniform.type;
  33933. }
  33934. }
  33935. /**
  33936. * A special form of Matrix4 uniform binding type.
  33937. * It's value is managed by a node object.
  33938. *
  33939. * @private
  33940. * @augments Matrix4Uniform
  33941. */
  33942. class Matrix4NodeUniform extends Matrix4Uniform {
  33943. /**
  33944. * Constructs a new node-based Matrix4 uniform.
  33945. *
  33946. * @param {NodeUniform} nodeUniform - The node uniform.
  33947. */
  33948. constructor( nodeUniform ) {
  33949. super( nodeUniform.name, nodeUniform.value );
  33950. /**
  33951. * The node uniform.
  33952. *
  33953. * @type {NodeUniform}
  33954. */
  33955. this.nodeUniform = nodeUniform;
  33956. }
  33957. /**
  33958. * Overwritten to return the value of the node uniform.
  33959. *
  33960. * @return {Matrix4} The value.
  33961. */
  33962. getValue() {
  33963. return this.nodeUniform.value;
  33964. }
  33965. /**
  33966. * Returns the node uniform data type.
  33967. *
  33968. * @return {string} The data type.
  33969. */
  33970. getType() {
  33971. return this.nodeUniform.type;
  33972. }
  33973. }
  33974. const rendererCache = new WeakMap();
  33975. const typeFromArray = new Map( [
  33976. [ Int8Array, 'int' ],
  33977. [ Int16Array, 'int' ],
  33978. [ Int32Array, 'int' ],
  33979. [ Uint8Array, 'uint' ],
  33980. [ Uint16Array, 'uint' ],
  33981. [ Uint32Array, 'uint' ],
  33982. [ Float32Array, 'float' ]
  33983. ] );
  33984. const toFloat = ( value ) => {
  33985. if ( /e/g.test( value ) ) {
  33986. return String( value ).replace( /\+/g, '' );
  33987. } else {
  33988. value = Number( value );
  33989. return value + ( value % 1 ? '' : '.0' );
  33990. }
  33991. };
  33992. /**
  33993. * Base class for builders which generate a shader program based
  33994. * on a 3D object and its node material definition.
  33995. */
  33996. class NodeBuilder {
  33997. /**
  33998. * Constructs a new node builder.
  33999. *
  34000. * @param {Object3D} object - The 3D object.
  34001. * @param {Renderer} renderer - The current renderer.
  34002. * @param {NodeParser} parser - A reference to a node parser.
  34003. */
  34004. constructor( object, renderer, parser ) {
  34005. /**
  34006. * The 3D object.
  34007. *
  34008. * @type {Object3D}
  34009. */
  34010. this.object = object;
  34011. /**
  34012. * The material of the 3D object.
  34013. *
  34014. * @type {?Material}
  34015. */
  34016. this.material = ( object && object.material ) || null;
  34017. /**
  34018. * The geometry of the 3D object.
  34019. *
  34020. * @type {?BufferGeometry}
  34021. */
  34022. this.geometry = ( object && object.geometry ) || null;
  34023. /**
  34024. * The current renderer.
  34025. *
  34026. * @type {Renderer}
  34027. */
  34028. this.renderer = renderer;
  34029. /**
  34030. * A reference to a node parser.
  34031. *
  34032. * @type {NodeParser}
  34033. */
  34034. this.parser = parser;
  34035. /**
  34036. * The scene the 3D object belongs to.
  34037. *
  34038. * @type {?Scene}
  34039. * @default null
  34040. */
  34041. this.scene = null;
  34042. /**
  34043. * The camera the 3D object is rendered with.
  34044. *
  34045. * @type {?Camera}
  34046. * @default null
  34047. */
  34048. this.camera = null;
  34049. /**
  34050. * A list of all nodes the builder is processing
  34051. * for this 3D object.
  34052. *
  34053. * @type {Array<Node>}
  34054. */
  34055. this.nodes = [];
  34056. /**
  34057. * A list of all sequential nodes.
  34058. *
  34059. * @type {Array<Node>}
  34060. */
  34061. this.sequentialNodes = [];
  34062. /**
  34063. * A list of all nodes which {@link Node#update} method should be executed.
  34064. *
  34065. * @type {Array<Node>}
  34066. */
  34067. this.updateNodes = [];
  34068. /**
  34069. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  34070. *
  34071. * @type {Array<Node>}
  34072. */
  34073. this.updateBeforeNodes = [];
  34074. /**
  34075. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  34076. *
  34077. * @type {Array<Node>}
  34078. */
  34079. this.updateAfterNodes = [];
  34080. /**
  34081. * A dictionary that assigns each node to a unique hash.
  34082. *
  34083. * @type {Object<number,Node>}
  34084. */
  34085. this.hashNodes = {};
  34086. /**
  34087. * A reference to a node material observer.
  34088. *
  34089. * @type {?NodeMaterialObserver}
  34090. * @default null
  34091. */
  34092. this.observer = null;
  34093. /**
  34094. * A reference to the current lights node.
  34095. *
  34096. * @type {?LightsNode}
  34097. * @default null
  34098. */
  34099. this.lightsNode = null;
  34100. /**
  34101. * A reference to the current environment node.
  34102. *
  34103. * @type {?Node}
  34104. * @default null
  34105. */
  34106. this.environmentNode = null;
  34107. /**
  34108. * A reference to the current fog node.
  34109. *
  34110. * @type {?Node}
  34111. * @default null
  34112. */
  34113. this.fogNode = null;
  34114. /**
  34115. * The current clipping context.
  34116. *
  34117. * @type {?ClippingContext}
  34118. */
  34119. this.clippingContext = null;
  34120. /**
  34121. * The generated vertex shader.
  34122. *
  34123. * @type {?string}
  34124. */
  34125. this.vertexShader = null;
  34126. /**
  34127. * The generated fragment shader.
  34128. *
  34129. * @type {?string}
  34130. */
  34131. this.fragmentShader = null;
  34132. /**
  34133. * The generated compute shader.
  34134. *
  34135. * @type {?string}
  34136. */
  34137. this.computeShader = null;
  34138. /**
  34139. * Nodes used in the primary flow of code generation.
  34140. *
  34141. * @type {Object<string,Array<Node>>}
  34142. */
  34143. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  34144. /**
  34145. * Nodes code from `.flowNodes`.
  34146. *
  34147. * @type {Object<string,string>}
  34148. */
  34149. this.flowCode = { vertex: '', fragment: '', compute: '' };
  34150. /**
  34151. * This dictionary holds the node uniforms of the builder.
  34152. * The uniforms are maintained in an array for each shader stage.
  34153. *
  34154. * @type {Object}
  34155. */
  34156. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  34157. /**
  34158. * This dictionary holds the output structs of the builder.
  34159. * The structs are maintained in an array for each shader stage.
  34160. *
  34161. * @type {Object}
  34162. */
  34163. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  34164. /**
  34165. * This dictionary holds the types of the builder.
  34166. *
  34167. * @type {Object}
  34168. */
  34169. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  34170. /**
  34171. * This dictionary holds the bindings for each shader stage.
  34172. *
  34173. * @type {Object}
  34174. */
  34175. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  34176. /**
  34177. * This dictionary maintains the binding indices per bind group.
  34178. *
  34179. * @type {Object}
  34180. */
  34181. this.bindingsIndexes = {};
  34182. /**
  34183. * Reference to the array of bind groups.
  34184. *
  34185. * @type {?Array<BindGroup>}
  34186. */
  34187. this.bindGroups = null;
  34188. /**
  34189. * This array holds the node attributes of this builder
  34190. * created via {@link AttributeNode}.
  34191. *
  34192. * @type {Array<NodeAttribute>}
  34193. */
  34194. this.attributes = [];
  34195. /**
  34196. * This array holds the node attributes of this builder
  34197. * created via {@link BufferAttributeNode}.
  34198. *
  34199. * @type {Array<NodeAttribute>}
  34200. */
  34201. this.bufferAttributes = [];
  34202. /**
  34203. * This array holds the node varyings of this builder.
  34204. *
  34205. * @type {Array<NodeVarying>}
  34206. */
  34207. this.varyings = [];
  34208. /**
  34209. * This dictionary holds the (native) node codes of this builder.
  34210. * The codes are maintained in an array for each shader stage.
  34211. *
  34212. * @type {Object<string,Array<NodeCode>>}
  34213. */
  34214. this.codes = {};
  34215. /**
  34216. * This dictionary holds the node variables of this builder.
  34217. * The variables are maintained in an array for each shader stage.
  34218. * This dictionary is also used to count the number of variables
  34219. * according to their type (const, vars).
  34220. *
  34221. * @type {Object<string,Array<NodeVar>|number>}
  34222. */
  34223. this.vars = {};
  34224. /**
  34225. * This dictionary holds the declarations for each shader stage.
  34226. *
  34227. * @type {Object}
  34228. */
  34229. this.declarations = {};
  34230. /**
  34231. * Current code flow.
  34232. * All code generated in this stack will be stored in `.flow`.
  34233. *
  34234. * @type {{code: string}}
  34235. */
  34236. this.flow = { code: '' };
  34237. /**
  34238. * A chain of nodes.
  34239. * Used to check recursive calls in node-graph.
  34240. *
  34241. * @type {Array<Node>}
  34242. */
  34243. this.chaining = [];
  34244. /**
  34245. * The current stack.
  34246. * This reflects the current process in the code block hierarchy,
  34247. * it is useful to know if the current process is inside a conditional for example.
  34248. *
  34249. * @type {StackNode}
  34250. */
  34251. this.stack = stack();
  34252. /**
  34253. * List of stack nodes.
  34254. * The current stack hierarchy is stored in an array.
  34255. *
  34256. * @type {Array<StackNode>}
  34257. */
  34258. this.stacks = [];
  34259. /**
  34260. * A tab value. Used for shader string generation.
  34261. *
  34262. * @type {string}
  34263. * @default '\t'
  34264. */
  34265. this.tab = '\t';
  34266. /**
  34267. * Reference to the current function node.
  34268. *
  34269. * @type {?FunctionNode}
  34270. * @default null
  34271. */
  34272. this.currentFunctionNode = null;
  34273. /**
  34274. * The builder's context.
  34275. *
  34276. * @type {Object}
  34277. */
  34278. this.context = {
  34279. material: this.material
  34280. };
  34281. /**
  34282. * The builder's cache.
  34283. *
  34284. * @type {NodeCache}
  34285. */
  34286. this.cache = new NodeCache();
  34287. /**
  34288. * Since the {@link NodeBuilder#cache} might be temporarily
  34289. * overwritten by other caches, this member retains the reference
  34290. * to the builder's own cache.
  34291. *
  34292. * @type {NodeCache}
  34293. * @default this.cache
  34294. */
  34295. this.globalCache = this.cache;
  34296. this.flowsData = new WeakMap();
  34297. /**
  34298. * The current shader stage.
  34299. *
  34300. * @type {?('vertex'|'fragment'|'compute'|'any')}
  34301. */
  34302. this.shaderStage = null;
  34303. /**
  34304. * The current build stage.
  34305. *
  34306. * @type {?('setup'|'analyze'|'generate')}
  34307. */
  34308. this.buildStage = null;
  34309. /**
  34310. * The sub-build layers.
  34311. *
  34312. * @type {Array<SubBuildNode>}
  34313. * @default []
  34314. */
  34315. this.subBuildLayers = [];
  34316. /**
  34317. * The current stack of nodes.
  34318. *
  34319. * @type {?StackNode}
  34320. * @default null
  34321. */
  34322. this.currentStack = null;
  34323. /**
  34324. * The current sub-build TSL function(Fn).
  34325. *
  34326. * @type {?string}
  34327. * @default null
  34328. */
  34329. this.subBuildFn = null;
  34330. /**
  34331. * The current TSL function(Fn) call node.
  34332. *
  34333. * @type {?Node}
  34334. * @default null
  34335. */
  34336. this.fnCall = null;
  34337. }
  34338. /**
  34339. * Returns the bind groups of the current renderer.
  34340. *
  34341. * @return {ChainMap} The cache.
  34342. */
  34343. getBindGroupsCache() {
  34344. let bindGroupsCache = rendererCache.get( this.renderer );
  34345. if ( bindGroupsCache === undefined ) {
  34346. bindGroupsCache = new ChainMap();
  34347. rendererCache.set( this.renderer, bindGroupsCache );
  34348. }
  34349. return bindGroupsCache;
  34350. }
  34351. /**
  34352. * Factory method for creating an instance of {@link RenderTarget} with the given
  34353. * dimensions and options.
  34354. *
  34355. * @param {number} width - The width of the render target.
  34356. * @param {number} height - The height of the render target.
  34357. * @param {Object} options - The options of the render target.
  34358. * @return {RenderTarget} The render target.
  34359. */
  34360. createRenderTarget( width, height, options ) {
  34361. return new RenderTarget( width, height, options );
  34362. }
  34363. /**
  34364. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  34365. * dimensions and options.
  34366. *
  34367. * @param {number} size - The size of the cube render target.
  34368. * @param {Object} options - The options of the cube render target.
  34369. * @return {CubeRenderTarget} The cube render target.
  34370. */
  34371. createCubeRenderTarget( size, options ) {
  34372. return new CubeRenderTarget( size, options );
  34373. }
  34374. /**
  34375. * Whether the given node is included in the internal array of nodes or not.
  34376. *
  34377. * @param {Node} node - The node to test.
  34378. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  34379. */
  34380. includes( node ) {
  34381. return this.nodes.includes( node );
  34382. }
  34383. /**
  34384. * Returns the output struct name which is required by
  34385. * {@link OutputStructNode}.
  34386. *
  34387. * @abstract
  34388. * @return {string} The name of the output struct.
  34389. */
  34390. getOutputStructName() {}
  34391. /**
  34392. * Returns a bind group for the given group name and binding.
  34393. *
  34394. * @private
  34395. * @param {string} groupName - The group name.
  34396. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  34397. * @return {BindGroup} The bind group
  34398. */
  34399. _getBindGroup( groupName, bindings ) {
  34400. const bindGroupsCache = this.getBindGroupsCache();
  34401. //
  34402. const bindingsArray = [];
  34403. let sharedGroup = true;
  34404. for ( const binding of bindings ) {
  34405. bindingsArray.push( binding );
  34406. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  34407. }
  34408. //
  34409. let bindGroup;
  34410. if ( sharedGroup ) {
  34411. bindGroup = bindGroupsCache.get( bindingsArray );
  34412. if ( bindGroup === undefined ) {
  34413. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  34414. bindGroupsCache.set( bindingsArray, bindGroup );
  34415. }
  34416. } else {
  34417. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  34418. }
  34419. return bindGroup;
  34420. }
  34421. /**
  34422. * Returns an array of node uniform groups for the given group name and shader stage.
  34423. *
  34424. * @param {string} groupName - The group name.
  34425. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34426. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  34427. */
  34428. getBindGroupArray( groupName, shaderStage ) {
  34429. const bindings = this.bindings[ shaderStage ];
  34430. let bindGroup = bindings[ groupName ];
  34431. if ( bindGroup === undefined ) {
  34432. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  34433. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  34434. }
  34435. bindings[ groupName ] = bindGroup = [];
  34436. }
  34437. return bindGroup;
  34438. }
  34439. /**
  34440. * Returns a list bindings of all shader stages separated by groups.
  34441. *
  34442. * @return {Array<BindGroup>} The list of bindings.
  34443. */
  34444. getBindings() {
  34445. let bindingsGroups = this.bindGroups;
  34446. if ( bindingsGroups === null ) {
  34447. const groups = {};
  34448. const bindings = this.bindings;
  34449. for ( const shaderStage of shaderStages ) {
  34450. for ( const groupName in bindings[ shaderStage ] ) {
  34451. const uniforms = bindings[ shaderStage ][ groupName ];
  34452. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  34453. groupUniforms.push( ...uniforms );
  34454. }
  34455. }
  34456. bindingsGroups = [];
  34457. for ( const groupName in groups ) {
  34458. const group = groups[ groupName ];
  34459. const bindingsGroup = this._getBindGroup( groupName, group );
  34460. bindingsGroups.push( bindingsGroup );
  34461. }
  34462. this.bindGroups = bindingsGroups;
  34463. }
  34464. return bindingsGroups;
  34465. }
  34466. /**
  34467. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  34468. */
  34469. sortBindingGroups() {
  34470. const bindingsGroups = this.getBindings();
  34471. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  34472. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  34473. const bindingGroup = bindingsGroups[ i ];
  34474. this.bindingsIndexes[ bindingGroup.name ].group = i;
  34475. bindingGroup.index = i;
  34476. }
  34477. }
  34478. /**
  34479. * The builder maintains each node in a hash-based dictionary.
  34480. * This method sets the given node (value) with the given hash (key) into this dictionary.
  34481. *
  34482. * @param {Node} node - The node to add.
  34483. * @param {number} hash - The hash of the node.
  34484. */
  34485. setHashNode( node, hash ) {
  34486. this.hashNodes[ hash ] = node;
  34487. }
  34488. /**
  34489. * Adds a node to this builder.
  34490. *
  34491. * @param {Node} node - The node to add.
  34492. */
  34493. addNode( node ) {
  34494. if ( this.nodes.includes( node ) === false ) {
  34495. this.nodes.push( node );
  34496. this.setHashNode( node, node.getHash( this ) );
  34497. }
  34498. }
  34499. /**
  34500. * It is used to add Nodes that will be used as FRAME and RENDER events,
  34501. * and need to follow a certain sequence in the calls to work correctly.
  34502. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  34503. *
  34504. * @param {Node} node - The node to add.
  34505. */
  34506. addSequentialNode( node ) {
  34507. if ( this.sequentialNodes.includes( node ) === false ) {
  34508. this.sequentialNodes.push( node );
  34509. }
  34510. }
  34511. /**
  34512. * Checks the update types of nodes
  34513. */
  34514. buildUpdateNodes() {
  34515. for ( const node of this.nodes ) {
  34516. const updateType = node.getUpdateType();
  34517. if ( updateType !== NodeUpdateType.NONE ) {
  34518. this.updateNodes.push( node );
  34519. }
  34520. }
  34521. for ( const node of this.sequentialNodes ) {
  34522. const updateBeforeType = node.getUpdateBeforeType();
  34523. const updateAfterType = node.getUpdateAfterType();
  34524. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  34525. this.updateBeforeNodes.push( node );
  34526. }
  34527. if ( updateAfterType !== NodeUpdateType.NONE ) {
  34528. this.updateAfterNodes.push( node );
  34529. }
  34530. }
  34531. }
  34532. /**
  34533. * A reference the current node which is the
  34534. * last node in the chain of nodes.
  34535. *
  34536. * @type {Node}
  34537. */
  34538. get currentNode() {
  34539. return this.chaining[ this.chaining.length - 1 ];
  34540. }
  34541. /**
  34542. * Whether the given texture is filtered or not.
  34543. *
  34544. * @param {Texture} texture - The texture to check.
  34545. * @return {boolean} Whether the given texture is filtered or not.
  34546. */
  34547. isFilteredTexture( texture ) {
  34548. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  34549. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  34550. }
  34551. /**
  34552. * Adds the given node to the internal node chain.
  34553. * This is used to check recursive calls in node-graph.
  34554. *
  34555. * @param {Node} node - The node to add.
  34556. */
  34557. addChain( node ) {
  34558. /*
  34559. if ( this.chaining.indexOf( node ) !== - 1 ) {
  34560. warn( 'Recursive node: ', node );
  34561. }
  34562. */
  34563. this.chaining.push( node );
  34564. }
  34565. /**
  34566. * Removes the given node from the internal node chain.
  34567. *
  34568. * @param {Node} node - The node to remove.
  34569. */
  34570. removeChain( node ) {
  34571. const lastChain = this.chaining.pop();
  34572. if ( lastChain !== node ) {
  34573. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  34574. }
  34575. }
  34576. /**
  34577. * Returns the native shader method name for a given generic name. E.g.
  34578. * the method name `textureDimensions` matches the WGSL name but must be
  34579. * resolved to `textureSize` in GLSL.
  34580. *
  34581. * @abstract
  34582. * @param {string} method - The method name to resolve.
  34583. * @return {string} The resolved method name.
  34584. */
  34585. getMethod( method ) {
  34586. return method;
  34587. }
  34588. /**
  34589. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  34590. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  34591. *
  34592. * @abstract
  34593. * @param {string} condSnippet - The condition determining which expression gets resolved.
  34594. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  34595. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  34596. * @return {string} The resolved method name.
  34597. */
  34598. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  34599. return null;
  34600. }
  34601. /**
  34602. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  34603. *
  34604. * @param {number} hash - The hash of the node.
  34605. * @return {Node} The found node.
  34606. */
  34607. getNodeFromHash( hash ) {
  34608. return this.hashNodes[ hash ];
  34609. }
  34610. /**
  34611. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  34612. *
  34613. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  34614. * @param {Node} node - The node to add.
  34615. * @return {Node} The node.
  34616. */
  34617. addFlow( shaderStage, node ) {
  34618. this.flowNodes[ shaderStage ].push( node );
  34619. return node;
  34620. }
  34621. /**
  34622. * Sets builder's context.
  34623. *
  34624. * @param {Object} context - The context to set.
  34625. */
  34626. setContext( context ) {
  34627. this.context = context;
  34628. }
  34629. /**
  34630. * Returns the builder's current context.
  34631. *
  34632. * @return {Object} The builder's current context.
  34633. */
  34634. getContext() {
  34635. return this.context;
  34636. }
  34637. /**
  34638. * Adds context data to the builder's current context.
  34639. *
  34640. * @param {Object} context - The context to add.
  34641. * @return {Object} The previous context.
  34642. */
  34643. addContext( context ) {
  34644. const previousContext = this.getContext();
  34645. this.setContext( { ...this.context, ...context } );
  34646. return previousContext;
  34647. }
  34648. /**
  34649. * Gets a context used in shader construction that can be shared across different materials.
  34650. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  34651. *
  34652. * @return {Object} The builder's current context without material.
  34653. */
  34654. getSharedContext() {
  34655. ({ ...this.context });
  34656. return this.context;
  34657. }
  34658. /**
  34659. * Sets builder's cache.
  34660. *
  34661. * @param {NodeCache} cache - The cache to set.
  34662. */
  34663. setCache( cache ) {
  34664. this.cache = cache;
  34665. }
  34666. /**
  34667. * Returns the builder's current cache.
  34668. *
  34669. * @return {NodeCache} The builder's current cache.
  34670. */
  34671. getCache() {
  34672. return this.cache;
  34673. }
  34674. /**
  34675. * Returns a cache for the given node.
  34676. *
  34677. * @param {Node} node - The node.
  34678. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  34679. * @return {NodeCache} The cache.
  34680. */
  34681. getCacheFromNode( node, parent = true ) {
  34682. const data = this.getDataFromNode( node );
  34683. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  34684. return data.cache;
  34685. }
  34686. /**
  34687. * Whether the requested feature is available or not.
  34688. *
  34689. * @abstract
  34690. * @param {string} name - The requested feature.
  34691. * @return {boolean} Whether the requested feature is supported or not.
  34692. */
  34693. isAvailable( /*name*/ ) {
  34694. return false;
  34695. }
  34696. /**
  34697. * Returns the vertexIndex input variable as a native shader string.
  34698. *
  34699. * @abstract
  34700. * @return {string} The instanceIndex shader string.
  34701. */
  34702. getVertexIndex() {
  34703. warn( 'Abstract function.' );
  34704. }
  34705. /**
  34706. * Contextually returns either the vertex stage instance index builtin
  34707. * or the linearized index of an compute invocation within a grid of workgroups.
  34708. *
  34709. * @abstract
  34710. * @return {string} The instanceIndex shader string.
  34711. */
  34712. getInstanceIndex() {
  34713. warn( 'Abstract function.' );
  34714. }
  34715. /**
  34716. * Returns the drawIndex input variable as a native shader string.
  34717. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  34718. *
  34719. * @abstract
  34720. * @return {?string} The drawIndex shader string.
  34721. */
  34722. getDrawIndex() {
  34723. warn( 'Abstract function.' );
  34724. }
  34725. /**
  34726. * Returns the frontFacing input variable as a native shader string.
  34727. *
  34728. * @abstract
  34729. * @return {string} The frontFacing shader string.
  34730. */
  34731. getFrontFacing() {
  34732. warn( 'Abstract function.' );
  34733. }
  34734. /**
  34735. * Returns the fragCoord input variable as a native shader string.
  34736. *
  34737. * @abstract
  34738. * @return {string} The fragCoord shader string.
  34739. */
  34740. getFragCoord() {
  34741. warn( 'Abstract function.' );
  34742. }
  34743. /**
  34744. * Whether to flip texture data along its vertical axis or not. WebGL needs
  34745. * this method evaluate to `true`, WebGPU to `false`.
  34746. *
  34747. * @abstract
  34748. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  34749. */
  34750. isFlipY() {
  34751. return false;
  34752. }
  34753. /**
  34754. * Calling this method increases the usage count for the given node by one.
  34755. *
  34756. * @param {Node} node - The node to increase the usage count for.
  34757. * @return {number} The updated usage count.
  34758. */
  34759. increaseUsage( node ) {
  34760. const nodeData = this.getDataFromNode( node );
  34761. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  34762. return nodeData.usageCount;
  34763. }
  34764. /**
  34765. * Generates a texture sample shader string for the given texture data.
  34766. *
  34767. * @abstract
  34768. * @param {Texture} texture - The texture.
  34769. * @param {string} textureProperty - The texture property name.
  34770. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  34771. * @return {string} The generated shader string.
  34772. */
  34773. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  34774. warn( 'Abstract function.' );
  34775. }
  34776. /**
  34777. * Generates a texture LOD shader string for the given texture data.
  34778. *
  34779. * @abstract
  34780. * @param {Texture} texture - The texture.
  34781. * @param {string} textureProperty - The texture property name.
  34782. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  34783. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  34784. * @param {string} levelSnippet - Snippet defining the mip level.
  34785. * @return {string} The generated shader string.
  34786. */
  34787. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  34788. warn( 'Abstract function.' );
  34789. }
  34790. /**
  34791. * Generates the array declaration string.
  34792. *
  34793. * @param {string} type - The type.
  34794. * @param {?number} [count] - The count.
  34795. * @return {string} The generated value as a shader string.
  34796. */
  34797. generateArrayDeclaration( type, count ) {
  34798. return this.getType( type ) + '[ ' + count + ' ]';
  34799. }
  34800. /**
  34801. * Generates the array shader string for the given type and value.
  34802. *
  34803. * @param {string} type - The type.
  34804. * @param {?number} [count] - The count.
  34805. * @param {?Array<Node>} [values=null] - The default values.
  34806. * @return {string} The generated value as a shader string.
  34807. */
  34808. generateArray( type, count, values = null ) {
  34809. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  34810. for ( let i = 0; i < count; i ++ ) {
  34811. const value = values ? values[ i ] : null;
  34812. if ( value !== null ) {
  34813. snippet += value.build( this, type );
  34814. } else {
  34815. snippet += this.generateConst( type );
  34816. }
  34817. if ( i < count - 1 ) snippet += ', ';
  34818. }
  34819. snippet += ' )';
  34820. return snippet;
  34821. }
  34822. /**
  34823. * Generates the struct shader string.
  34824. *
  34825. * @param {string} type - The type.
  34826. * @param {Array<Object>} [membersLayout] - The count.
  34827. * @param {?Array<Node>} [values=null] - The default values.
  34828. * @return {string} The generated value as a shader string.
  34829. */
  34830. generateStruct( type, membersLayout, values = null ) {
  34831. const snippets = [];
  34832. for ( const member of membersLayout ) {
  34833. const { name, type } = member;
  34834. if ( values && values[ name ] && values[ name ].isNode ) {
  34835. snippets.push( values[ name ].build( this, type ) );
  34836. } else {
  34837. snippets.push( this.generateConst( type ) );
  34838. }
  34839. }
  34840. return type + '( ' + snippets.join( ', ' ) + ' )';
  34841. }
  34842. /**
  34843. * Generates the shader string for the given type and value.
  34844. *
  34845. * @param {string} type - The type.
  34846. * @param {?any} [value=null] - The value.
  34847. * @return {string} The generated value as a shader string.
  34848. */
  34849. generateConst( type, value = null ) {
  34850. if ( value === null ) {
  34851. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  34852. else if ( type === 'bool' ) value = false;
  34853. else if ( type === 'color' ) value = new Color();
  34854. else if ( type === 'vec2' ) value = new Vector2();
  34855. else if ( type === 'vec3' ) value = new Vector3();
  34856. else if ( type === 'vec4' ) value = new Vector4();
  34857. }
  34858. if ( type === 'float' ) return toFloat( value );
  34859. if ( type === 'int' ) return `${ Math.round( value ) }`;
  34860. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  34861. if ( type === 'bool' ) return value ? 'true' : 'false';
  34862. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  34863. const typeLength = this.getTypeLength( type );
  34864. const componentType = this.getComponentType( type );
  34865. const generateConst = value => this.generateConst( componentType, value );
  34866. if ( typeLength === 2 ) {
  34867. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  34868. } else if ( typeLength === 3 ) {
  34869. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  34870. } else if ( typeLength === 4 && type !== 'mat2' ) {
  34871. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  34872. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  34873. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  34874. } else if ( typeLength > 4 ) {
  34875. return `${ this.getType( type ) }()`;
  34876. }
  34877. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  34878. }
  34879. /**
  34880. * It might be necessary to convert certain data types to different ones
  34881. * so this method can be used to hide the conversion.
  34882. *
  34883. * @param {string} type - The type.
  34884. * @return {string} The updated type.
  34885. */
  34886. getType( type ) {
  34887. if ( type === 'color' ) return 'vec3';
  34888. return type;
  34889. }
  34890. /**
  34891. * Whether the given attribute name is defined in the geometry or not.
  34892. *
  34893. * @param {string} name - The attribute name.
  34894. * @return {boolean} Whether the given attribute name is defined in the geometry.
  34895. */
  34896. hasGeometryAttribute( name ) {
  34897. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  34898. }
  34899. /**
  34900. * Returns a node attribute for the given name and type.
  34901. *
  34902. * @param {string} name - The attribute's name.
  34903. * @param {string} type - The attribute's type.
  34904. * @return {NodeAttribute} The node attribute.
  34905. */
  34906. getAttribute( name, type ) {
  34907. const attributes = this.attributes;
  34908. // find attribute
  34909. for ( const attribute of attributes ) {
  34910. if ( attribute.name === name ) {
  34911. return attribute;
  34912. }
  34913. }
  34914. // create a new if no exist
  34915. const attribute = new NodeAttribute( name, type );
  34916. this.registerDeclaration( attribute );
  34917. attributes.push( attribute );
  34918. return attribute;
  34919. }
  34920. /**
  34921. * Returns for the given node and shader stage the property name for the shader.
  34922. *
  34923. * @param {Node} node - The node.
  34924. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34925. * @return {string} The property name.
  34926. */
  34927. getPropertyName( node/*, shaderStage*/ ) {
  34928. return node.name;
  34929. }
  34930. /**
  34931. * Whether the given type is a vector type or not.
  34932. *
  34933. * @param {string} type - The type to check.
  34934. * @return {boolean} Whether the given type is a vector type or not.
  34935. */
  34936. isVector( type ) {
  34937. return /vec\d/.test( type );
  34938. }
  34939. /**
  34940. * Whether the given type is a matrix type or not.
  34941. *
  34942. * @param {string} type - The type to check.
  34943. * @return {boolean} Whether the given type is a matrix type or not.
  34944. */
  34945. isMatrix( type ) {
  34946. return /mat\d/.test( type );
  34947. }
  34948. /**
  34949. * Whether the given type is a reference type or not.
  34950. *
  34951. * @param {string} type - The type to check.
  34952. * @return {boolean} Whether the given type is a reference type or not.
  34953. */
  34954. isReference( type ) {
  34955. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  34956. }
  34957. /**
  34958. * Checks if the given texture requires a manual conversion to the working color space.
  34959. *
  34960. * @abstract
  34961. * @param {Texture} texture - The texture to check.
  34962. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  34963. */
  34964. needsToWorkingColorSpace( /*texture*/ ) {
  34965. return false;
  34966. }
  34967. /**
  34968. * Returns the component type of a given texture.
  34969. *
  34970. * @param {Texture} texture - The texture.
  34971. * @return {string} The component type.
  34972. */
  34973. getComponentTypeFromTexture( texture ) {
  34974. const type = texture.type;
  34975. if ( texture.isDataTexture ) {
  34976. if ( type === IntType ) return 'int';
  34977. if ( type === UnsignedIntType ) return 'uint';
  34978. }
  34979. return 'float';
  34980. }
  34981. /**
  34982. * Returns the element type for a given type.
  34983. *
  34984. * @param {string} type - The type.
  34985. * @return {string} The element type.
  34986. */
  34987. getElementType( type ) {
  34988. if ( type === 'mat2' ) return 'vec2';
  34989. if ( type === 'mat3' ) return 'vec3';
  34990. if ( type === 'mat4' ) return 'vec4';
  34991. return this.getComponentType( type );
  34992. }
  34993. /**
  34994. * Returns the component type for a given type.
  34995. *
  34996. * @param {string} type - The type.
  34997. * @return {string} The component type.
  34998. */
  34999. getComponentType( type ) {
  35000. type = this.getVectorType( type );
  35001. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  35002. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  35003. if ( componentType === null ) return null;
  35004. if ( componentType[ 1 ] === 'b' ) return 'bool';
  35005. if ( componentType[ 1 ] === 'i' ) return 'int';
  35006. if ( componentType[ 1 ] === 'u' ) return 'uint';
  35007. return 'float';
  35008. }
  35009. /**
  35010. * Returns the vector type for a given type.
  35011. *
  35012. * @param {string} type - The type.
  35013. * @return {string} The vector type.
  35014. */
  35015. getVectorType( type ) {
  35016. if ( type === 'color' ) return 'vec3';
  35017. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  35018. return type;
  35019. }
  35020. /**
  35021. * Returns the data type for the given the length and component type.
  35022. *
  35023. * @param {number} length - The length.
  35024. * @param {string} [componentType='float'] - The component type.
  35025. * @return {string} The type.
  35026. */
  35027. getTypeFromLength( length, componentType = 'float' ) {
  35028. if ( length === 1 ) return componentType;
  35029. let baseType = getTypeFromLength( length );
  35030. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  35031. // fix edge case for mat2x2 being same size as vec4
  35032. if ( /mat2/.test( componentType ) === true ) {
  35033. baseType = baseType.replace( 'vec', 'mat' );
  35034. }
  35035. return prefix + baseType;
  35036. }
  35037. /**
  35038. * Returns the type for a given typed array.
  35039. *
  35040. * @param {TypedArray} array - The typed array.
  35041. * @return {string} The type.
  35042. */
  35043. getTypeFromArray( array ) {
  35044. return typeFromArray.get( array.constructor );
  35045. }
  35046. /**
  35047. * Returns the type is an integer type.
  35048. *
  35049. * @param {string} type - The type.
  35050. * @return {boolean} Whether the type is an integer type or not.
  35051. */
  35052. isInteger( type ) {
  35053. return /int|uint|(i|u)vec/.test( type );
  35054. }
  35055. /**
  35056. * Returns the type for a given buffer attribute.
  35057. *
  35058. * @param {BufferAttribute} attribute - The buffer attribute.
  35059. * @return {string} The type.
  35060. */
  35061. getTypeFromAttribute( attribute ) {
  35062. let dataAttribute = attribute;
  35063. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  35064. const array = dataAttribute.array;
  35065. const itemSize = attribute.itemSize;
  35066. const normalized = attribute.normalized;
  35067. let arrayType;
  35068. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  35069. arrayType = this.getTypeFromArray( array );
  35070. }
  35071. return this.getTypeFromLength( itemSize, arrayType );
  35072. }
  35073. /**
  35074. * Returns the length for the given data type.
  35075. *
  35076. * @param {string} type - The data type.
  35077. * @return {number} The length.
  35078. */
  35079. getTypeLength( type ) {
  35080. const vecType = this.getVectorType( type );
  35081. const vecNum = /vec([2-4])/.exec( vecType );
  35082. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  35083. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  35084. if ( /mat2/.test( type ) === true ) return 4;
  35085. if ( /mat3/.test( type ) === true ) return 9;
  35086. if ( /mat4/.test( type ) === true ) return 16;
  35087. return 0;
  35088. }
  35089. /**
  35090. * Returns the vector type for a given matrix type.
  35091. *
  35092. * @param {string} type - The matrix type.
  35093. * @return {string} The vector type.
  35094. */
  35095. getVectorFromMatrix( type ) {
  35096. return type.replace( 'mat', 'vec' );
  35097. }
  35098. /**
  35099. * For a given type this method changes the component type to the
  35100. * given value. E.g. `vec4` should be changed to the new component type
  35101. * `uint` which results in `uvec4`.
  35102. *
  35103. * @param {string} type - The type.
  35104. * @param {string} newComponentType - The new component type.
  35105. * @return {string} The new type.
  35106. */
  35107. changeComponentType( type, newComponentType ) {
  35108. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  35109. }
  35110. /**
  35111. * Returns the integer type pendant for the given type.
  35112. *
  35113. * @param {string} type - The type.
  35114. * @return {string} The integer type.
  35115. */
  35116. getIntegerType( type ) {
  35117. const componentType = this.getComponentType( type );
  35118. if ( componentType === 'int' || componentType === 'uint' ) return type;
  35119. return this.changeComponentType( type, 'int' );
  35120. }
  35121. /**
  35122. * Adds a stack node to the internal stack.
  35123. *
  35124. * @return {StackNode} The added stack node.
  35125. */
  35126. addStack() {
  35127. this.stack = stack( this.stack );
  35128. const previousStack = getCurrentStack();
  35129. this.stacks.push( previousStack );
  35130. setCurrentStack( this.stack );
  35131. return this.stack;
  35132. }
  35133. /**
  35134. * Removes the last stack node from the internal stack.
  35135. *
  35136. * @return {StackNode} The removed stack node.
  35137. */
  35138. removeStack() {
  35139. const lastStack = this.stack;
  35140. this.stack = lastStack.parent;
  35141. setCurrentStack( this.stacks.pop() );
  35142. return lastStack;
  35143. }
  35144. /**
  35145. * The builder maintains (cached) data for each node during the building process. This method
  35146. * can be used to get these data for a specific shader stage and cache.
  35147. *
  35148. * @param {Node} node - The node to get the data for.
  35149. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35150. * @param {?NodeCache} cache - An optional cache.
  35151. * @return {Object} The node data.
  35152. */
  35153. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  35154. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  35155. let nodeData = cache.getData( node );
  35156. if ( nodeData === undefined ) {
  35157. nodeData = {};
  35158. cache.setData( node, nodeData );
  35159. }
  35160. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  35161. //
  35162. let data = nodeData[ shaderStage ];
  35163. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  35164. const subBuild = this.getClosestSubBuild( subBuilds );
  35165. if ( subBuild ) {
  35166. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  35167. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  35168. data.subBuilds = subBuilds;
  35169. }
  35170. return data;
  35171. }
  35172. /**
  35173. * Returns the properties for the given node and shader stage.
  35174. *
  35175. * Properties are typically used within a build stage to reference a node's
  35176. * child node or nodes manually assigned to the properties in a separate build stage.
  35177. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  35178. * to the current node's properties in the setup stage and building those properties in the generate stage.
  35179. *
  35180. * @param {Node} node - The node to get the properties for.
  35181. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  35182. * @return {Object} The node properties.
  35183. */
  35184. getNodeProperties( node, shaderStage = 'any' ) {
  35185. const nodeData = this.getDataFromNode( node, shaderStage );
  35186. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  35187. }
  35188. /**
  35189. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  35190. *
  35191. * @param {BufferAttributeNode} node - The buffer attribute node.
  35192. * @param {string} type - The node type.
  35193. * @return {NodeAttribute} The node attribute.
  35194. */
  35195. getBufferAttributeFromNode( node, type ) {
  35196. const nodeData = this.getDataFromNode( node );
  35197. let bufferAttribute = nodeData.bufferAttribute;
  35198. if ( bufferAttribute === undefined ) {
  35199. const index = this.uniforms.index ++;
  35200. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  35201. this.bufferAttributes.push( bufferAttribute );
  35202. nodeData.bufferAttribute = bufferAttribute;
  35203. }
  35204. return bufferAttribute;
  35205. }
  35206. /**
  35207. * Returns an instance of {@link StructType} for the given struct name and shader stage
  35208. * or null if not found.
  35209. *
  35210. * @param {string} name - The name of the struct.
  35211. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35212. * @return {?StructType} The struct type or null if not found.
  35213. */
  35214. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  35215. return this.types[ shaderStage ][ name ] || null;
  35216. }
  35217. /**
  35218. * Returns an instance of {@link StructType} for the given output struct node.
  35219. *
  35220. * @param {OutputStructNode} node - The output struct node.
  35221. * @param {Array<Object>} membersLayout - The output struct types.
  35222. * @param {?string} [name=null] - The name of the struct.
  35223. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35224. * @return {StructType} The struct type attribute.
  35225. */
  35226. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  35227. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  35228. let structType = nodeData.structType;
  35229. if ( structType === undefined ) {
  35230. const index = this.structs.index ++;
  35231. if ( name === null ) name = 'StructType' + index;
  35232. structType = new StructType( name, membersLayout );
  35233. this.structs[ shaderStage ].push( structType );
  35234. this.types[ shaderStage ][ name ] = node;
  35235. nodeData.structType = structType;
  35236. }
  35237. return structType;
  35238. }
  35239. /**
  35240. * Returns an instance of {@link StructType} for the given output struct node.
  35241. *
  35242. * @param {OutputStructNode} node - The output struct node.
  35243. * @param {Array<Object>} membersLayout - The output struct types.
  35244. * @return {StructType} The struct type attribute.
  35245. */
  35246. getOutputStructTypeFromNode( node, membersLayout ) {
  35247. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  35248. structType.output = true;
  35249. return structType;
  35250. }
  35251. /**
  35252. * Returns an instance of {@link NodeUniform} for the given uniform node.
  35253. *
  35254. * @param {UniformNode} node - The uniform node.
  35255. * @param {string} type - The uniform type.
  35256. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35257. * @param {?string} name - The name of the uniform.
  35258. * @return {NodeUniform} The node uniform.
  35259. */
  35260. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  35261. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  35262. let nodeUniform = nodeData.uniform;
  35263. if ( nodeUniform === undefined ) {
  35264. const index = this.uniforms.index ++;
  35265. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  35266. this.uniforms[ shaderStage ].push( nodeUniform );
  35267. this.registerDeclaration( nodeUniform );
  35268. nodeData.uniform = nodeUniform;
  35269. }
  35270. return nodeUniform;
  35271. }
  35272. /**
  35273. * Returns an instance of {@link NodeVar} for the given variable node.
  35274. *
  35275. * @param {VarNode} node - The variable node.
  35276. * @param {?string} name - The variable's name.
  35277. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  35278. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35279. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  35280. *
  35281. * @return {NodeVar} The node variable.
  35282. */
  35283. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  35284. const nodeData = this.getDataFromNode( node, shaderStage );
  35285. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  35286. let nodeVar = nodeData[ subBuildVariable ];
  35287. if ( nodeVar === undefined ) {
  35288. const idNS = readOnly ? '_const' : '_var';
  35289. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  35290. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  35291. if ( name === null ) {
  35292. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  35293. this.vars[ idNS ] ++;
  35294. }
  35295. //
  35296. if ( subBuildVariable !== 'variable' ) {
  35297. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  35298. }
  35299. //
  35300. const count = node.getArrayCount( this );
  35301. nodeVar = new NodeVar( name, type, readOnly, count );
  35302. if ( ! readOnly ) {
  35303. vars.push( nodeVar );
  35304. }
  35305. this.registerDeclaration( nodeVar );
  35306. nodeData[ subBuildVariable ] = nodeVar;
  35307. }
  35308. return nodeVar;
  35309. }
  35310. /**
  35311. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  35312. *
  35313. * @param {Node} node - The varying node.
  35314. * @return {boolean} Returns true if deterministic.
  35315. */
  35316. isDeterministic( node ) {
  35317. if ( node.isMathNode ) {
  35318. return this.isDeterministic( node.aNode ) &&
  35319. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  35320. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  35321. } else if ( node.isOperatorNode ) {
  35322. return this.isDeterministic( node.aNode ) &&
  35323. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  35324. } else if ( node.isArrayNode ) {
  35325. if ( node.values !== null ) {
  35326. for ( const n of node.values ) {
  35327. if ( ! this.isDeterministic( n ) ) {
  35328. return false;
  35329. }
  35330. }
  35331. }
  35332. return true;
  35333. } else if ( node.isConstNode ) {
  35334. return true;
  35335. }
  35336. return false;
  35337. }
  35338. /**
  35339. * Returns an instance of {@link NodeVarying} for the given varying node.
  35340. *
  35341. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  35342. * @param {?string} name - The varying's name.
  35343. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  35344. * @param {?string} interpolationType - The interpolation type of the varying.
  35345. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  35346. * @return {NodeVar} The node varying.
  35347. */
  35348. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  35349. const nodeData = this.getDataFromNode( node, 'any' );
  35350. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  35351. let nodeVarying = nodeData[ subBuildVarying ];
  35352. if ( nodeVarying === undefined ) {
  35353. const varyings = this.varyings;
  35354. const index = varyings.length;
  35355. if ( name === null ) name = 'nodeVarying' + index;
  35356. //
  35357. if ( subBuildVarying !== 'varying' ) {
  35358. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  35359. }
  35360. //
  35361. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  35362. varyings.push( nodeVarying );
  35363. this.registerDeclaration( nodeVarying );
  35364. nodeData[ subBuildVarying ] = nodeVarying;
  35365. }
  35366. return nodeVarying;
  35367. }
  35368. /**
  35369. * Registers a node declaration in the current shader stage.
  35370. *
  35371. * @param {Object} node - The node to be registered.
  35372. */
  35373. registerDeclaration( node ) {
  35374. const shaderStage = this.shaderStage;
  35375. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  35376. const property = this.getPropertyName( node );
  35377. let index = 1;
  35378. let name = property;
  35379. // Automatically renames the property if the name is already in use.
  35380. while ( declarations[ name ] !== undefined ) {
  35381. name = property + '_' + index ++;
  35382. }
  35383. if ( index > 1 ) {
  35384. node.name = name;
  35385. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  35386. }
  35387. declarations[ name ] = node;
  35388. }
  35389. /**
  35390. * Returns an instance of {@link NodeCode} for the given code node.
  35391. *
  35392. * @param {CodeNode} node - The code node.
  35393. * @param {string} type - The node type.
  35394. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35395. * @return {NodeCode} The node code.
  35396. */
  35397. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  35398. const nodeData = this.getDataFromNode( node );
  35399. let nodeCode = nodeData.code;
  35400. if ( nodeCode === undefined ) {
  35401. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  35402. const index = codes.length;
  35403. nodeCode = new NodeCode( 'nodeCode' + index, type );
  35404. codes.push( nodeCode );
  35405. nodeData.code = nodeCode;
  35406. }
  35407. return nodeCode;
  35408. }
  35409. /**
  35410. * Adds a code flow based on the code-block hierarchy.
  35411. * This is used so that code-blocks like If,Else create their variables locally if the Node
  35412. * is only used inside one of these conditionals in the current shader stage.
  35413. *
  35414. * @param {Node} node - The node to add.
  35415. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  35416. */
  35417. addFlowCodeHierarchy( node, nodeBlock ) {
  35418. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  35419. let needsFlowCode = true;
  35420. let nodeBlockHierarchy = nodeBlock;
  35421. while ( nodeBlockHierarchy ) {
  35422. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  35423. needsFlowCode = false;
  35424. break;
  35425. }
  35426. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  35427. }
  35428. if ( needsFlowCode ) {
  35429. for ( const flowCode of flowCodes ) {
  35430. this.addLineFlowCode( flowCode );
  35431. }
  35432. }
  35433. }
  35434. /**
  35435. * Add a inline-code to the current flow code-block.
  35436. *
  35437. * @param {Node} node - The node to add.
  35438. * @param {string} code - The code to add.
  35439. * @param {Node} nodeBlock - Current ConditionalNode
  35440. */
  35441. addLineFlowCodeBlock( node, code, nodeBlock ) {
  35442. const nodeData = this.getDataFromNode( node );
  35443. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  35444. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  35445. flowCodes.push( code );
  35446. codeBlock.set( nodeBlock, true );
  35447. }
  35448. /**
  35449. * Add a inline-code to the current flow.
  35450. *
  35451. * @param {string} code - The code to add.
  35452. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  35453. * @return {NodeBuilder} A reference to this node builder.
  35454. */
  35455. addLineFlowCode( code, node = null ) {
  35456. if ( code === '' ) return this;
  35457. if ( node !== null && this.context.nodeBlock ) {
  35458. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  35459. }
  35460. code = this.tab + code;
  35461. if ( ! /;\s*$/.test( code ) ) {
  35462. code = code + ';\n';
  35463. }
  35464. this.flow.code += code;
  35465. return this;
  35466. }
  35467. /**
  35468. * Adds a code to the current code flow.
  35469. *
  35470. * @param {string} code - Shader code.
  35471. * @return {NodeBuilder} A reference to this node builder.
  35472. */
  35473. addFlowCode( code ) {
  35474. this.flow.code += code;
  35475. return this;
  35476. }
  35477. /**
  35478. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  35479. * Typically used in codes with If,Else.
  35480. *
  35481. * @return {NodeBuilder} A reference to this node builder.
  35482. */
  35483. addFlowTab() {
  35484. this.tab += '\t';
  35485. return this;
  35486. }
  35487. /**
  35488. * Removes a tab.
  35489. *
  35490. * @return {NodeBuilder} A reference to this node builder.
  35491. */
  35492. removeFlowTab() {
  35493. this.tab = this.tab.slice( 0, -1 );
  35494. return this;
  35495. }
  35496. /**
  35497. * Gets the current flow data based on a Node.
  35498. *
  35499. * @param {Node} node - Node that the flow was started.
  35500. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35501. * @return {Object} The flow data.
  35502. */
  35503. getFlowData( node/*, shaderStage*/ ) {
  35504. return this.flowsData.get( node );
  35505. }
  35506. /**
  35507. * Executes the node flow based on a root node to generate the final shader code.
  35508. *
  35509. * @param {Node} node - The node to execute.
  35510. * @return {Object} The code flow.
  35511. */
  35512. flowNode( node ) {
  35513. const output = node.getNodeType( this );
  35514. const flowData = this.flowChildNode( node, output );
  35515. this.flowsData.set( node, flowData );
  35516. return flowData;
  35517. }
  35518. /**
  35519. * Includes a node in the current function node.
  35520. *
  35521. * @param {Node} node - The node to include.
  35522. * @returns {void}
  35523. */
  35524. addInclude( node ) {
  35525. if ( this.currentFunctionNode !== null ) {
  35526. this.currentFunctionNode.includes.push( node );
  35527. }
  35528. }
  35529. /**
  35530. * Returns the native shader operator name for a given generic name.
  35531. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  35532. *
  35533. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  35534. * @return {FunctionNode} The build function node.
  35535. */
  35536. buildFunctionNode( shaderNode ) {
  35537. const fn = new FunctionNode();
  35538. const previous = this.currentFunctionNode;
  35539. this.currentFunctionNode = fn;
  35540. fn.code = this.buildFunctionCode( shaderNode );
  35541. this.currentFunctionNode = previous;
  35542. return fn;
  35543. }
  35544. /**
  35545. * Generates a code flow based on a TSL function: Fn().
  35546. *
  35547. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  35548. * @return {Object}
  35549. */
  35550. flowShaderNode( shaderNode ) {
  35551. const layout = shaderNode.layout;
  35552. const inputs = {
  35553. [ Symbol.iterator ]() {
  35554. let index = 0;
  35555. const values = Object.values( this );
  35556. return {
  35557. next: () => ( {
  35558. value: values[ index ],
  35559. done: index ++ >= values.length
  35560. } )
  35561. };
  35562. }
  35563. };
  35564. for ( const input of layout.inputs ) {
  35565. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  35566. }
  35567. //
  35568. shaderNode.layout = null;
  35569. const callNode = shaderNode.call( inputs );
  35570. const flowData = this.flowStagesNode( callNode, layout.type );
  35571. shaderNode.layout = layout;
  35572. return flowData;
  35573. }
  35574. /**
  35575. * Executes the node in a specific build stage.
  35576. *
  35577. * This function can be used to arbitrarily execute the specified build stage
  35578. * outside of the standard build process. For instance, if a node's type depends
  35579. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  35580. * can be used to execute the setup build stage and access its generated nodes
  35581. * before the standard build process begins.
  35582. *
  35583. * @param {Node} node - The node to execute.
  35584. * @param {string} buildStage - The build stage to execute the node in.
  35585. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  35586. * @return {?(Node|string)} The result of the node build.
  35587. */
  35588. flowBuildStage( node, buildStage, output = null ) {
  35589. const previousBuildStage = this.getBuildStage();
  35590. this.setBuildStage( buildStage );
  35591. const result = node.build( this, output );
  35592. this.setBuildStage( previousBuildStage );
  35593. return result;
  35594. }
  35595. /**
  35596. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  35597. *
  35598. * @param {Node} node - The node to execute.
  35599. * @param {?string} output - Expected output type. For example 'vec3'.
  35600. * @return {Object}
  35601. */
  35602. flowStagesNode( node, output = null ) {
  35603. const previousFlow = this.flow;
  35604. const previousVars = this.vars;
  35605. const previousDeclarations = this.declarations;
  35606. const previousCache = this.cache;
  35607. const previousBuildStage = this.buildStage;
  35608. const previousStack = this.stack;
  35609. const flow = {
  35610. code: ''
  35611. };
  35612. this.flow = flow;
  35613. this.vars = {};
  35614. this.declarations = {};
  35615. this.cache = new NodeCache();
  35616. this.stack = stack();
  35617. for ( const buildStage of defaultBuildStages ) {
  35618. this.setBuildStage( buildStage );
  35619. flow.result = node.build( this, output );
  35620. }
  35621. flow.vars = this.getVars( this.shaderStage );
  35622. this.flow = previousFlow;
  35623. this.vars = previousVars;
  35624. this.declarations = previousDeclarations;
  35625. this.cache = previousCache;
  35626. this.stack = previousStack;
  35627. this.setBuildStage( previousBuildStage );
  35628. return flow;
  35629. }
  35630. /**
  35631. * Returns the native shader operator name for a given generic name.
  35632. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  35633. *
  35634. * @abstract
  35635. * @param {string} op - The operator name to resolve.
  35636. * @return {?string} The resolved operator name.
  35637. */
  35638. getFunctionOperator( /* op */ ) {
  35639. return null;
  35640. }
  35641. /**
  35642. * Builds the given shader node.
  35643. *
  35644. * @abstract
  35645. * @param {ShaderNodeInternal} shaderNode - The shader node.
  35646. * @return {string} The function code.
  35647. */
  35648. buildFunctionCode( /* shaderNode */ ) {
  35649. warn( 'Abstract function.' );
  35650. }
  35651. /**
  35652. * Generates a code flow based on a child Node.
  35653. *
  35654. * @param {Node} node - The node to execute.
  35655. * @param {?string} output - Expected output type. For example 'vec3'.
  35656. * @return {Object} The code flow.
  35657. */
  35658. flowChildNode( node, output = null ) {
  35659. const previousFlow = this.flow;
  35660. const flow = {
  35661. code: ''
  35662. };
  35663. this.flow = flow;
  35664. flow.result = node.build( this, output );
  35665. this.flow = previousFlow;
  35666. return flow;
  35667. }
  35668. /**
  35669. * Executes a flow of code in a different stage.
  35670. *
  35671. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  35672. * return the value in fragment-stage even if it is being executed in an input fragment.
  35673. *
  35674. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35675. * @param {Node} node - The node to execute.
  35676. * @param {?string} output - Expected output type. For example 'vec3'.
  35677. * @param {?string} propertyName - The property name to assign the result.
  35678. * @return {?(Object|Node)} The code flow or node.build() result.
  35679. */
  35680. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  35681. const previousTab = this.tab;
  35682. const previousCache = this.cache;
  35683. const previousShaderStage = this.shaderStage;
  35684. const previousContext = this.context;
  35685. this.setShaderStage( shaderStage );
  35686. const context = { ...this.context };
  35687. delete context.nodeBlock;
  35688. this.cache = this.globalCache;
  35689. this.tab = '\t';
  35690. this.context = context;
  35691. let result = null;
  35692. if ( this.buildStage === 'generate' ) {
  35693. const flowData = this.flowChildNode( node, output );
  35694. if ( propertyName !== null ) {
  35695. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  35696. }
  35697. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  35698. result = flowData;
  35699. } else {
  35700. result = node.build( this );
  35701. }
  35702. this.setShaderStage( previousShaderStage );
  35703. this.cache = previousCache;
  35704. this.tab = previousTab;
  35705. this.context = previousContext;
  35706. return result;
  35707. }
  35708. /**
  35709. * Returns an array holding all node attributes of this node builder.
  35710. *
  35711. * @return {Array<NodeAttribute>} The node attributes of this builder.
  35712. */
  35713. getAttributesArray() {
  35714. return this.attributes.concat( this.bufferAttributes );
  35715. }
  35716. /**
  35717. * Returns the attribute definitions as a shader string for the given shader stage.
  35718. *
  35719. * @abstract
  35720. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35721. * @return {string} The attribute code section.
  35722. */
  35723. getAttributes( /*shaderStage*/ ) {
  35724. warn( 'Abstract function.' );
  35725. }
  35726. /**
  35727. * Returns the varying definitions as a shader string for the given shader stage.
  35728. *
  35729. * @abstract
  35730. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35731. * @return {string} The varying code section.
  35732. */
  35733. getVaryings( /*shaderStage*/ ) {
  35734. warn( 'Abstract function.' );
  35735. }
  35736. /**
  35737. * Returns a single variable definition as a shader string for the given variable type and name.
  35738. *
  35739. * @param {string} type - The variable's type.
  35740. * @param {string} name - The variable's name.
  35741. * @param {?number} [count=null] - The array length.
  35742. * @return {string} The shader string.
  35743. */
  35744. getVar( type, name, count = null ) {
  35745. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  35746. }
  35747. /**
  35748. * Returns the variable definitions as a shader string for the given shader stage.
  35749. *
  35750. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35751. * @return {string} The variable code section.
  35752. */
  35753. getVars( shaderStage ) {
  35754. let snippet = '';
  35755. const vars = this.vars[ shaderStage ];
  35756. if ( vars !== undefined ) {
  35757. for ( const variable of vars ) {
  35758. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  35759. }
  35760. }
  35761. return snippet;
  35762. }
  35763. /**
  35764. * Returns the uniform definitions as a shader string for the given shader stage.
  35765. *
  35766. * @abstract
  35767. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35768. * @return {string} The uniform code section.
  35769. */
  35770. getUniforms( /*shaderStage*/ ) {
  35771. warn( 'Abstract function.' );
  35772. }
  35773. /**
  35774. * Returns the native code definitions as a shader string for the given shader stage.
  35775. *
  35776. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35777. * @return {string} The native code section.
  35778. */
  35779. getCodes( shaderStage ) {
  35780. const codes = this.codes[ shaderStage ];
  35781. let code = '';
  35782. if ( codes !== undefined ) {
  35783. for ( const nodeCode of codes ) {
  35784. code += nodeCode.code + '\n';
  35785. }
  35786. }
  35787. return code;
  35788. }
  35789. /**
  35790. * Returns the hash of this node builder.
  35791. *
  35792. * @return {string} The hash.
  35793. */
  35794. getHash() {
  35795. return this.vertexShader + this.fragmentShader + this.computeShader;
  35796. }
  35797. /**
  35798. * Sets the current shader stage.
  35799. *
  35800. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  35801. */
  35802. setShaderStage( shaderStage ) {
  35803. this.shaderStage = shaderStage;
  35804. }
  35805. /**
  35806. * Returns the current shader stage.
  35807. *
  35808. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  35809. */
  35810. getShaderStage() {
  35811. return this.shaderStage;
  35812. }
  35813. /**
  35814. * Sets the current build stage.
  35815. *
  35816. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  35817. */
  35818. setBuildStage( buildStage ) {
  35819. this.buildStage = buildStage;
  35820. }
  35821. /**
  35822. * Returns the current build stage.
  35823. *
  35824. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  35825. */
  35826. getBuildStage() {
  35827. return this.buildStage;
  35828. }
  35829. /**
  35830. * Controls the code build of the shader stages.
  35831. *
  35832. * @abstract
  35833. */
  35834. buildCode() {
  35835. warn( 'Abstract function.' );
  35836. }
  35837. /**
  35838. * Returns the current sub-build layer.
  35839. *
  35840. * @return {SubBuildNode} The current sub-build layers.
  35841. */
  35842. get subBuild() {
  35843. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  35844. }
  35845. /**
  35846. * Adds a sub-build layer to the node builder.
  35847. *
  35848. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  35849. */
  35850. addSubBuild( subBuild ) {
  35851. this.subBuildLayers.push( subBuild );
  35852. }
  35853. /**
  35854. * Removes the last sub-build layer from the node builder.
  35855. *
  35856. * @return {SubBuildNode} The removed sub-build layer.
  35857. */
  35858. removeSubBuild() {
  35859. return this.subBuildLayers.pop();
  35860. }
  35861. /**
  35862. * Returns the closest sub-build layer for the given data.
  35863. *
  35864. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  35865. * @return {?string} The closest sub-build name or null if none found.
  35866. */
  35867. getClosestSubBuild( data ) {
  35868. let subBuilds;
  35869. if ( data && data.isNode ) {
  35870. if ( data.isShaderCallNodeInternal ) {
  35871. subBuilds = data.shaderNode.subBuilds;
  35872. } else if ( data.isStackNode ) {
  35873. subBuilds = [ data.subBuild ];
  35874. } else {
  35875. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  35876. }
  35877. } else if ( data instanceof Set ) {
  35878. subBuilds = [ ...data ];
  35879. } else {
  35880. subBuilds = data;
  35881. }
  35882. if ( ! subBuilds ) return null;
  35883. const subBuildLayers = this.subBuildLayers;
  35884. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  35885. const subBuild = subBuilds[ i ];
  35886. if ( subBuildLayers.includes( subBuild ) ) {
  35887. return subBuild;
  35888. }
  35889. }
  35890. return null;
  35891. }
  35892. /**
  35893. * Returns the output node of a sub-build layer.
  35894. *
  35895. * @param {Node} node - The node to get the output from.
  35896. * @return {string} The output node name.
  35897. */
  35898. getSubBuildOutput( node ) {
  35899. return this.getSubBuildProperty( 'outputNode', node );
  35900. }
  35901. /**
  35902. * Returns the sub-build property name for the given property and node.
  35903. *
  35904. * @param {string} [property=''] - The property name.
  35905. * @param {?Node} [node=null] - The node to get the sub-build from.
  35906. * @return {string} The sub-build property name.
  35907. */
  35908. getSubBuildProperty( property = '', node = null ) {
  35909. let subBuild;
  35910. if ( node !== null ) {
  35911. subBuild = this.getClosestSubBuild( node );
  35912. } else {
  35913. subBuild = this.subBuildFn;
  35914. }
  35915. let result;
  35916. if ( subBuild ) {
  35917. result = property ? ( subBuild + '_' + property ) : subBuild;
  35918. } else {
  35919. result = property;
  35920. }
  35921. return result;
  35922. }
  35923. /**
  35924. * Central build method which controls the build for the given object.
  35925. *
  35926. * @return {NodeBuilder} A reference to this node builder.
  35927. */
  35928. build() {
  35929. const { object, material, renderer } = this;
  35930. if ( material !== null ) {
  35931. let nodeMaterial = renderer.library.fromMaterial( material );
  35932. if ( nodeMaterial === null ) {
  35933. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  35934. nodeMaterial = new NodeMaterial();
  35935. }
  35936. nodeMaterial.build( this );
  35937. } else {
  35938. this.addFlow( 'compute', object );
  35939. }
  35940. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  35941. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  35942. // generate() -> stage 3: generate shader
  35943. for ( const buildStage of defaultBuildStages ) {
  35944. this.setBuildStage( buildStage );
  35945. if ( this.context.vertex && this.context.vertex.isNode ) {
  35946. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  35947. }
  35948. for ( const shaderStage of shaderStages ) {
  35949. this.setShaderStage( shaderStage );
  35950. const flowNodes = this.flowNodes[ shaderStage ];
  35951. for ( const node of flowNodes ) {
  35952. if ( buildStage === 'generate' ) {
  35953. this.flowNode( node );
  35954. } else {
  35955. node.build( this );
  35956. }
  35957. }
  35958. }
  35959. }
  35960. this.setBuildStage( null );
  35961. this.setShaderStage( null );
  35962. // stage 4: build code for a specific output
  35963. this.buildCode();
  35964. this.buildUpdateNodes();
  35965. return this;
  35966. }
  35967. /**
  35968. * Returns a uniform representation which is later used for UBO generation and rendering.
  35969. *
  35970. * @param {NodeUniform} uniformNode - The uniform node.
  35971. * @param {string} type - The requested type.
  35972. * @return {Uniform} The uniform.
  35973. */
  35974. getNodeUniform( uniformNode, type ) {
  35975. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  35976. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  35977. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  35978. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  35979. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  35980. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  35981. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  35982. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  35983. throw new Error( `Uniform "${type}" not declared.` );
  35984. }
  35985. /**
  35986. * Formats the given shader snippet from a given type into another one. E.g.
  35987. * this method might be used to convert a simple float string `"1.0"` into a
  35988. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  35989. *
  35990. * @param {string} snippet - The shader snippet.
  35991. * @param {string} fromType - The source type.
  35992. * @param {string} toType - The target type.
  35993. * @return {string} The updated shader string.
  35994. */
  35995. format( snippet, fromType, toType ) {
  35996. fromType = this.getVectorType( fromType );
  35997. toType = this.getVectorType( toType );
  35998. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  35999. return snippet;
  36000. }
  36001. const fromTypeLength = this.getTypeLength( fromType );
  36002. const toTypeLength = this.getTypeLength( toType );
  36003. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  36004. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  36005. }
  36006. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  36007. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  36008. }
  36009. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  36010. // @TODO: ignore for now
  36011. return snippet;
  36012. }
  36013. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  36014. // @TODO: ignore for now
  36015. return snippet;
  36016. }
  36017. if ( fromTypeLength === toTypeLength ) {
  36018. return `${ this.getType( toType ) }( ${ snippet } )`;
  36019. }
  36020. if ( fromTypeLength > toTypeLength ) {
  36021. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  36022. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  36023. }
  36024. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  36025. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  36026. }
  36027. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  36028. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  36029. }
  36030. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  36031. // convert a number value to vector type, e.g:
  36032. // vec3( 1u ) -> vec3( float( 1u ) )
  36033. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  36034. }
  36035. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  36036. }
  36037. /**
  36038. * Returns a signature with the engine's current revision.
  36039. *
  36040. * @return {string} The signature.
  36041. */
  36042. getSignature() {
  36043. return `// Three.js r${ REVISION } - Node System\n`;
  36044. }
  36045. }
  36046. /**
  36047. * Management class for updating nodes. The module tracks metrics like
  36048. * the elapsed time, delta time, the render and frame ID to correctly
  36049. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  36050. * and {@link Node#updateAfter} depending on the node's configuration.
  36051. */
  36052. class NodeFrame {
  36053. /**
  36054. * Constructs a new node fame.
  36055. */
  36056. constructor() {
  36057. /**
  36058. * The elapsed time in seconds.
  36059. *
  36060. * @type {number}
  36061. * @default 0
  36062. */
  36063. this.time = 0;
  36064. /**
  36065. * The delta time in seconds.
  36066. *
  36067. * @type {number}
  36068. * @default 0
  36069. */
  36070. this.deltaTime = 0;
  36071. /**
  36072. * The frame ID.
  36073. *
  36074. * @type {number}
  36075. * @default 0
  36076. */
  36077. this.frameId = 0;
  36078. /**
  36079. * The render ID.
  36080. *
  36081. * @type {number}
  36082. * @default 0
  36083. */
  36084. this.renderId = 0;
  36085. /**
  36086. * Used to control the {@link Node#update} call.
  36087. *
  36088. * @type {WeakMap<Node, Object>}
  36089. */
  36090. this.updateMap = new WeakMap();
  36091. /**
  36092. * Used to control the {@link Node#updateBefore} call.
  36093. *
  36094. * @type {WeakMap<Node, Object>}
  36095. */
  36096. this.updateBeforeMap = new WeakMap();
  36097. /**
  36098. * Used to control the {@link Node#updateAfter} call.
  36099. *
  36100. * @type {WeakMap<Node, Object>}
  36101. */
  36102. this.updateAfterMap = new WeakMap();
  36103. /**
  36104. * A reference to the current renderer.
  36105. *
  36106. * @type {?Renderer}
  36107. * @default null
  36108. */
  36109. this.renderer = null;
  36110. /**
  36111. * A reference to the current material.
  36112. *
  36113. * @type {?Material}
  36114. * @default null
  36115. */
  36116. this.material = null;
  36117. /**
  36118. * A reference to the current camera.
  36119. *
  36120. * @type {?Camera}
  36121. * @default null
  36122. */
  36123. this.camera = null;
  36124. /**
  36125. * A reference to the current 3D object.
  36126. *
  36127. * @type {?Object3D}
  36128. * @default null
  36129. */
  36130. this.object = null;
  36131. /**
  36132. * A reference to the current scene.
  36133. *
  36134. * @type {?Scene}
  36135. * @default null
  36136. */
  36137. this.scene = null;
  36138. }
  36139. /**
  36140. * Returns a dictionary for a given node and update map which
  36141. * is used to correctly call node update methods per frame or render.
  36142. *
  36143. * @private
  36144. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  36145. * @param {Node} nodeRef - The reference to the current node.
  36146. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  36147. */
  36148. _getMaps( referenceMap, nodeRef ) {
  36149. let maps = referenceMap.get( nodeRef );
  36150. if ( maps === undefined ) {
  36151. maps = {
  36152. renderId: 0,
  36153. frameId: 0,
  36154. };
  36155. referenceMap.set( nodeRef, maps );
  36156. }
  36157. return maps;
  36158. }
  36159. /**
  36160. * This method executes the {@link Node#updateBefore} for the given node.
  36161. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  36162. * is only executed once per frame, render or object depending on the update
  36163. * type.
  36164. *
  36165. * @param {Node} node - The node that should be updated.
  36166. */
  36167. updateBeforeNode( node ) {
  36168. const updateType = node.getUpdateBeforeType();
  36169. const reference = node.updateReference( this );
  36170. if ( updateType === NodeUpdateType.FRAME ) {
  36171. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  36172. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  36173. if ( node.updateBefore( this ) !== false ) {
  36174. nodeUpdateBeforeMap.frameId = this.frameId;
  36175. }
  36176. }
  36177. } else if ( updateType === NodeUpdateType.RENDER ) {
  36178. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  36179. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  36180. if ( node.updateBefore( this ) !== false ) {
  36181. nodeUpdateBeforeMap.renderId = this.renderId;
  36182. }
  36183. }
  36184. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36185. node.updateBefore( this );
  36186. }
  36187. }
  36188. /**
  36189. * This method executes the {@link Node#updateAfter} for the given node.
  36190. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  36191. * is only executed once per frame, render or object depending on the update
  36192. * type.
  36193. *
  36194. * @param {Node} node - The node that should be updated.
  36195. */
  36196. updateAfterNode( node ) {
  36197. const updateType = node.getUpdateAfterType();
  36198. const reference = node.updateReference( this );
  36199. if ( updateType === NodeUpdateType.FRAME ) {
  36200. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  36201. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  36202. if ( node.updateAfter( this ) !== false ) {
  36203. nodeUpdateAfterMap.frameId = this.frameId;
  36204. }
  36205. }
  36206. } else if ( updateType === NodeUpdateType.RENDER ) {
  36207. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  36208. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  36209. if ( node.updateAfter( this ) !== false ) {
  36210. nodeUpdateAfterMap.renderId = this.renderId;
  36211. }
  36212. }
  36213. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36214. node.updateAfter( this );
  36215. }
  36216. }
  36217. /**
  36218. * This method executes the {@link Node#update} for the given node.
  36219. * It makes sure {@link Node#updateType} is honored meaning the update
  36220. * is only executed once per frame, render or object depending on the update
  36221. * type.
  36222. *
  36223. * @param {Node} node - The node that should be updated.
  36224. */
  36225. updateNode( node ) {
  36226. const updateType = node.getUpdateType();
  36227. const reference = node.updateReference( this );
  36228. if ( updateType === NodeUpdateType.FRAME ) {
  36229. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  36230. if ( nodeUpdateMap.frameId !== this.frameId ) {
  36231. if ( node.update( this ) !== false ) {
  36232. nodeUpdateMap.frameId = this.frameId;
  36233. }
  36234. }
  36235. } else if ( updateType === NodeUpdateType.RENDER ) {
  36236. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  36237. if ( nodeUpdateMap.renderId !== this.renderId ) {
  36238. if ( node.update( this ) !== false ) {
  36239. nodeUpdateMap.renderId = this.renderId;
  36240. }
  36241. }
  36242. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36243. node.update( this );
  36244. }
  36245. }
  36246. /**
  36247. * Updates the internal state of the node frame. This method is
  36248. * called by the renderer in its internal animation loop.
  36249. */
  36250. update() {
  36251. this.frameId ++;
  36252. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  36253. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  36254. this.lastTime = performance.now();
  36255. this.time += this.deltaTime;
  36256. }
  36257. }
  36258. /**
  36259. * Describes the input of a {@link NodeFunction}.
  36260. */
  36261. class NodeFunctionInput {
  36262. /**
  36263. * Constructs a new node function input.
  36264. *
  36265. * @param {string} type - The input type.
  36266. * @param {string} name - The input name.
  36267. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  36268. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  36269. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  36270. */
  36271. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  36272. /**
  36273. * The input type.
  36274. *
  36275. * @type {string}
  36276. */
  36277. this.type = type;
  36278. /**
  36279. * The input name.
  36280. *
  36281. * @type {string}
  36282. */
  36283. this.name = name;
  36284. /**
  36285. * If the input is an Array, count will be the length.
  36286. *
  36287. * @type {?number}
  36288. * @default null
  36289. */
  36290. this.count = count;
  36291. /**
  36292. *The parameter qualifier (only relevant for GLSL).
  36293. *
  36294. * @type {('in'|'out'|'inout')}
  36295. * @default ''
  36296. */
  36297. this.qualifier = qualifier;
  36298. /**
  36299. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  36300. *
  36301. * @type {boolean}
  36302. * @default false
  36303. */
  36304. this.isConst = isConst;
  36305. }
  36306. }
  36307. NodeFunctionInput.isNodeFunctionInput = true;
  36308. /**
  36309. * Module for representing directional lights as nodes.
  36310. *
  36311. * @augments AnalyticLightNode
  36312. */
  36313. class DirectionalLightNode extends AnalyticLightNode {
  36314. static get type() {
  36315. return 'DirectionalLightNode';
  36316. }
  36317. /**
  36318. * Constructs a new directional light node.
  36319. *
  36320. * @param {?DirectionalLight} [light=null] - The directional light source.
  36321. */
  36322. constructor( light = null ) {
  36323. super( light );
  36324. }
  36325. setupDirect() {
  36326. const lightColor = this.colorNode;
  36327. const lightDirection = lightTargetDirection( this.light );
  36328. return { lightDirection, lightColor };
  36329. }
  36330. }
  36331. const _matrix41 = /*@__PURE__*/ new Matrix4();
  36332. const _matrix42 = /*@__PURE__*/ new Matrix4();
  36333. let _ltcLib = null;
  36334. /**
  36335. * Module for representing rect area lights as nodes.
  36336. *
  36337. * @augments AnalyticLightNode
  36338. */
  36339. class RectAreaLightNode extends AnalyticLightNode {
  36340. static get type() {
  36341. return 'RectAreaLightNode';
  36342. }
  36343. /**
  36344. * Constructs a new rect area light node.
  36345. *
  36346. * @param {?RectAreaLight} [light=null] - The rect area light source.
  36347. */
  36348. constructor( light = null ) {
  36349. super( light );
  36350. /**
  36351. * Uniform node representing the half height of the are light.
  36352. *
  36353. * @type {UniformNode<vec3>}
  36354. */
  36355. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  36356. /**
  36357. * Uniform node representing the half width of the are light.
  36358. *
  36359. * @type {UniformNode<vec3>}
  36360. */
  36361. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  36362. /**
  36363. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  36364. * relies on `viewMatrix` which might vary per render call.
  36365. *
  36366. * @type {string}
  36367. * @default 'render'
  36368. */
  36369. this.updateType = NodeUpdateType.RENDER;
  36370. }
  36371. /**
  36372. * Overwritten to updated rect area light specific uniforms.
  36373. *
  36374. * @param {NodeFrame} frame - A reference to the current node frame.
  36375. */
  36376. update( frame ) {
  36377. super.update( frame );
  36378. const { light } = this;
  36379. const viewMatrix = frame.camera.matrixWorldInverse;
  36380. _matrix42.identity();
  36381. _matrix41.copy( light.matrixWorld );
  36382. _matrix41.premultiply( viewMatrix );
  36383. _matrix42.extractRotation( _matrix41 );
  36384. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  36385. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  36386. this.halfWidth.value.applyMatrix4( _matrix42 );
  36387. this.halfHeight.value.applyMatrix4( _matrix42 );
  36388. }
  36389. setupDirectRectArea( builder ) {
  36390. let ltc_1, ltc_2;
  36391. if ( builder.isAvailable( 'float32Filterable' ) ) {
  36392. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  36393. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  36394. } else {
  36395. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  36396. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  36397. }
  36398. const { colorNode, light } = this;
  36399. const lightPosition = lightViewPosition( light );
  36400. return {
  36401. lightColor: colorNode,
  36402. lightPosition,
  36403. halfWidth: this.halfWidth,
  36404. halfHeight: this.halfHeight,
  36405. ltc_1,
  36406. ltc_2
  36407. };
  36408. }
  36409. /**
  36410. * Used to configure the internal BRDF approximation texture data.
  36411. *
  36412. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  36413. */
  36414. static setLTC( ltc ) {
  36415. _ltcLib = ltc;
  36416. }
  36417. }
  36418. /**
  36419. * Module for representing spot lights as nodes.
  36420. *
  36421. * @augments AnalyticLightNode
  36422. */
  36423. class SpotLightNode extends AnalyticLightNode {
  36424. static get type() {
  36425. return 'SpotLightNode';
  36426. }
  36427. /**
  36428. * Constructs a new spot light node.
  36429. *
  36430. * @param {?SpotLight} [light=null] - The spot light source.
  36431. */
  36432. constructor( light = null ) {
  36433. super( light );
  36434. /**
  36435. * Uniform node representing the cone cosine.
  36436. *
  36437. * @type {UniformNode<float>}
  36438. */
  36439. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  36440. /**
  36441. * Uniform node representing the penumbra cosine.
  36442. *
  36443. * @type {UniformNode<float>}
  36444. */
  36445. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  36446. /**
  36447. * Uniform node representing the cutoff distance.
  36448. *
  36449. * @type {UniformNode<float>}
  36450. */
  36451. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  36452. /**
  36453. * Uniform node representing the decay exponent.
  36454. *
  36455. * @type {UniformNode<float>}
  36456. */
  36457. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  36458. /**
  36459. * Uniform node representing the light color.
  36460. *
  36461. * @type {UniformNode<Color>}
  36462. */
  36463. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  36464. }
  36465. /**
  36466. * Overwritten to updated spot light specific uniforms.
  36467. *
  36468. * @param {NodeFrame} frame - A reference to the current node frame.
  36469. */
  36470. update( frame ) {
  36471. super.update( frame );
  36472. const { light } = this;
  36473. this.coneCosNode.value = Math.cos( light.angle );
  36474. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  36475. this.cutoffDistanceNode.value = light.distance;
  36476. this.decayExponentNode.value = light.decay;
  36477. }
  36478. /**
  36479. * Computes the spot attenuation for the given angle.
  36480. *
  36481. * @param {NodeBuilder} builder - The node builder.
  36482. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  36483. * @return {Node<float>} The spot attenuation.
  36484. */
  36485. getSpotAttenuation( builder, angleCosine ) {
  36486. const { coneCosNode, penumbraCosNode } = this;
  36487. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  36488. }
  36489. getLightCoord( builder ) {
  36490. const properties = builder.getNodeProperties( this );
  36491. let projectionUV = properties.projectionUV;
  36492. if ( projectionUV === undefined ) {
  36493. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  36494. properties.projectionUV = projectionUV;
  36495. }
  36496. return projectionUV;
  36497. }
  36498. setupDirect( builder ) {
  36499. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  36500. const lightVector = this.getLightVector( builder );
  36501. const lightDirection = lightVector.normalize();
  36502. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  36503. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  36504. const lightDistance = lightVector.length();
  36505. const lightAttenuation = getDistanceAttenuation( {
  36506. lightDistance,
  36507. cutoffDistance: cutoffDistanceNode,
  36508. decayExponent: decayExponentNode
  36509. } );
  36510. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  36511. let projected, lightCoord;
  36512. if ( light.colorNode ) {
  36513. lightCoord = this.getLightCoord( builder );
  36514. projected = light.colorNode( lightCoord );
  36515. } else if ( light.map ) {
  36516. lightCoord = this.getLightCoord( builder );
  36517. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  36518. }
  36519. if ( projected ) {
  36520. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  36521. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  36522. }
  36523. return { lightColor, lightDirection };
  36524. }
  36525. }
  36526. /**
  36527. * An IES version of the default spot light node.
  36528. *
  36529. * @augments SpotLightNode
  36530. */
  36531. class IESSpotLightNode extends SpotLightNode {
  36532. static get type() {
  36533. return 'IESSpotLightNode';
  36534. }
  36535. /**
  36536. * Overwrites the default implementation to compute an IES conform spot attenuation.
  36537. *
  36538. * @param {NodeBuilder} builder - The node builder.
  36539. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  36540. * @return {Node<float>} The spot attenuation.
  36541. */
  36542. getSpotAttenuation( builder, angleCosine ) {
  36543. const iesMap = this.light.iesMap;
  36544. let spotAttenuation = null;
  36545. if ( iesMap && iesMap.isTexture === true ) {
  36546. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  36547. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  36548. } else {
  36549. spotAttenuation = super.getSpotAttenuation( angleCosine );
  36550. }
  36551. return spotAttenuation;
  36552. }
  36553. }
  36554. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  36555. const d = p.abs().sub( b );
  36556. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  36557. } );
  36558. /**
  36559. * An implementation of a projector light node.
  36560. *
  36561. * @augments SpotLightNode
  36562. */
  36563. class ProjectorLightNode extends SpotLightNode {
  36564. static get type() {
  36565. return 'ProjectorLightNode';
  36566. }
  36567. update( frame ) {
  36568. super.update( frame );
  36569. const light = this.light;
  36570. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  36571. if ( light.aspect === null ) {
  36572. let aspect = 1;
  36573. if ( light.map !== null ) {
  36574. aspect = light.map.width / light.map.height;
  36575. }
  36576. light.shadow.aspect = aspect;
  36577. } else {
  36578. light.shadow.aspect = light.aspect;
  36579. }
  36580. }
  36581. /**
  36582. * Overwrites the default implementation to compute projection attenuation.
  36583. *
  36584. * @param {NodeBuilder} builder - The node builder.
  36585. * @return {Node<float>} The spot attenuation.
  36586. */
  36587. getSpotAttenuation( builder ) {
  36588. const attenuation = float( 0 );
  36589. const penumbraCos = this.penumbraCosNode;
  36590. // compute the fragment's position in the light's clip space
  36591. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  36592. // the sign of w determines whether the current fragment is in front or behind the light.
  36593. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  36594. If( spotLightCoord.w.greaterThan( 0 ), () => {
  36595. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  36596. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  36597. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  36598. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  36599. } );
  36600. return attenuation;
  36601. }
  36602. }
  36603. /**
  36604. * Module for representing ambient lights as nodes.
  36605. *
  36606. * @augments AnalyticLightNode
  36607. */
  36608. class AmbientLightNode extends AnalyticLightNode {
  36609. static get type() {
  36610. return 'AmbientLightNode';
  36611. }
  36612. /**
  36613. * Constructs a new ambient light node.
  36614. *
  36615. * @param {?AmbientLight} [light=null] - The ambient light source.
  36616. */
  36617. constructor( light = null ) {
  36618. super( light );
  36619. }
  36620. setup( { context } ) {
  36621. context.irradiance.addAssign( this.colorNode );
  36622. }
  36623. }
  36624. /**
  36625. * Module for representing hemisphere lights as nodes.
  36626. *
  36627. * @augments AnalyticLightNode
  36628. */
  36629. class HemisphereLightNode extends AnalyticLightNode {
  36630. static get type() {
  36631. return 'HemisphereLightNode';
  36632. }
  36633. /**
  36634. * Constructs a new hemisphere light node.
  36635. *
  36636. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  36637. */
  36638. constructor( light = null ) {
  36639. super( light );
  36640. /**
  36641. * Uniform node representing the light's position.
  36642. *
  36643. * @type {UniformNode<vec3>}
  36644. */
  36645. this.lightPositionNode = lightPosition( light );
  36646. /**
  36647. * A node representing the light's direction.
  36648. *
  36649. * @type {Node<vec3>}
  36650. */
  36651. this.lightDirectionNode = this.lightPositionNode.normalize();
  36652. /**
  36653. * Uniform node representing the light's ground color.
  36654. *
  36655. * @type {UniformNode<vec3>}
  36656. */
  36657. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  36658. }
  36659. /**
  36660. * Overwritten to updated hemisphere light specific uniforms.
  36661. *
  36662. * @param {NodeFrame} frame - A reference to the current node frame.
  36663. */
  36664. update( frame ) {
  36665. const { light } = this;
  36666. super.update( frame );
  36667. this.lightPositionNode.object3d = light;
  36668. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  36669. }
  36670. setup( builder ) {
  36671. const { colorNode, groundColorNode, lightDirectionNode } = this;
  36672. const dotNL = normalWorld.dot( lightDirectionNode );
  36673. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  36674. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  36675. builder.context.irradiance.addAssign( irradiance );
  36676. }
  36677. }
  36678. /**
  36679. * Module for representing light probes as nodes.
  36680. *
  36681. * @augments AnalyticLightNode
  36682. */
  36683. class LightProbeNode extends AnalyticLightNode {
  36684. static get type() {
  36685. return 'LightProbeNode';
  36686. }
  36687. /**
  36688. * Constructs a new light probe node.
  36689. *
  36690. * @param {?LightProbe} [light=null] - The light probe.
  36691. */
  36692. constructor( light = null ) {
  36693. super( light );
  36694. const array = [];
  36695. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  36696. /**
  36697. * Light probe represented as a uniform of spherical harmonics.
  36698. *
  36699. * @type {UniformArrayNode}
  36700. */
  36701. this.lightProbe = uniformArray( array );
  36702. }
  36703. /**
  36704. * Overwritten to updated light probe specific uniforms.
  36705. *
  36706. * @param {NodeFrame} frame - A reference to the current node frame.
  36707. */
  36708. update( frame ) {
  36709. const { light } = this;
  36710. super.update( frame );
  36711. //
  36712. for ( let i = 0; i < 9; i ++ ) {
  36713. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  36714. }
  36715. }
  36716. setup( builder ) {
  36717. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  36718. builder.context.irradiance.addAssign( irradiance );
  36719. }
  36720. }
  36721. /**
  36722. * Base class for node parsers. A derived parser must be implemented
  36723. * for each supported native shader language.
  36724. */
  36725. class NodeParser {
  36726. /**
  36727. * The method parses the given native code an returns a node function.
  36728. *
  36729. * @abstract
  36730. * @param {string} source - The native shader code.
  36731. * @return {NodeFunction} A node function.
  36732. */
  36733. parseFunction( /*source*/ ) {
  36734. warn( 'Abstract function.' );
  36735. }
  36736. }
  36737. /**
  36738. * Base class for node functions. A derived module must be implemented
  36739. * for each supported native shader language. Similar to other `Node*` modules,
  36740. * this class is only relevant during the building process and not used
  36741. * in user-level code.
  36742. */
  36743. class NodeFunction {
  36744. /**
  36745. * Constructs a new node function.
  36746. *
  36747. * @param {string} type - The node type. This type is the return type of the node function.
  36748. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  36749. * @param {string} [name=''] - The function's name.
  36750. * @param {string} [precision=''] - The precision qualifier.
  36751. */
  36752. constructor( type, inputs, name = '', precision = '' ) {
  36753. /**
  36754. * The node type. This type is the return type of the node function.
  36755. *
  36756. * @type {string}
  36757. */
  36758. this.type = type;
  36759. /**
  36760. * The function's inputs.
  36761. *
  36762. * @type {Array<NodeFunctionInput>}
  36763. */
  36764. this.inputs = inputs;
  36765. /**
  36766. * The name of the uniform.
  36767. *
  36768. * @type {string}
  36769. * @default ''
  36770. */
  36771. this.name = name;
  36772. /**
  36773. * The precision qualifier.
  36774. *
  36775. * @type {string}
  36776. * @default ''
  36777. */
  36778. this.precision = precision;
  36779. }
  36780. /**
  36781. * This method returns the native code of the node function.
  36782. *
  36783. * @abstract
  36784. * @param {string} name - The function's name.
  36785. * @return {string} A shader code.
  36786. */
  36787. getCode( /*name = this.name*/ ) {
  36788. warn( 'Abstract function.' );
  36789. }
  36790. }
  36791. NodeFunction.isNodeFunction = true;
  36792. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  36793. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  36794. const pragmaMain = '#pragma main';
  36795. const parse$1 = ( source ) => {
  36796. source = source.trim();
  36797. const pragmaMainIndex = source.indexOf( pragmaMain );
  36798. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  36799. const declaration = mainCode.match( declarationRegexp$1 );
  36800. if ( declaration !== null && declaration.length === 5 ) {
  36801. // tokenizer
  36802. const inputsCode = declaration[ 4 ];
  36803. const propsMatches = [];
  36804. let nameMatch = null;
  36805. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  36806. propsMatches.push( nameMatch );
  36807. }
  36808. // parser
  36809. const inputs = [];
  36810. let i = 0;
  36811. while ( i < propsMatches.length ) {
  36812. const isConst = propsMatches[ i ][ 0 ] === 'const';
  36813. if ( isConst === true ) {
  36814. i ++;
  36815. }
  36816. let qualifier = propsMatches[ i ][ 0 ];
  36817. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  36818. i ++;
  36819. } else {
  36820. qualifier = '';
  36821. }
  36822. const type = propsMatches[ i ++ ][ 0 ];
  36823. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  36824. if ( Number.isNaN( count ) === false ) i ++;
  36825. else count = null;
  36826. const name = propsMatches[ i ++ ][ 0 ];
  36827. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  36828. }
  36829. //
  36830. const blockCode = mainCode.substring( declaration[ 0 ].length );
  36831. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  36832. const type = declaration[ 2 ];
  36833. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  36834. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  36835. return {
  36836. type,
  36837. inputs,
  36838. name,
  36839. precision,
  36840. inputsCode,
  36841. blockCode,
  36842. headerCode
  36843. };
  36844. } else {
  36845. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  36846. }
  36847. };
  36848. /**
  36849. * This class represents a GLSL node function.
  36850. *
  36851. * @augments NodeFunction
  36852. */
  36853. class GLSLNodeFunction extends NodeFunction {
  36854. /**
  36855. * Constructs a new GLSL node function.
  36856. *
  36857. * @param {string} source - The GLSL source.
  36858. */
  36859. constructor( source ) {
  36860. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  36861. super( type, inputs, name, precision );
  36862. this.inputsCode = inputsCode;
  36863. this.blockCode = blockCode;
  36864. this.headerCode = headerCode;
  36865. }
  36866. /**
  36867. * This method returns the GLSL code of the node function.
  36868. *
  36869. * @param {string} [name=this.name] - The function's name.
  36870. * @return {string} The shader code.
  36871. */
  36872. getCode( name = this.name ) {
  36873. let code;
  36874. const blockCode = this.blockCode;
  36875. if ( blockCode !== '' ) {
  36876. const { type, inputsCode, headerCode, precision } = this;
  36877. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  36878. if ( precision !== '' ) {
  36879. declarationCode = `${ precision } ${ declarationCode }`;
  36880. }
  36881. code = headerCode + declarationCode + blockCode;
  36882. } else {
  36883. // interface function
  36884. code = '';
  36885. }
  36886. return code;
  36887. }
  36888. }
  36889. /**
  36890. * A GLSL node parser.
  36891. *
  36892. * @augments NodeParser
  36893. */
  36894. class GLSLNodeParser extends NodeParser {
  36895. /**
  36896. * The method parses the given GLSL code an returns a node function.
  36897. *
  36898. * @param {string} source - The GLSL code.
  36899. * @return {GLSLNodeFunction} A node function.
  36900. */
  36901. parseFunction( source ) {
  36902. return new GLSLNodeFunction( source );
  36903. }
  36904. }
  36905. const _outputNodeMap = new WeakMap();
  36906. const _chainKeys$2 = [];
  36907. const _cacheKeyValues = [];
  36908. /**
  36909. * This renderer module manages node-related objects and is the
  36910. * primary interface between the renderer and the node system.
  36911. *
  36912. * @private
  36913. * @augments DataMap
  36914. */
  36915. class Nodes extends DataMap {
  36916. /**
  36917. * Constructs a new nodes management component.
  36918. *
  36919. * @param {Renderer} renderer - The renderer.
  36920. * @param {Backend} backend - The renderer's backend.
  36921. */
  36922. constructor( renderer, backend ) {
  36923. super();
  36924. /**
  36925. * The renderer.
  36926. *
  36927. * @type {Renderer}
  36928. */
  36929. this.renderer = renderer;
  36930. /**
  36931. * The renderer's backend.
  36932. *
  36933. * @type {Backend}
  36934. */
  36935. this.backend = backend;
  36936. /**
  36937. * The node frame.
  36938. *
  36939. * @type {Renderer}
  36940. */
  36941. this.nodeFrame = new NodeFrame();
  36942. /**
  36943. * A cache for managing node builder states.
  36944. *
  36945. * @type {Map<number,NodeBuilderState>}
  36946. */
  36947. this.nodeBuilderCache = new Map();
  36948. /**
  36949. * A cache for managing data cache key data.
  36950. *
  36951. * @type {ChainMap}
  36952. */
  36953. this.callHashCache = new ChainMap();
  36954. /**
  36955. * A cache for managing node uniforms group data.
  36956. *
  36957. * @type {ChainMap}
  36958. */
  36959. this.groupsData = new ChainMap();
  36960. /**
  36961. * A cache for managing node objects of
  36962. * scene properties like fog or environments.
  36963. *
  36964. * @type {Object<string,WeakMap>}
  36965. */
  36966. this.cacheLib = {};
  36967. }
  36968. /**
  36969. * Returns `true` if the given node uniforms group must be updated or not.
  36970. *
  36971. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  36972. * @return {boolean} Whether the node uniforms group requires an update or not.
  36973. */
  36974. updateGroup( nodeUniformsGroup ) {
  36975. const groupNode = nodeUniformsGroup.groupNode;
  36976. const name = groupNode.name;
  36977. // objectGroup is always updated
  36978. if ( name === objectGroup.name ) return true;
  36979. // renderGroup is updated once per render/compute call
  36980. if ( name === renderGroup.name ) {
  36981. const uniformsGroupData = this.get( nodeUniformsGroup );
  36982. const renderId = this.nodeFrame.renderId;
  36983. if ( uniformsGroupData.renderId !== renderId ) {
  36984. uniformsGroupData.renderId = renderId;
  36985. return true;
  36986. }
  36987. return false;
  36988. }
  36989. // frameGroup is updated once per frame
  36990. if ( name === frameGroup.name ) {
  36991. const uniformsGroupData = this.get( nodeUniformsGroup );
  36992. const frameId = this.nodeFrame.frameId;
  36993. if ( uniformsGroupData.frameId !== frameId ) {
  36994. uniformsGroupData.frameId = frameId;
  36995. return true;
  36996. }
  36997. return false;
  36998. }
  36999. // other groups are updated just when groupNode.needsUpdate is true
  37000. _chainKeys$2[ 0 ] = groupNode;
  37001. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  37002. let groupData = this.groupsData.get( _chainKeys$2 );
  37003. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  37004. _chainKeys$2.length = 0;
  37005. if ( groupData.version !== groupNode.version ) {
  37006. groupData.version = groupNode.version;
  37007. return true;
  37008. }
  37009. return false;
  37010. }
  37011. /**
  37012. * Returns the cache key for the given render object.
  37013. *
  37014. * @param {RenderObject} renderObject - The render object.
  37015. * @return {number} The cache key.
  37016. */
  37017. getForRenderCacheKey( renderObject ) {
  37018. return renderObject.initialCacheKey;
  37019. }
  37020. /**
  37021. * Returns a node builder state for the given render object.
  37022. *
  37023. * @param {RenderObject} renderObject - The render object.
  37024. * @return {NodeBuilderState} The node builder state.
  37025. */
  37026. getForRender( renderObject ) {
  37027. const renderObjectData = this.get( renderObject );
  37028. let nodeBuilderState = renderObjectData.nodeBuilderState;
  37029. if ( nodeBuilderState === undefined ) {
  37030. const { nodeBuilderCache } = this;
  37031. const cacheKey = this.getForRenderCacheKey( renderObject );
  37032. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  37033. if ( nodeBuilderState === undefined ) {
  37034. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  37035. nodeBuilder.scene = renderObject.scene;
  37036. nodeBuilder.material = renderObject.material;
  37037. nodeBuilder.camera = renderObject.camera;
  37038. nodeBuilder.context.material = renderObject.material;
  37039. nodeBuilder.lightsNode = renderObject.lightsNode;
  37040. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  37041. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  37042. nodeBuilder.clippingContext = renderObject.clippingContext;
  37043. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  37044. nodeBuilder.enableMultiview();
  37045. }
  37046. nodeBuilder.build();
  37047. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37048. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  37049. }
  37050. nodeBuilderState.usedTimes ++;
  37051. renderObjectData.nodeBuilderState = nodeBuilderState;
  37052. }
  37053. return nodeBuilderState;
  37054. }
  37055. /**
  37056. * Deletes the given object from the internal data map
  37057. *
  37058. * @param {any} object - The object to delete.
  37059. * @return {?Object} The deleted dictionary.
  37060. */
  37061. delete( object ) {
  37062. if ( object.isRenderObject ) {
  37063. const nodeBuilderState = this.get( object ).nodeBuilderState;
  37064. nodeBuilderState.usedTimes --;
  37065. if ( nodeBuilderState.usedTimes === 0 ) {
  37066. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  37067. }
  37068. }
  37069. return super.delete( object );
  37070. }
  37071. /**
  37072. * Returns a node builder state for the given compute node.
  37073. *
  37074. * @param {Node} computeNode - The compute node.
  37075. * @return {NodeBuilderState} The node builder state.
  37076. */
  37077. getForCompute( computeNode ) {
  37078. const computeData = this.get( computeNode );
  37079. let nodeBuilderState = computeData.nodeBuilderState;
  37080. if ( nodeBuilderState === undefined ) {
  37081. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  37082. nodeBuilder.build();
  37083. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37084. computeData.nodeBuilderState = nodeBuilderState;
  37085. }
  37086. return nodeBuilderState;
  37087. }
  37088. /**
  37089. * Creates a node builder state for the given node builder.
  37090. *
  37091. * @private
  37092. * @param {NodeBuilder} nodeBuilder - The node builder.
  37093. * @return {NodeBuilderState} The node builder state.
  37094. */
  37095. _createNodeBuilderState( nodeBuilder ) {
  37096. return new NodeBuilderState(
  37097. nodeBuilder.vertexShader,
  37098. nodeBuilder.fragmentShader,
  37099. nodeBuilder.computeShader,
  37100. nodeBuilder.getAttributesArray(),
  37101. nodeBuilder.getBindings(),
  37102. nodeBuilder.updateNodes,
  37103. nodeBuilder.updateBeforeNodes,
  37104. nodeBuilder.updateAfterNodes,
  37105. nodeBuilder.observer,
  37106. nodeBuilder.transforms
  37107. );
  37108. }
  37109. /**
  37110. * Returns an environment node for the current configured
  37111. * scene environment.
  37112. *
  37113. * @param {Scene} scene - The scene.
  37114. * @return {Node} A node representing the current scene environment.
  37115. */
  37116. getEnvironmentNode( scene ) {
  37117. this.updateEnvironment( scene );
  37118. let environmentNode = null;
  37119. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  37120. environmentNode = scene.environmentNode;
  37121. } else {
  37122. const sceneData = this.get( scene );
  37123. if ( sceneData.environmentNode ) {
  37124. environmentNode = sceneData.environmentNode;
  37125. }
  37126. }
  37127. return environmentNode;
  37128. }
  37129. /**
  37130. * Returns a background node for the current configured
  37131. * scene background.
  37132. *
  37133. * @param {Scene} scene - The scene.
  37134. * @return {Node} A node representing the current scene background.
  37135. */
  37136. getBackgroundNode( scene ) {
  37137. this.updateBackground( scene );
  37138. let backgroundNode = null;
  37139. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  37140. backgroundNode = scene.backgroundNode;
  37141. } else {
  37142. const sceneData = this.get( scene );
  37143. if ( sceneData.backgroundNode ) {
  37144. backgroundNode = sceneData.backgroundNode;
  37145. }
  37146. }
  37147. return backgroundNode;
  37148. }
  37149. /**
  37150. * Returns a fog node for the current configured scene fog.
  37151. *
  37152. * @param {Scene} scene - The scene.
  37153. * @return {Node} A node representing the current scene fog.
  37154. */
  37155. getFogNode( scene ) {
  37156. this.updateFog( scene );
  37157. return scene.fogNode || this.get( scene ).fogNode || null;
  37158. }
  37159. /**
  37160. * Returns a cache key for the given scene and lights node.
  37161. * This key is used by `RenderObject` as a part of the dynamic
  37162. * cache key (a key that must be checked every time the render
  37163. * objects is drawn).
  37164. *
  37165. * @param {Scene} scene - The scene.
  37166. * @param {LightsNode} lightsNode - The lights node.
  37167. * @return {number} The cache key.
  37168. */
  37169. getCacheKey( scene, lightsNode ) {
  37170. _chainKeys$2[ 0 ] = scene;
  37171. _chainKeys$2[ 1 ] = lightsNode;
  37172. const callId = this.renderer.info.calls;
  37173. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  37174. if ( cacheKeyData.callId !== callId ) {
  37175. const environmentNode = this.getEnvironmentNode( scene );
  37176. const fogNode = this.getFogNode( scene );
  37177. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  37178. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  37179. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  37180. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  37181. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  37182. cacheKeyData.callId = callId;
  37183. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  37184. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  37185. _cacheKeyValues.length = 0;
  37186. }
  37187. _chainKeys$2.length = 0;
  37188. return cacheKeyData.cacheKey;
  37189. }
  37190. /**
  37191. * A boolean that indicates whether tone mapping should be enabled
  37192. * or not.
  37193. *
  37194. * @type {boolean}
  37195. */
  37196. get isToneMappingState() {
  37197. return this.renderer.getRenderTarget() ? false : true;
  37198. }
  37199. /**
  37200. * If a scene background is configured, this method makes sure to
  37201. * represent the background with a corresponding node-based implementation.
  37202. *
  37203. * @param {Scene} scene - The scene.
  37204. */
  37205. updateBackground( scene ) {
  37206. const sceneData = this.get( scene );
  37207. const background = scene.background;
  37208. if ( background ) {
  37209. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  37210. if ( sceneData.background !== background || forceUpdate ) {
  37211. const backgroundNode = this.getCacheNode( 'background', background, () => {
  37212. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  37213. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  37214. return pmremTexture( background );
  37215. } else {
  37216. let envMap;
  37217. if ( background.isCubeTexture === true ) {
  37218. envMap = cubeTexture( background );
  37219. } else {
  37220. envMap = texture( background );
  37221. }
  37222. return cubeMapNode( envMap );
  37223. }
  37224. } else if ( background.isTexture === true ) {
  37225. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  37226. } else if ( background.isColor !== true ) {
  37227. error( 'WebGPUNodes: Unsupported background configuration.', background );
  37228. }
  37229. }, forceUpdate );
  37230. sceneData.backgroundNode = backgroundNode;
  37231. sceneData.background = background;
  37232. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  37233. }
  37234. } else if ( sceneData.backgroundNode ) {
  37235. delete sceneData.backgroundNode;
  37236. delete sceneData.background;
  37237. }
  37238. }
  37239. /**
  37240. * This method is part of the caching of nodes which are used to represents the
  37241. * scene's background, fog or environment.
  37242. *
  37243. * @param {string} type - The type of object to cache.
  37244. * @param {Object} object - The object.
  37245. * @param {Function} callback - A callback that produces a node representation for the given object.
  37246. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  37247. * @return {Node} The node representation.
  37248. */
  37249. getCacheNode( type, object, callback, forceUpdate = false ) {
  37250. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  37251. let node = nodeCache.get( object );
  37252. if ( node === undefined || forceUpdate ) {
  37253. node = callback();
  37254. nodeCache.set( object, node );
  37255. }
  37256. return node;
  37257. }
  37258. /**
  37259. * If a scene fog is configured, this method makes sure to
  37260. * represent the fog with a corresponding node-based implementation.
  37261. *
  37262. * @param {Scene} scene - The scene.
  37263. */
  37264. updateFog( scene ) {
  37265. const sceneData = this.get( scene );
  37266. const sceneFog = scene.fog;
  37267. if ( sceneFog ) {
  37268. if ( sceneData.fog !== sceneFog ) {
  37269. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  37270. if ( sceneFog.isFogExp2 ) {
  37271. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  37272. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  37273. return fog( color, densityFogFactor( density ) );
  37274. } else if ( sceneFog.isFog ) {
  37275. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  37276. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  37277. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  37278. return fog( color, rangeFogFactor( near, far ) );
  37279. } else {
  37280. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  37281. }
  37282. } );
  37283. sceneData.fogNode = fogNode;
  37284. sceneData.fog = sceneFog;
  37285. }
  37286. } else {
  37287. delete sceneData.fogNode;
  37288. delete sceneData.fog;
  37289. }
  37290. }
  37291. /**
  37292. * If a scene environment is configured, this method makes sure to
  37293. * represent the environment with a corresponding node-based implementation.
  37294. *
  37295. * @param {Scene} scene - The scene.
  37296. */
  37297. updateEnvironment( scene ) {
  37298. const sceneData = this.get( scene );
  37299. const environment = scene.environment;
  37300. if ( environment ) {
  37301. if ( sceneData.environment !== environment ) {
  37302. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  37303. if ( environment.isCubeTexture === true ) {
  37304. return cubeTexture( environment );
  37305. } else if ( environment.isTexture === true ) {
  37306. return texture( environment );
  37307. } else {
  37308. error( 'Nodes: Unsupported environment configuration.', environment );
  37309. }
  37310. } );
  37311. sceneData.environmentNode = environmentNode;
  37312. sceneData.environment = environment;
  37313. }
  37314. } else if ( sceneData.environmentNode ) {
  37315. delete sceneData.environmentNode;
  37316. delete sceneData.environment;
  37317. }
  37318. }
  37319. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  37320. const nodeFrame = this.nodeFrame;
  37321. nodeFrame.renderer = renderer;
  37322. nodeFrame.scene = scene;
  37323. nodeFrame.object = object;
  37324. nodeFrame.camera = camera;
  37325. nodeFrame.material = material;
  37326. return nodeFrame;
  37327. }
  37328. getNodeFrameForRender( renderObject ) {
  37329. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  37330. }
  37331. /**
  37332. * Returns the current output cache key.
  37333. *
  37334. * @return {string} The output cache key.
  37335. */
  37336. getOutputCacheKey() {
  37337. const renderer = this.renderer;
  37338. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  37339. }
  37340. /**
  37341. * Checks if the output configuration (tone mapping and color space) for
  37342. * the given target has changed.
  37343. *
  37344. * @param {Texture} outputTarget - The output target.
  37345. * @return {boolean} Whether the output configuration has changed or not.
  37346. */
  37347. hasOutputChange( outputTarget ) {
  37348. const cacheKey = _outputNodeMap.get( outputTarget );
  37349. return cacheKey !== this.getOutputCacheKey();
  37350. }
  37351. /**
  37352. * Returns a node that represents the output configuration (tone mapping and
  37353. * color space) for the current target.
  37354. *
  37355. * @param {Texture} outputTarget - The output target.
  37356. * @return {Node} The output node.
  37357. */
  37358. getOutputNode( outputTarget ) {
  37359. const renderer = this.renderer;
  37360. const cacheKey = this.getOutputCacheKey();
  37361. const output = outputTarget.isArrayTexture ?
  37362. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  37363. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  37364. _outputNodeMap.set( outputTarget, cacheKey );
  37365. return output;
  37366. }
  37367. /**
  37368. * Triggers the call of `updateBefore()` methods
  37369. * for all nodes of the given render object.
  37370. *
  37371. * @param {RenderObject} renderObject - The render object.
  37372. */
  37373. updateBefore( renderObject ) {
  37374. const nodeBuilder = renderObject.getNodeBuilderState();
  37375. for ( const node of nodeBuilder.updateBeforeNodes ) {
  37376. // update frame state for each node
  37377. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  37378. }
  37379. }
  37380. /**
  37381. * Triggers the call of `updateAfter()` methods
  37382. * for all nodes of the given render object.
  37383. *
  37384. * @param {RenderObject} renderObject - The render object.
  37385. */
  37386. updateAfter( renderObject ) {
  37387. const nodeBuilder = renderObject.getNodeBuilderState();
  37388. for ( const node of nodeBuilder.updateAfterNodes ) {
  37389. // update frame state for each node
  37390. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  37391. }
  37392. }
  37393. /**
  37394. * Triggers the call of `update()` methods
  37395. * for all nodes of the given compute node.
  37396. *
  37397. * @param {Node} computeNode - The compute node.
  37398. */
  37399. updateForCompute( computeNode ) {
  37400. const nodeFrame = this.getNodeFrame();
  37401. const nodeBuilder = this.getForCompute( computeNode );
  37402. for ( const node of nodeBuilder.updateNodes ) {
  37403. nodeFrame.updateNode( node );
  37404. }
  37405. }
  37406. /**
  37407. * Triggers the call of `update()` methods
  37408. * for all nodes of the given compute node.
  37409. *
  37410. * @param {RenderObject} renderObject - The render object.
  37411. */
  37412. updateForRender( renderObject ) {
  37413. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37414. const nodeBuilder = renderObject.getNodeBuilderState();
  37415. for ( const node of nodeBuilder.updateNodes ) {
  37416. nodeFrame.updateNode( node );
  37417. }
  37418. }
  37419. /**
  37420. * Returns `true` if the given render object requires a refresh.
  37421. *
  37422. * @param {RenderObject} renderObject - The render object.
  37423. * @return {boolean} Whether the given render object requires a refresh or not.
  37424. */
  37425. needsRefresh( renderObject ) {
  37426. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37427. const monitor = renderObject.getMonitor();
  37428. return monitor.needsRefresh( renderObject, nodeFrame );
  37429. }
  37430. /**
  37431. * Frees the internal resources.
  37432. */
  37433. dispose() {
  37434. super.dispose();
  37435. this.nodeFrame = new NodeFrame();
  37436. this.nodeBuilderCache = new Map();
  37437. this.cacheLib = {};
  37438. }
  37439. }
  37440. const _plane = /*@__PURE__*/ new Plane();
  37441. /**
  37442. * Represents the state that is used to perform clipping via clipping planes.
  37443. * There is a default clipping context for each render context. When the
  37444. * scene holds instances of `ClippingGroup`, there will be a context for each
  37445. * group.
  37446. *
  37447. * @private
  37448. */
  37449. class ClippingContext {
  37450. /**
  37451. * Constructs a new clipping context.
  37452. *
  37453. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  37454. */
  37455. constructor( parentContext = null ) {
  37456. /**
  37457. * The clipping context's version.
  37458. *
  37459. * @type {number}
  37460. * @readonly
  37461. */
  37462. this.version = 0;
  37463. /**
  37464. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  37465. *
  37466. * @type {?boolean}
  37467. * @default null
  37468. */
  37469. this.clipIntersection = null;
  37470. /**
  37471. * The clipping context's cache key.
  37472. *
  37473. * @type {string}
  37474. */
  37475. this.cacheKey = '';
  37476. /**
  37477. * Whether the shadow pass is active or not.
  37478. *
  37479. * @type {boolean}
  37480. * @default false
  37481. */
  37482. this.shadowPass = false;
  37483. /**
  37484. * The view normal matrix.
  37485. *
  37486. * @type {Matrix3}
  37487. */
  37488. this.viewNormalMatrix = new Matrix3();
  37489. /**
  37490. * Internal cache for maintaining clipping contexts.
  37491. *
  37492. * @type {WeakMap<ClippingGroup,ClippingContext>}
  37493. */
  37494. this.clippingGroupContexts = new WeakMap();
  37495. /**
  37496. * The intersection planes.
  37497. *
  37498. * @type {Array<Vector4>}
  37499. */
  37500. this.intersectionPlanes = [];
  37501. /**
  37502. * The intersection planes.
  37503. *
  37504. * @type {Array<Vector4>}
  37505. */
  37506. this.unionPlanes = [];
  37507. /**
  37508. * The version of the clipping context's parent context.
  37509. *
  37510. * @type {?number}
  37511. * @readonly
  37512. */
  37513. this.parentVersion = null;
  37514. if ( parentContext !== null ) {
  37515. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  37516. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  37517. this.shadowPass = parentContext.shadowPass;
  37518. this.viewMatrix = parentContext.viewMatrix;
  37519. }
  37520. }
  37521. /**
  37522. * Projects the given source clipping planes and writes the result into the
  37523. * destination array.
  37524. *
  37525. * @param {Array<Plane>} source - The source clipping planes.
  37526. * @param {Array<Vector4>} destination - The destination.
  37527. * @param {number} offset - The offset.
  37528. */
  37529. projectPlanes( source, destination, offset ) {
  37530. const l = source.length;
  37531. for ( let i = 0; i < l; i ++ ) {
  37532. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  37533. const v = destination[ offset + i ];
  37534. const normal = _plane.normal;
  37535. v.x = - normal.x;
  37536. v.y = - normal.y;
  37537. v.z = - normal.z;
  37538. v.w = _plane.constant;
  37539. }
  37540. }
  37541. /**
  37542. * Updates the root clipping context of a scene.
  37543. *
  37544. * @param {Scene} scene - The scene.
  37545. * @param {Camera} camera - The camera that is used to render the scene.
  37546. */
  37547. updateGlobal( scene, camera ) {
  37548. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  37549. this.viewMatrix = camera.matrixWorldInverse;
  37550. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  37551. }
  37552. /**
  37553. * Updates the clipping context.
  37554. *
  37555. * @param {ClippingContext} parentContext - The parent context.
  37556. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  37557. */
  37558. update( parentContext, clippingGroup ) {
  37559. let update = false;
  37560. if ( parentContext.version !== this.parentVersion ) {
  37561. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  37562. this.unionPlanes = Array.from( parentContext.unionPlanes );
  37563. this.parentVersion = parentContext.version;
  37564. }
  37565. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  37566. this.clipIntersection = clippingGroup.clipIntersection;
  37567. if ( this.clipIntersection ) {
  37568. this.unionPlanes.length = parentContext.unionPlanes.length;
  37569. } else {
  37570. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  37571. }
  37572. }
  37573. const srcClippingPlanes = clippingGroup.clippingPlanes;
  37574. const l = srcClippingPlanes.length;
  37575. let dstClippingPlanes;
  37576. let offset;
  37577. if ( this.clipIntersection ) {
  37578. dstClippingPlanes = this.intersectionPlanes;
  37579. offset = parentContext.intersectionPlanes.length;
  37580. } else {
  37581. dstClippingPlanes = this.unionPlanes;
  37582. offset = parentContext.unionPlanes.length;
  37583. }
  37584. if ( dstClippingPlanes.length !== offset + l ) {
  37585. dstClippingPlanes.length = offset + l;
  37586. for ( let i = 0; i < l; i ++ ) {
  37587. dstClippingPlanes[ offset + i ] = new Vector4();
  37588. }
  37589. update = true;
  37590. }
  37591. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  37592. if ( update ) {
  37593. this.version ++;
  37594. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  37595. }
  37596. }
  37597. /**
  37598. * Returns a clipping context for the given clipping group.
  37599. *
  37600. * @param {ClippingGroup} clippingGroup - The clipping group.
  37601. * @return {ClippingContext} The clipping context.
  37602. */
  37603. getGroupContext( clippingGroup ) {
  37604. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  37605. let context = this.clippingGroupContexts.get( clippingGroup );
  37606. if ( context === undefined ) {
  37607. context = new ClippingContext( this );
  37608. this.clippingGroupContexts.set( clippingGroup, context );
  37609. }
  37610. context.update( this, clippingGroup );
  37611. return context;
  37612. }
  37613. /**
  37614. * The count of union clipping planes.
  37615. *
  37616. * @type {number}
  37617. * @readonly
  37618. */
  37619. get unionClippingCount() {
  37620. return this.unionPlanes.length;
  37621. }
  37622. }
  37623. /**
  37624. * This module is used to represent render bundles inside the renderer
  37625. * for further processing.
  37626. *
  37627. * @private
  37628. */
  37629. class RenderBundle {
  37630. /**
  37631. * Constructs a new bundle group.
  37632. *
  37633. * @param {BundleGroup} bundleGroup - The bundle group.
  37634. * @param {Camera} camera - The camera the bundle group is rendered with.
  37635. */
  37636. constructor( bundleGroup, camera ) {
  37637. this.bundleGroup = bundleGroup;
  37638. this.camera = camera;
  37639. }
  37640. }
  37641. const _chainKeys$1 = [];
  37642. /**
  37643. * This renderer module manages render bundles.
  37644. *
  37645. * @private
  37646. */
  37647. class RenderBundles {
  37648. /**
  37649. * Constructs a new render bundle management component.
  37650. */
  37651. constructor() {
  37652. /**
  37653. * A chain map for maintaining the render bundles.
  37654. *
  37655. * @type {ChainMap}
  37656. */
  37657. this.bundles = new ChainMap();
  37658. }
  37659. /**
  37660. * Returns a render bundle for the given bundle group and camera.
  37661. *
  37662. * @param {BundleGroup} bundleGroup - The bundle group.
  37663. * @param {Camera} camera - The camera the bundle group is rendered with.
  37664. * @return {RenderBundle} The render bundle.
  37665. */
  37666. get( bundleGroup, camera ) {
  37667. const bundles = this.bundles;
  37668. _chainKeys$1[ 0 ] = bundleGroup;
  37669. _chainKeys$1[ 1 ] = camera;
  37670. let bundle = bundles.get( _chainKeys$1 );
  37671. if ( bundle === undefined ) {
  37672. bundle = new RenderBundle( bundleGroup, camera );
  37673. bundles.set( _chainKeys$1, bundle );
  37674. }
  37675. _chainKeys$1.length = 0;
  37676. return bundle;
  37677. }
  37678. /**
  37679. * Frees all internal resources.
  37680. */
  37681. dispose() {
  37682. this.bundles = new ChainMap();
  37683. }
  37684. }
  37685. /**
  37686. * The purpose of a node library is to assign node implementations
  37687. * to existing library features. In `WebGPURenderer` lights, materials
  37688. * which are not based on `NodeMaterial` as well as tone mapping techniques
  37689. * are implemented with node-based modules.
  37690. *
  37691. * @private
  37692. */
  37693. class NodeLibrary {
  37694. /**
  37695. * Constructs a new node library.
  37696. */
  37697. constructor() {
  37698. /**
  37699. * A weak map that maps lights to light nodes.
  37700. *
  37701. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  37702. */
  37703. this.lightNodes = new WeakMap();
  37704. /**
  37705. * A map that maps materials to node materials.
  37706. *
  37707. * @type {Map<string,NodeMaterial.constructor>}
  37708. */
  37709. this.materialNodes = new Map();
  37710. /**
  37711. * A map that maps tone mapping techniques (constants)
  37712. * to tone mapping node functions.
  37713. *
  37714. * @type {Map<number,Function>}
  37715. */
  37716. this.toneMappingNodes = new Map();
  37717. }
  37718. /**
  37719. * Returns a matching node material instance for the given material object.
  37720. *
  37721. * This method also assigns/copies the properties of the given material object
  37722. * to the node material. This is done to make sure the current material
  37723. * configuration carries over to the node version.
  37724. *
  37725. * @param {Material} material - A material.
  37726. * @return {NodeMaterial} The corresponding node material.
  37727. */
  37728. fromMaterial( material ) {
  37729. if ( material.isNodeMaterial ) return material;
  37730. let nodeMaterial = null;
  37731. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  37732. if ( nodeMaterialClass !== null ) {
  37733. nodeMaterial = new nodeMaterialClass();
  37734. for ( const key in material ) {
  37735. nodeMaterial[ key ] = material[ key ];
  37736. }
  37737. }
  37738. return nodeMaterial;
  37739. }
  37740. /**
  37741. * Adds a tone mapping node function for a tone mapping technique (constant).
  37742. *
  37743. * @param {Function} toneMappingNode - The tone mapping node function.
  37744. * @param {number} toneMapping - The tone mapping.
  37745. */
  37746. addToneMapping( toneMappingNode, toneMapping ) {
  37747. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  37748. }
  37749. /**
  37750. * Returns a tone mapping node function for a tone mapping technique (constant).
  37751. *
  37752. * @param {number} toneMapping - The tone mapping.
  37753. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  37754. */
  37755. getToneMappingFunction( toneMapping ) {
  37756. return this.toneMappingNodes.get( toneMapping ) || null;
  37757. }
  37758. /**
  37759. * Returns a node material class definition for a material type.
  37760. *
  37761. * @param {string} materialType - The material type.
  37762. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  37763. */
  37764. getMaterialNodeClass( materialType ) {
  37765. return this.materialNodes.get( materialType ) || null;
  37766. }
  37767. /**
  37768. * Adds a node material class definition for a given material type.
  37769. *
  37770. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  37771. * @param {string} materialClassType - The material type.
  37772. */
  37773. addMaterial( materialNodeClass, materialClassType ) {
  37774. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  37775. }
  37776. /**
  37777. * Returns a light node class definition for a light class definition.
  37778. *
  37779. * @param {Light.constructor} light - The light class definition.
  37780. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  37781. */
  37782. getLightNodeClass( light ) {
  37783. return this.lightNodes.get( light ) || null;
  37784. }
  37785. /**
  37786. * Adds a light node class definition for a given light class definition.
  37787. *
  37788. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  37789. * @param {Light.constructor} lightClass - The light class definition.
  37790. */
  37791. addLight( lightNodeClass, lightClass ) {
  37792. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  37793. }
  37794. /**
  37795. * Adds a node class definition for the given type to the provided type library.
  37796. *
  37797. * @param {Node.constructor} nodeClass - The node class definition.
  37798. * @param {number|string} type - The object type.
  37799. * @param {Map<number|string,Node.constructor>} library - The type library.
  37800. */
  37801. addType( nodeClass, type, library ) {
  37802. if ( library.has( type ) ) {
  37803. warn( `Redefinition of node ${ type }` );
  37804. return;
  37805. }
  37806. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37807. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  37808. library.set( type, nodeClass );
  37809. }
  37810. /**
  37811. * Adds a node class definition for the given class definition to the provided type library.
  37812. *
  37813. * @param {Node.constructor} nodeClass - The node class definition.
  37814. * @param {Node.constructor} baseClass - The class definition.
  37815. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  37816. */
  37817. addClass( nodeClass, baseClass, library ) {
  37818. if ( library.has( baseClass ) ) {
  37819. warn( `Redefinition of node ${ baseClass.name }` );
  37820. return;
  37821. }
  37822. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37823. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  37824. library.set( baseClass, nodeClass );
  37825. }
  37826. }
  37827. const _defaultLights = /*@__PURE__*/ new LightsNode();
  37828. const _chainKeys = [];
  37829. /**
  37830. * This renderer module manages the lights nodes which are unique
  37831. * per scene and camera combination.
  37832. *
  37833. * The lights node itself is later configured in the render list
  37834. * with the actual lights from the scene.
  37835. *
  37836. * @private
  37837. * @augments ChainMap
  37838. */
  37839. class Lighting extends ChainMap {
  37840. /**
  37841. * Constructs a lighting management component.
  37842. */
  37843. constructor() {
  37844. super();
  37845. }
  37846. /**
  37847. * Creates a new lights node for the given array of lights.
  37848. *
  37849. * @param {Array<Light>} lights - The render object.
  37850. * @return {LightsNode} The lights node.
  37851. */
  37852. createNode( lights = [] ) {
  37853. return new LightsNode().setLights( lights );
  37854. }
  37855. /**
  37856. * Returns a lights node for the given scene and camera.
  37857. *
  37858. * @param {Scene} scene - The scene.
  37859. * @param {Camera} camera - The camera.
  37860. * @return {LightsNode} The lights node.
  37861. */
  37862. getNode( scene, camera ) {
  37863. // ignore post-processing
  37864. if ( scene.isQuadMesh ) return _defaultLights;
  37865. _chainKeys[ 0 ] = scene;
  37866. _chainKeys[ 1 ] = camera;
  37867. let node = this.get( _chainKeys );
  37868. if ( node === undefined ) {
  37869. node = this.createNode();
  37870. this.set( _chainKeys, node );
  37871. }
  37872. _chainKeys.length = 0;
  37873. return node;
  37874. }
  37875. }
  37876. /**
  37877. * A special type of render target that is used when rendering
  37878. * with the WebXR Device API.
  37879. *
  37880. * @private
  37881. * @augments RenderTarget
  37882. */
  37883. class XRRenderTarget extends RenderTarget {
  37884. /**
  37885. * Constructs a new XR render target.
  37886. *
  37887. * @param {number} [width=1] - The width of the render target.
  37888. * @param {number} [height=1] - The height of the render target.
  37889. * @param {Object} [options={}] - The configuration options.
  37890. */
  37891. constructor( width = 1, height = 1, options = {} ) {
  37892. super( width, height, options );
  37893. /**
  37894. * This flag can be used for type testing.
  37895. *
  37896. * @type {boolean}
  37897. * @readonly
  37898. * @default true
  37899. */
  37900. this.isXRRenderTarget = true;
  37901. /**
  37902. * Whether the attachments of the render target
  37903. * are defined by external textures. This flag is
  37904. * set to `true` when using the WebXR Layers API.
  37905. *
  37906. * @private
  37907. * @type {boolean}
  37908. * @default false
  37909. */
  37910. this._hasExternalTextures = false;
  37911. /**
  37912. * Whether a depth buffer should automatically be allocated
  37913. * for this XR render target or not.
  37914. *
  37915. * Allocating a depth buffer is the default behavior of XR render
  37916. * targets. However, when using the WebXR Layers API, this flag
  37917. * must be set to `false` when the `ignoreDepthValues` property of
  37918. * the projection layers evaluates to `false`.
  37919. *
  37920. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  37921. *
  37922. * @private
  37923. * @type {boolean}
  37924. * @default true
  37925. */
  37926. this._autoAllocateDepthBuffer = true;
  37927. /**
  37928. * Whether this render target is associated with a XRWebGLLayer.
  37929. *
  37930. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  37931. * this means that you don't have access to its bound color,
  37932. * stencil and depth buffers. We need to handle this framebuffer
  37933. * differently since its textures are always bound.
  37934. *
  37935. * @private
  37936. * @type {boolean}
  37937. * @default false
  37938. * */
  37939. this._isOpaqueFramebuffer = false;
  37940. }
  37941. copy( source ) {
  37942. super.copy( source );
  37943. this._hasExternalTextures = source._hasExternalTextures;
  37944. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  37945. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  37946. return this;
  37947. }
  37948. }
  37949. const _cameraLPos = /*@__PURE__*/ new Vector3();
  37950. const _cameraRPos = /*@__PURE__*/ new Vector3();
  37951. /**
  37952. * The XR manager is built on top of the WebXR Device API to
  37953. * manage XR sessions with `WebGPURenderer`.
  37954. *
  37955. * XR is currently only supported with a WebGL 2 backend.
  37956. *
  37957. * @augments EventDispatcher
  37958. */
  37959. class XRManager extends EventDispatcher {
  37960. /**
  37961. * Constructs a new XR manager.
  37962. *
  37963. * @param {Renderer} renderer - The renderer.
  37964. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  37965. */
  37966. constructor( renderer, multiview = false ) {
  37967. super();
  37968. /**
  37969. * This flag globally enables XR rendering.
  37970. *
  37971. * @type {boolean}
  37972. * @default false
  37973. */
  37974. this.enabled = false;
  37975. /**
  37976. * Whether the XR device is currently presenting or not.
  37977. *
  37978. * @type {boolean}
  37979. * @default false
  37980. * @readonly
  37981. */
  37982. this.isPresenting = false;
  37983. /**
  37984. * Whether the XR camera should automatically be updated or not.
  37985. *
  37986. * @type {boolean}
  37987. * @default true
  37988. */
  37989. this.cameraAutoUpdate = true;
  37990. /**
  37991. * The renderer.
  37992. *
  37993. * @private
  37994. * @type {Renderer}
  37995. */
  37996. this._renderer = renderer;
  37997. // camera
  37998. /**
  37999. * Represents the camera for the left eye.
  38000. *
  38001. * @private
  38002. * @type {PerspectiveCamera}
  38003. */
  38004. this._cameraL = new PerspectiveCamera();
  38005. this._cameraL.viewport = new Vector4();
  38006. /**
  38007. * Represents the camera for the right eye.
  38008. *
  38009. * @private
  38010. * @type {PerspectiveCamera}
  38011. */
  38012. this._cameraR = new PerspectiveCamera();
  38013. this._cameraR.viewport = new Vector4();
  38014. /**
  38015. * A list of cameras used for rendering the XR views.
  38016. *
  38017. * @private
  38018. * @type {Array<Camera>}
  38019. */
  38020. this._cameras = [ this._cameraL, this._cameraR ];
  38021. /**
  38022. * The main XR camera.
  38023. *
  38024. * @private
  38025. * @type {ArrayCamera}
  38026. */
  38027. this._cameraXR = new ArrayCamera();
  38028. /**
  38029. * The current near value of the XR camera.
  38030. *
  38031. * @private
  38032. * @type {?number}
  38033. * @default null
  38034. */
  38035. this._currentDepthNear = null;
  38036. /**
  38037. * The current far value of the XR camera.
  38038. *
  38039. * @private
  38040. * @type {?number}
  38041. * @default null
  38042. */
  38043. this._currentDepthFar = null;
  38044. /**
  38045. * A list of WebXR controllers requested by the application.
  38046. *
  38047. * @private
  38048. * @type {Array<WebXRController>}
  38049. */
  38050. this._controllers = [];
  38051. /**
  38052. * A list of XR input source. Each input source belongs to
  38053. * an instance of WebXRController.
  38054. *
  38055. * @private
  38056. * @type {Array<XRInputSource?>}
  38057. */
  38058. this._controllerInputSources = [];
  38059. /**
  38060. * The XR render target that represents the rendering destination
  38061. * during an active XR session.
  38062. *
  38063. * @private
  38064. * @type {?RenderTarget}
  38065. * @default null
  38066. */
  38067. this._xrRenderTarget = null;
  38068. /**
  38069. * An array holding all the non-projection layers
  38070. *
  38071. * @private
  38072. * @type {Array<Object>}
  38073. * @default []
  38074. */
  38075. this._layers = [];
  38076. /**
  38077. * Whether the XR session uses layers.
  38078. *
  38079. * @type {boolean}
  38080. * @default false
  38081. */
  38082. this._sessionUsesLayers = false;
  38083. /**
  38084. * Whether the device supports binding gl objects.
  38085. *
  38086. * @private
  38087. * @type {boolean}
  38088. * @readonly
  38089. */
  38090. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  38091. this._frameBufferTargets = null;
  38092. /**
  38093. * Helper function to create native WebXR Layer.
  38094. *
  38095. * @private
  38096. * @type {Function}
  38097. */
  38098. this._createXRLayer = createXRLayer.bind( this );
  38099. /**
  38100. * The current WebGL context.
  38101. *
  38102. * @private
  38103. * @type {?WebGL2RenderingContext}
  38104. * @default null
  38105. */
  38106. this._gl = null;
  38107. /**
  38108. * The current animation context.
  38109. *
  38110. * @private
  38111. * @type {?Window}
  38112. * @default null
  38113. */
  38114. this._currentAnimationContext = null;
  38115. /**
  38116. * The current animation loop.
  38117. *
  38118. * @private
  38119. * @type {?Function}
  38120. * @default null
  38121. */
  38122. this._currentAnimationLoop = null;
  38123. /**
  38124. * The current pixel ratio.
  38125. *
  38126. * @private
  38127. * @type {?number}
  38128. * @default null
  38129. */
  38130. this._currentPixelRatio = null;
  38131. /**
  38132. * The current size of the renderer's canvas
  38133. * in logical pixel unit.
  38134. *
  38135. * @private
  38136. * @type {Vector2}
  38137. */
  38138. this._currentSize = new Vector2();
  38139. /**
  38140. * The default event listener for handling events inside a XR session.
  38141. *
  38142. * @private
  38143. * @type {Function}
  38144. */
  38145. this._onSessionEvent = onSessionEvent.bind( this );
  38146. /**
  38147. * The event listener for handling the end of a XR session.
  38148. *
  38149. * @private
  38150. * @type {Function}
  38151. */
  38152. this._onSessionEnd = onSessionEnd.bind( this );
  38153. /**
  38154. * The event listener for handling the `inputsourceschange` event.
  38155. *
  38156. * @private
  38157. * @type {Function}
  38158. */
  38159. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  38160. /**
  38161. * The animation loop which is used as a replacement for the default
  38162. * animation loop of the application. It is only used when a XR session
  38163. * is active.
  38164. *
  38165. * @private
  38166. * @type {Function}
  38167. */
  38168. this._onAnimationFrame = onAnimationFrame.bind( this );
  38169. /**
  38170. * The current XR reference space.
  38171. *
  38172. * @private
  38173. * @type {?XRReferenceSpace}
  38174. * @default null
  38175. */
  38176. this._referenceSpace = null;
  38177. /**
  38178. * The current XR reference space type.
  38179. *
  38180. * @private
  38181. * @type {XRReferenceSpaceType}
  38182. * @default 'local-floor'
  38183. */
  38184. this._referenceSpaceType = 'local-floor';
  38185. /**
  38186. * A custom reference space defined by the application.
  38187. *
  38188. * @private
  38189. * @type {?XRReferenceSpace}
  38190. * @default null
  38191. */
  38192. this._customReferenceSpace = null;
  38193. /**
  38194. * The framebuffer scale factor.
  38195. *
  38196. * @private
  38197. * @type {number}
  38198. * @default 1
  38199. */
  38200. this._framebufferScaleFactor = 1;
  38201. /**
  38202. * The foveation factor.
  38203. *
  38204. * @private
  38205. * @type {number}
  38206. * @default 1
  38207. */
  38208. this._foveation = 1.0;
  38209. /**
  38210. * A reference to the current XR session.
  38211. *
  38212. * @private
  38213. * @type {?XRSession}
  38214. * @default null
  38215. */
  38216. this._session = null;
  38217. /**
  38218. * A reference to the current XR base layer.
  38219. *
  38220. * @private
  38221. * @type {?XRWebGLLayer}
  38222. * @default null
  38223. */
  38224. this._glBaseLayer = null;
  38225. /**
  38226. * A reference to the current XR binding.
  38227. *
  38228. * @private
  38229. * @type {?XRWebGLBinding}
  38230. * @default null
  38231. */
  38232. this._glBinding = null;
  38233. /**
  38234. * A reference to the current XR projection layer.
  38235. *
  38236. * @private
  38237. * @type {?XRProjectionLayer}
  38238. * @default null
  38239. */
  38240. this._glProjLayer = null;
  38241. /**
  38242. * A reference to the current XR frame.
  38243. *
  38244. * @private
  38245. * @type {?XRFrame}
  38246. * @default null
  38247. */
  38248. this._xrFrame = null;
  38249. /**
  38250. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  38251. *
  38252. * Note: this does not represent XRSession explicitly requesting
  38253. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  38254. *
  38255. * @private
  38256. * @type {boolean}
  38257. * @readonly
  38258. */
  38259. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  38260. /**
  38261. * Whether the usage of multiview has been requested by the application or not.
  38262. *
  38263. * @private
  38264. * @type {boolean}
  38265. * @default false
  38266. * @readonly
  38267. */
  38268. this._useMultiviewIfPossible = multiview;
  38269. /**
  38270. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  38271. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  38272. *
  38273. * @private
  38274. * @type {boolean}
  38275. * @readonly
  38276. */
  38277. this._useMultiview = false;
  38278. }
  38279. /**
  38280. * Returns an instance of `THREE.Group` that represents the transformation
  38281. * of a XR controller in target ray space. The requested controller is defined
  38282. * by the given index.
  38283. *
  38284. * @param {number} index - The index of the XR controller.
  38285. * @return {Group} A group that represents the controller's transformation.
  38286. */
  38287. getController( index ) {
  38288. const controller = this._getController( index );
  38289. return controller.getTargetRaySpace();
  38290. }
  38291. /**
  38292. * Returns an instance of `THREE.Group` that represents the transformation
  38293. * of a XR controller in grip space. The requested controller is defined
  38294. * by the given index.
  38295. *
  38296. * @param {number} index - The index of the XR controller.
  38297. * @return {Group} A group that represents the controller's transformation.
  38298. */
  38299. getControllerGrip( index ) {
  38300. const controller = this._getController( index );
  38301. return controller.getGripSpace();
  38302. }
  38303. /**
  38304. * Returns an instance of `THREE.Group` that represents the transformation
  38305. * of a XR controller in hand space. The requested controller is defined
  38306. * by the given index.
  38307. *
  38308. * @param {number} index - The index of the XR controller.
  38309. * @return {Group} A group that represents the controller's transformation.
  38310. */
  38311. getHand( index ) {
  38312. const controller = this._getController( index );
  38313. return controller.getHandSpace();
  38314. }
  38315. /**
  38316. * Returns the foveation value.
  38317. *
  38318. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  38319. */
  38320. getFoveation() {
  38321. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  38322. return undefined;
  38323. }
  38324. return this._foveation;
  38325. }
  38326. /**
  38327. * Sets the foveation value.
  38328. *
  38329. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  38330. * and `1` means maximum foveation (the edges render at lower resolution).
  38331. */
  38332. setFoveation( foveation ) {
  38333. this._foveation = foveation;
  38334. if ( this._glProjLayer !== null ) {
  38335. this._glProjLayer.fixedFoveation = foveation;
  38336. }
  38337. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  38338. this._glBaseLayer.fixedFoveation = foveation;
  38339. }
  38340. }
  38341. /**
  38342. * Returns the framebuffer scale factor.
  38343. *
  38344. * @return {number} The framebuffer scale factor.
  38345. */
  38346. getFramebufferScaleFactor() {
  38347. return this._framebufferScaleFactor;
  38348. }
  38349. /**
  38350. * Sets the framebuffer scale factor.
  38351. *
  38352. * This method can not be used during a XR session.
  38353. *
  38354. * @param {number} factor - The framebuffer scale factor.
  38355. */
  38356. setFramebufferScaleFactor( factor ) {
  38357. this._framebufferScaleFactor = factor;
  38358. if ( this.isPresenting === true ) {
  38359. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  38360. }
  38361. }
  38362. /**
  38363. * Returns the reference space type.
  38364. *
  38365. * @return {XRReferenceSpaceType} The reference space type.
  38366. */
  38367. getReferenceSpaceType() {
  38368. return this._referenceSpaceType;
  38369. }
  38370. /**
  38371. * Sets the reference space type.
  38372. *
  38373. * This method can not be used during a XR session.
  38374. *
  38375. * @param {XRReferenceSpaceType} type - The reference space type.
  38376. */
  38377. setReferenceSpaceType( type ) {
  38378. this._referenceSpaceType = type;
  38379. if ( this.isPresenting === true ) {
  38380. warn( 'XRManager: Cannot change reference space type while presenting.' );
  38381. }
  38382. }
  38383. /**
  38384. * Returns the XR reference space.
  38385. *
  38386. * @return {XRReferenceSpace} The XR reference space.
  38387. */
  38388. getReferenceSpace() {
  38389. return this._customReferenceSpace || this._referenceSpace;
  38390. }
  38391. /**
  38392. * Sets a custom XR reference space.
  38393. *
  38394. * @param {XRReferenceSpace} space - The XR reference space.
  38395. */
  38396. setReferenceSpace( space ) {
  38397. this._customReferenceSpace = space;
  38398. }
  38399. /**
  38400. * Returns the XR camera.
  38401. *
  38402. * @return {ArrayCamera} The XR camera.
  38403. */
  38404. getCamera() {
  38405. return this._cameraXR;
  38406. }
  38407. /**
  38408. * Returns the environment blend mode from the current XR session.
  38409. *
  38410. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  38411. */
  38412. getEnvironmentBlendMode() {
  38413. if ( this._session !== null ) {
  38414. return this._session.environmentBlendMode;
  38415. }
  38416. }
  38417. /**
  38418. * Returns the current XR binding.
  38419. *
  38420. * Creates a new binding if needed and the browser is
  38421. * capable of doing so.
  38422. *
  38423. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  38424. */
  38425. getBinding() {
  38426. if ( this._glBinding === null && this._supportsGlBinding ) {
  38427. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  38428. }
  38429. return this._glBinding;
  38430. }
  38431. /**
  38432. * Returns the current XR frame.
  38433. *
  38434. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  38435. */
  38436. getFrame() {
  38437. return this._xrFrame;
  38438. }
  38439. /**
  38440. * Returns `true` if the engine renders to a multiview target.
  38441. *
  38442. * @return {boolean} Whether the engine renders to a multiview render target or not.
  38443. */
  38444. useMultiview() {
  38445. return this._useMultiview;
  38446. }
  38447. /**
  38448. * This method can be used in XR applications to create a quadratic layer that presents a separate
  38449. * rendered scene.
  38450. *
  38451. * @param {number} width - The width of the layer plane in world units.
  38452. * @param {number} height - The height of the layer plane in world units.
  38453. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  38454. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  38455. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  38456. * @param {number} pixelheight - The height of the layer's render target in pixels.
  38457. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  38458. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  38459. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  38460. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  38461. */
  38462. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  38463. const geometry = new PlaneGeometry( width, height );
  38464. const renderTarget = new XRRenderTarget(
  38465. pixelwidth,
  38466. pixelheight,
  38467. {
  38468. format: RGBAFormat,
  38469. type: UnsignedByteType,
  38470. depthTexture: new DepthTexture(
  38471. pixelwidth,
  38472. pixelheight,
  38473. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  38474. undefined,
  38475. undefined,
  38476. undefined,
  38477. undefined,
  38478. undefined,
  38479. undefined,
  38480. attributes.stencil ? DepthStencilFormat : DepthFormat
  38481. ),
  38482. stencilBuffer: attributes.stencil,
  38483. resolveDepthBuffer: false,
  38484. resolveStencilBuffer: false
  38485. } );
  38486. renderTarget._autoAllocateDepthBuffer = true;
  38487. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  38488. material.map = renderTarget.texture;
  38489. material.map.offset.y = 1;
  38490. material.map.repeat.y = -1;
  38491. const plane = new Mesh( geometry, material );
  38492. plane.position.copy( translation );
  38493. plane.quaternion.copy( quaternion );
  38494. const layer = {
  38495. type: 'quad',
  38496. width: width,
  38497. height: height,
  38498. translation: translation,
  38499. quaternion: quaternion,
  38500. pixelwidth: pixelwidth,
  38501. pixelheight: pixelheight,
  38502. plane: plane,
  38503. material: material,
  38504. rendercall: rendercall,
  38505. renderTarget: renderTarget };
  38506. this._layers.push( layer );
  38507. if ( this._session !== null ) {
  38508. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  38509. layer.plane.material.blending = CustomBlending;
  38510. layer.plane.material.blendEquation = AddEquation;
  38511. layer.plane.material.blendSrc = ZeroFactor;
  38512. layer.plane.material.blendDst = ZeroFactor;
  38513. layer.xrlayer = this._createXRLayer( layer );
  38514. const xrlayers = this._session.renderState.layers;
  38515. xrlayers.unshift( layer.xrlayer );
  38516. this._session.updateRenderState( { layers: xrlayers } );
  38517. } else {
  38518. renderTarget.isXRRenderTarget = false;
  38519. }
  38520. return plane;
  38521. }
  38522. /**
  38523. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  38524. * rendered scene.
  38525. *
  38526. * @param {number} radius - The radius of the cylinder in world units.
  38527. * @param {number} centralAngle - The central angle of the cylinder in radians.
  38528. * @param {number} aspectratio - The aspect ratio.
  38529. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  38530. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  38531. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  38532. * @param {number} pixelheight - The height of the layer's render target in pixels.
  38533. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  38534. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  38535. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  38536. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  38537. */
  38538. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  38539. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  38540. const renderTarget = new XRRenderTarget(
  38541. pixelwidth,
  38542. pixelheight,
  38543. {
  38544. format: RGBAFormat,
  38545. type: UnsignedByteType,
  38546. depthTexture: new DepthTexture(
  38547. pixelwidth,
  38548. pixelheight,
  38549. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  38550. undefined,
  38551. undefined,
  38552. undefined,
  38553. undefined,
  38554. undefined,
  38555. undefined,
  38556. attributes.stencil ? DepthStencilFormat : DepthFormat
  38557. ),
  38558. stencilBuffer: attributes.stencil,
  38559. resolveDepthBuffer: false,
  38560. resolveStencilBuffer: false
  38561. } );
  38562. renderTarget._autoAllocateDepthBuffer = true;
  38563. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  38564. material.map = renderTarget.texture;
  38565. material.map.offset.y = 1;
  38566. material.map.repeat.y = -1;
  38567. const plane = new Mesh( geometry, material );
  38568. plane.position.copy( translation );
  38569. plane.quaternion.copy( quaternion );
  38570. const layer = {
  38571. type: 'cylinder',
  38572. radius: radius,
  38573. centralAngle: centralAngle,
  38574. aspectratio: aspectratio,
  38575. translation: translation,
  38576. quaternion: quaternion,
  38577. pixelwidth: pixelwidth,
  38578. pixelheight: pixelheight,
  38579. plane: plane,
  38580. material: material,
  38581. rendercall: rendercall,
  38582. renderTarget: renderTarget };
  38583. this._layers.push( layer );
  38584. if ( this._session !== null ) {
  38585. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  38586. layer.plane.material.blending = CustomBlending;
  38587. layer.plane.material.blendEquation = AddEquation;
  38588. layer.plane.material.blendSrc = ZeroFactor;
  38589. layer.plane.material.blendDst = ZeroFactor;
  38590. layer.xrlayer = this._createXRLayer( layer );
  38591. const xrlayers = this._session.renderState.layers;
  38592. xrlayers.unshift( layer.xrlayer );
  38593. this._session.updateRenderState( { layers: xrlayers } );
  38594. } else {
  38595. renderTarget.isXRRenderTarget = false;
  38596. }
  38597. return plane;
  38598. }
  38599. /**
  38600. * Renders the XR layers that have been previously added to the scene.
  38601. *
  38602. * This method is usually called in your animation loop before rendering
  38603. * the actual scene via `renderer.render( scene, camera );`.
  38604. */
  38605. renderLayers( ) {
  38606. const translationObject = new Vector3();
  38607. const quaternionObject = new Quaternion();
  38608. const renderer = this._renderer;
  38609. const wasPresenting = this.isPresenting;
  38610. const rendererOutputTarget = renderer.getOutputRenderTarget();
  38611. const rendererFramebufferTarget = renderer._frameBufferTarget;
  38612. this.isPresenting = false;
  38613. const rendererSize = new Vector2();
  38614. renderer.getSize( rendererSize );
  38615. const rendererQuad = renderer._quad;
  38616. for ( const layer of this._layers ) {
  38617. layer.renderTarget.isXRRenderTarget = this._session !== null;
  38618. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  38619. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  38620. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  38621. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  38622. renderer.backend.setXRRenderTargetTextures(
  38623. layer.renderTarget,
  38624. glSubImage.colorTexture,
  38625. undefined );
  38626. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  38627. renderer.setOutputRenderTarget( layer.renderTarget );
  38628. renderer.setRenderTarget( null );
  38629. renderer._frameBufferTarget = null;
  38630. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  38631. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  38632. if ( ! frameBufferTarget ) {
  38633. renderer._quad = new QuadMesh( new NodeMaterial() );
  38634. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  38635. } else {
  38636. renderer._frameBufferTarget = frameBufferTarget;
  38637. renderer._quad = quad;
  38638. }
  38639. layer.rendercall();
  38640. renderer._frameBufferTarget = null;
  38641. } else {
  38642. renderer.setRenderTarget( layer.renderTarget );
  38643. layer.rendercall();
  38644. }
  38645. }
  38646. renderer.setRenderTarget( null );
  38647. renderer.setOutputRenderTarget( rendererOutputTarget );
  38648. renderer._frameBufferTarget = rendererFramebufferTarget;
  38649. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  38650. renderer._quad = rendererQuad;
  38651. this.isPresenting = wasPresenting;
  38652. }
  38653. /**
  38654. * Returns the current XR session.
  38655. *
  38656. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  38657. */
  38658. getSession() {
  38659. return this._session;
  38660. }
  38661. /**
  38662. * After a XR session has been requested usually with one of the `*Button` modules, it
  38663. * is injected into the renderer with this method. This method triggers the start of
  38664. * the actual XR rendering.
  38665. *
  38666. * @async
  38667. * @param {XRSession} session - The XR session to set.
  38668. * @return {Promise} A Promise that resolves when the session has been set.
  38669. */
  38670. async setSession( session ) {
  38671. const renderer = this._renderer;
  38672. const backend = renderer.backend;
  38673. this._gl = renderer.getContext();
  38674. const gl = this._gl;
  38675. const attributes = gl.getContextAttributes();
  38676. this._session = session;
  38677. if ( session !== null ) {
  38678. 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.' );
  38679. session.addEventListener( 'select', this._onSessionEvent );
  38680. session.addEventListener( 'selectstart', this._onSessionEvent );
  38681. session.addEventListener( 'selectend', this._onSessionEvent );
  38682. session.addEventListener( 'squeeze', this._onSessionEvent );
  38683. session.addEventListener( 'squeezestart', this._onSessionEvent );
  38684. session.addEventListener( 'squeezeend', this._onSessionEvent );
  38685. session.addEventListener( 'end', this._onSessionEnd );
  38686. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  38687. await backend.makeXRCompatible();
  38688. this._currentPixelRatio = renderer.getPixelRatio();
  38689. renderer.getSize( this._currentSize );
  38690. this._currentAnimationContext = renderer._animation.getContext();
  38691. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  38692. renderer._animation.stop();
  38693. //
  38694. if ( this._supportsLayers === true ) {
  38695. // default path using XRProjectionLayer
  38696. let depthFormat = null;
  38697. let depthType = null;
  38698. let glDepthFormat = null;
  38699. if ( renderer.depth ) {
  38700. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  38701. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  38702. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  38703. }
  38704. const projectionlayerInit = {
  38705. colorFormat: gl.RGBA8,
  38706. depthFormat: glDepthFormat,
  38707. scaleFactor: this._framebufferScaleFactor,
  38708. clearOnAccess: false
  38709. };
  38710. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  38711. projectionlayerInit.textureType = 'texture-array';
  38712. this._useMultiview = true;
  38713. }
  38714. this._glBinding = this.getBinding();
  38715. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  38716. const layersArray = [ glProjLayer ];
  38717. this._glProjLayer = glProjLayer;
  38718. renderer.setPixelRatio( 1 );
  38719. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  38720. const depth = this._useMultiview ? 2 : 1;
  38721. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  38722. this._xrRenderTarget = new XRRenderTarget(
  38723. glProjLayer.textureWidth,
  38724. glProjLayer.textureHeight,
  38725. {
  38726. format: RGBAFormat,
  38727. type: UnsignedByteType,
  38728. colorSpace: renderer.outputColorSpace,
  38729. depthTexture: depthTexture,
  38730. stencilBuffer: renderer.stencil,
  38731. samples: attributes.antialias ? 4 : 0,
  38732. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  38733. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  38734. depth: this._useMultiview ? 2 : 1,
  38735. multiview: this._useMultiview
  38736. } );
  38737. this._xrRenderTarget._hasExternalTextures = true;
  38738. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  38739. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  38740. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  38741. if ( this._sessionUsesLayers ) {
  38742. // switch layers to native
  38743. for ( const layer of this._layers ) {
  38744. // change material so it "punches" out a hole to show the XR Layer.
  38745. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  38746. layer.plane.material.blending = CustomBlending;
  38747. layer.plane.material.blendEquation = AddEquation;
  38748. layer.plane.material.blendSrc = ZeroFactor;
  38749. layer.plane.material.blendDst = ZeroFactor;
  38750. layer.xrlayer = this._createXRLayer( layer );
  38751. layersArray.unshift( layer.xrlayer );
  38752. }
  38753. }
  38754. session.updateRenderState( { layers: layersArray } );
  38755. } else {
  38756. // fallback to XRWebGLLayer
  38757. const layerInit = {
  38758. antialias: renderer.currentSamples > 0,
  38759. alpha: true,
  38760. depth: renderer.depth,
  38761. stencil: renderer.stencil,
  38762. framebufferScaleFactor: this.getFramebufferScaleFactor()
  38763. };
  38764. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  38765. this._glBaseLayer = glBaseLayer;
  38766. session.updateRenderState( { baseLayer: glBaseLayer } );
  38767. renderer.setPixelRatio( 1 );
  38768. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  38769. this._xrRenderTarget = new XRRenderTarget(
  38770. glBaseLayer.framebufferWidth,
  38771. glBaseLayer.framebufferHeight,
  38772. {
  38773. format: RGBAFormat,
  38774. type: UnsignedByteType,
  38775. colorSpace: renderer.outputColorSpace,
  38776. stencilBuffer: renderer.stencil,
  38777. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  38778. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  38779. }
  38780. );
  38781. this._xrRenderTarget._isOpaqueFramebuffer = true;
  38782. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  38783. }
  38784. //
  38785. this.setFoveation( this.getFoveation() );
  38786. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  38787. renderer._animation.setContext( session );
  38788. renderer._animation.start();
  38789. this.isPresenting = true;
  38790. this.dispatchEvent( { type: 'sessionstart' } );
  38791. }
  38792. }
  38793. /**
  38794. * This method is called by the renderer per frame and updates the XR camera
  38795. * and it sub cameras based on the given camera. The given camera is the "user"
  38796. * camera created on application level and used for non-XR rendering.
  38797. *
  38798. * @param {PerspectiveCamera} camera - The camera.
  38799. */
  38800. updateCamera( camera ) {
  38801. const session = this._session;
  38802. if ( session === null ) return;
  38803. const depthNear = camera.near;
  38804. const depthFar = camera.far;
  38805. const cameraXR = this._cameraXR;
  38806. const cameraL = this._cameraL;
  38807. const cameraR = this._cameraR;
  38808. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  38809. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  38810. cameraXR.isMultiViewCamera = this._useMultiview;
  38811. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  38812. // Note that the new renderState won't apply until the next frame. See #18320
  38813. session.updateRenderState( {
  38814. depthNear: cameraXR.near,
  38815. depthFar: cameraXR.far
  38816. } );
  38817. this._currentDepthNear = cameraXR.near;
  38818. this._currentDepthFar = cameraXR.far;
  38819. }
  38820. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  38821. cameraXR.layers.mask = camera.layers.mask | 0b110;
  38822. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  38823. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  38824. const parent = camera.parent;
  38825. const cameras = cameraXR.cameras;
  38826. updateCamera( cameraXR, parent );
  38827. for ( let i = 0; i < cameras.length; i ++ ) {
  38828. updateCamera( cameras[ i ], parent );
  38829. }
  38830. // update projection matrix for proper view frustum culling
  38831. if ( cameras.length === 2 ) {
  38832. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  38833. } else {
  38834. // assume single camera setup (AR)
  38835. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  38836. }
  38837. // update user camera and its children
  38838. updateUserCamera( camera, cameraXR, parent );
  38839. }
  38840. /**
  38841. * Returns a WebXR controller for the given controller index.
  38842. *
  38843. * @private
  38844. * @param {number} index - The controller index.
  38845. * @return {WebXRController} The XR controller.
  38846. */
  38847. _getController( index ) {
  38848. let controller = this._controllers[ index ];
  38849. if ( controller === undefined ) {
  38850. controller = new WebXRController();
  38851. this._controllers[ index ] = controller;
  38852. }
  38853. return controller;
  38854. }
  38855. }
  38856. /**
  38857. * Assumes 2 cameras that are parallel and share an X-axis, and that
  38858. * the cameras' projection and world matrices have already been set.
  38859. * And that near and far planes are identical for both cameras.
  38860. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  38861. *
  38862. * @param {ArrayCamera} camera - The camera to update.
  38863. * @param {PerspectiveCamera} cameraL - The left camera.
  38864. * @param {PerspectiveCamera} cameraR - The right camera.
  38865. */
  38866. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  38867. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  38868. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  38869. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  38870. const projL = cameraL.projectionMatrix.elements;
  38871. const projR = cameraR.projectionMatrix.elements;
  38872. // VR systems will have identical far and near planes, and
  38873. // most likely identical top and bottom frustum extents.
  38874. // Use the left camera for these values.
  38875. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  38876. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  38877. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  38878. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  38879. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  38880. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  38881. const left = near * leftFov;
  38882. const right = near * rightFov;
  38883. // Calculate the new camera's position offset from the
  38884. // left camera. xOffset should be roughly half `ipd`.
  38885. const zOffset = ipd / ( - leftFov + rightFov );
  38886. const xOffset = zOffset * - leftFov;
  38887. // TODO: Better way to apply this offset?
  38888. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  38889. camera.translateX( xOffset );
  38890. camera.translateZ( zOffset );
  38891. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  38892. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38893. // Check if the projection uses an infinite far plane.
  38894. if ( projL[ 10 ] === -1 ) {
  38895. // Use the projection matrix from the left eye.
  38896. // The camera offset is sufficient to include the view volumes
  38897. // of both eyes (assuming symmetric projections).
  38898. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  38899. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  38900. } else {
  38901. // Find the union of the frustum values of the cameras and scale
  38902. // the values so that the near plane's position does not change in world space,
  38903. // although must now be relative to the new union camera.
  38904. const near2 = near + zOffset;
  38905. const far2 = far + zOffset;
  38906. const left2 = left - xOffset;
  38907. const right2 = right + ( ipd - xOffset );
  38908. const top2 = topFov * far / far2 * near2;
  38909. const bottom2 = bottomFov * far / far2 * near2;
  38910. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  38911. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  38912. }
  38913. }
  38914. /**
  38915. * Updates the world matrices for the given camera based on the parent 3D object.
  38916. *
  38917. * @inner
  38918. * @param {Camera} camera - The camera to update.
  38919. * @param {Object3D} parent - The parent 3D object.
  38920. */
  38921. function updateCamera( camera, parent ) {
  38922. if ( parent === null ) {
  38923. camera.matrixWorld.copy( camera.matrix );
  38924. } else {
  38925. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  38926. }
  38927. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38928. }
  38929. /**
  38930. * Updates the given camera with the transformation of the XR camera and parent object.
  38931. *
  38932. * @inner
  38933. * @param {Camera} camera - The camera to update.
  38934. * @param {ArrayCamera} cameraXR - The XR camera.
  38935. * @param {Object3D} parent - The parent 3D object.
  38936. */
  38937. function updateUserCamera( camera, cameraXR, parent ) {
  38938. if ( parent === null ) {
  38939. camera.matrix.copy( cameraXR.matrixWorld );
  38940. } else {
  38941. camera.matrix.copy( parent.matrixWorld );
  38942. camera.matrix.invert();
  38943. camera.matrix.multiply( cameraXR.matrixWorld );
  38944. }
  38945. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38946. camera.updateMatrixWorld( true );
  38947. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  38948. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  38949. if ( camera.isPerspectiveCamera ) {
  38950. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  38951. camera.zoom = 1;
  38952. }
  38953. }
  38954. function onSessionEvent( event ) {
  38955. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  38956. if ( controllerIndex === -1 ) {
  38957. return;
  38958. }
  38959. const controller = this._controllers[ controllerIndex ];
  38960. if ( controller !== undefined ) {
  38961. const referenceSpace = this.getReferenceSpace();
  38962. controller.update( event.inputSource, event.frame, referenceSpace );
  38963. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  38964. }
  38965. }
  38966. function onSessionEnd() {
  38967. const session = this._session;
  38968. const renderer = this._renderer;
  38969. session.removeEventListener( 'select', this._onSessionEvent );
  38970. session.removeEventListener( 'selectstart', this._onSessionEvent );
  38971. session.removeEventListener( 'selectend', this._onSessionEvent );
  38972. session.removeEventListener( 'squeeze', this._onSessionEvent );
  38973. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  38974. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  38975. session.removeEventListener( 'end', this._onSessionEnd );
  38976. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  38977. for ( let i = 0; i < this._controllers.length; i ++ ) {
  38978. const inputSource = this._controllerInputSources[ i ];
  38979. if ( inputSource === null ) continue;
  38980. this._controllerInputSources[ i ] = null;
  38981. this._controllers[ i ].disconnect( inputSource );
  38982. }
  38983. this._currentDepthNear = null;
  38984. this._currentDepthFar = null;
  38985. // restore framebuffer/rendering state
  38986. renderer._resetXRState();
  38987. this._session = null;
  38988. this._xrRenderTarget = null;
  38989. this._glBinding = null;
  38990. this._glBaseLayer = null;
  38991. this._glProjLayer = null;
  38992. // switch layers back to emulated
  38993. if ( this._sessionUsesLayers === true ) {
  38994. for ( const layer of this._layers ) {
  38995. // Recreate layer render target to reset state
  38996. layer.renderTarget = new XRRenderTarget(
  38997. layer.pixelwidth,
  38998. layer.pixelheight,
  38999. {
  39000. format: RGBAFormat,
  39001. type: UnsignedByteType,
  39002. depthTexture: new DepthTexture(
  39003. layer.pixelwidth,
  39004. layer.pixelheight,
  39005. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  39006. undefined,
  39007. undefined,
  39008. undefined,
  39009. undefined,
  39010. undefined,
  39011. undefined,
  39012. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  39013. ),
  39014. stencilBuffer: layer.stencilBuffer,
  39015. resolveDepthBuffer: false,
  39016. resolveStencilBuffer: false
  39017. } );
  39018. layer.renderTarget.isXRRenderTarget = false;
  39019. layer.plane.material = layer.material;
  39020. layer.material.map = layer.renderTarget.texture;
  39021. layer.material.map.offset.y = 1;
  39022. layer.material.map.repeat.y = -1;
  39023. delete layer.xrlayer;
  39024. }
  39025. }
  39026. //
  39027. this.isPresenting = false;
  39028. this._useMultiview = false;
  39029. renderer._animation.stop();
  39030. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  39031. renderer._animation.setContext( this._currentAnimationContext );
  39032. renderer._animation.start();
  39033. renderer.setPixelRatio( this._currentPixelRatio );
  39034. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  39035. this.dispatchEvent( { type: 'sessionend' } );
  39036. }
  39037. function onInputSourcesChange( event ) {
  39038. const controllers = this._controllers;
  39039. const controllerInputSources = this._controllerInputSources;
  39040. // Notify disconnected
  39041. for ( let i = 0; i < event.removed.length; i ++ ) {
  39042. const inputSource = event.removed[ i ];
  39043. const index = controllerInputSources.indexOf( inputSource );
  39044. if ( index >= 0 ) {
  39045. controllerInputSources[ index ] = null;
  39046. controllers[ index ].disconnect( inputSource );
  39047. }
  39048. }
  39049. // Notify connected
  39050. for ( let i = 0; i < event.added.length; i ++ ) {
  39051. const inputSource = event.added[ i ];
  39052. let controllerIndex = controllerInputSources.indexOf( inputSource );
  39053. if ( controllerIndex === -1 ) {
  39054. // Assign input source a controller that currently has no input source
  39055. for ( let i = 0; i < controllers.length; i ++ ) {
  39056. if ( i >= controllerInputSources.length ) {
  39057. controllerInputSources.push( inputSource );
  39058. controllerIndex = i;
  39059. break;
  39060. } else if ( controllerInputSources[ i ] === null ) {
  39061. controllerInputSources[ i ] = inputSource;
  39062. controllerIndex = i;
  39063. break;
  39064. }
  39065. }
  39066. // If all controllers do currently receive input we ignore new ones
  39067. if ( controllerIndex === -1 ) break;
  39068. }
  39069. const controller = controllers[ controllerIndex ];
  39070. if ( controller ) {
  39071. controller.connect( inputSource );
  39072. }
  39073. }
  39074. }
  39075. // Creation method for native WebXR layers
  39076. function createXRLayer( layer ) {
  39077. if ( layer.type === 'quad' ) {
  39078. return this._glBinding.createQuadLayer( {
  39079. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  39080. width: layer.width / 2,
  39081. height: layer.height / 2,
  39082. space: this._referenceSpace,
  39083. viewPixelWidth: layer.pixelwidth,
  39084. viewPixelHeight: layer.pixelheight,
  39085. clearOnAccess: false
  39086. } );
  39087. } else {
  39088. return this._glBinding.createCylinderLayer( {
  39089. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  39090. radius: layer.radius,
  39091. centralAngle: layer.centralAngle,
  39092. aspectRatio: layer.aspectRatio,
  39093. space: this._referenceSpace,
  39094. viewPixelWidth: layer.pixelwidth,
  39095. viewPixelHeight: layer.pixelheight,
  39096. clearOnAccess: false
  39097. } );
  39098. }
  39099. }
  39100. // Animation Loop
  39101. function onAnimationFrame( time, frame ) {
  39102. if ( frame === undefined ) return;
  39103. const cameraXR = this._cameraXR;
  39104. const renderer = this._renderer;
  39105. const backend = renderer.backend;
  39106. const glBaseLayer = this._glBaseLayer;
  39107. const referenceSpace = this.getReferenceSpace();
  39108. const pose = frame.getViewerPose( referenceSpace );
  39109. this._xrFrame = frame;
  39110. if ( pose !== null ) {
  39111. const views = pose.views;
  39112. if ( this._glBaseLayer !== null ) {
  39113. backend.setXRTarget( glBaseLayer.framebuffer );
  39114. }
  39115. let cameraXRNeedsUpdate = false;
  39116. // check if it's necessary to rebuild cameraXR's camera list
  39117. if ( views.length !== cameraXR.cameras.length ) {
  39118. cameraXR.cameras.length = 0;
  39119. cameraXRNeedsUpdate = true;
  39120. }
  39121. for ( let i = 0; i < views.length; i ++ ) {
  39122. const view = views[ i ];
  39123. let viewport;
  39124. if ( this._supportsLayers === true ) {
  39125. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  39126. viewport = glSubImage.viewport;
  39127. // For side-by-side projection, we only produce a single texture for both eyes.
  39128. if ( i === 0 ) {
  39129. backend.setXRRenderTargetTextures(
  39130. this._xrRenderTarget,
  39131. glSubImage.colorTexture,
  39132. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  39133. );
  39134. }
  39135. } else {
  39136. viewport = glBaseLayer.getViewport( view );
  39137. }
  39138. let camera = this._cameras[ i ];
  39139. if ( camera === undefined ) {
  39140. camera = new PerspectiveCamera();
  39141. camera.layers.enable( i );
  39142. camera.viewport = new Vector4();
  39143. this._cameras[ i ] = camera;
  39144. }
  39145. camera.matrix.fromArray( view.transform.matrix );
  39146. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  39147. camera.projectionMatrix.fromArray( view.projectionMatrix );
  39148. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  39149. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  39150. if ( i === 0 ) {
  39151. cameraXR.matrix.copy( camera.matrix );
  39152. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  39153. }
  39154. if ( cameraXRNeedsUpdate === true ) {
  39155. cameraXR.cameras.push( camera );
  39156. }
  39157. }
  39158. renderer.setOutputRenderTarget( this._xrRenderTarget );
  39159. }
  39160. //
  39161. for ( let i = 0; i < this._controllers.length; i ++ ) {
  39162. const inputSource = this._controllerInputSources[ i ];
  39163. const controller = this._controllers[ i ];
  39164. if ( inputSource !== null && controller !== undefined ) {
  39165. controller.update( inputSource, frame, referenceSpace );
  39166. }
  39167. }
  39168. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  39169. if ( frame.detectedPlanes ) {
  39170. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  39171. }
  39172. this._xrFrame = null;
  39173. }
  39174. /**
  39175. * CanvasTarget is a class that represents the final output destination of the renderer.
  39176. *
  39177. * @augments EventDispatcher
  39178. */
  39179. class CanvasTarget extends EventDispatcher {
  39180. /**
  39181. * Constructs a new CanvasTarget.
  39182. *
  39183. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  39184. */
  39185. constructor( domElement ) {
  39186. super();
  39187. /**
  39188. * A reference to the canvas element the renderer is drawing to.
  39189. * This value of this property will automatically be created by
  39190. * the renderer.
  39191. *
  39192. * @type {HTMLCanvasElement|OffscreenCanvas}
  39193. */
  39194. this.domElement = domElement;
  39195. /**
  39196. * The renderer's pixel ratio.
  39197. *
  39198. * @private
  39199. * @type {number}
  39200. * @default 1
  39201. */
  39202. this._pixelRatio = 1;
  39203. /**
  39204. * The width of the renderer's default framebuffer in logical pixel unit.
  39205. *
  39206. * @private
  39207. * @type {number}
  39208. */
  39209. this._width = this.domElement.width;
  39210. /**
  39211. * The height of the renderer's default framebuffer in logical pixel unit.
  39212. *
  39213. * @private
  39214. * @type {number}
  39215. */
  39216. this._height = this.domElement.height;
  39217. /**
  39218. * The viewport of the renderer in logical pixel unit.
  39219. *
  39220. * @private
  39221. * @type {Vector4}
  39222. */
  39223. this._viewport = new Vector4( 0, 0, this._width, this._height );
  39224. /**
  39225. * The scissor rectangle of the renderer in logical pixel unit.
  39226. *
  39227. * @private
  39228. * @type {Vector4}
  39229. */
  39230. this._scissor = new Vector4( 0, 0, this._width, this._height );
  39231. /**
  39232. * Whether the scissor test should be enabled or not.
  39233. *
  39234. * @private
  39235. * @type {boolean}
  39236. */
  39237. this._scissorTest = false;
  39238. /**
  39239. * The color texture of the default framebuffer.
  39240. *
  39241. * @type {FramebufferTexture}
  39242. */
  39243. this.colorTexture = new FramebufferTexture();
  39244. /**
  39245. * The depth texture of the default framebuffer.
  39246. *
  39247. * @type {DepthTexture}
  39248. */
  39249. this.depthTexture = new DepthTexture();
  39250. }
  39251. /**
  39252. * Returns the pixel ratio.
  39253. *
  39254. * @return {number} The pixel ratio.
  39255. */
  39256. getPixelRatio() {
  39257. return this._pixelRatio;
  39258. }
  39259. /**
  39260. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  39261. *
  39262. * @param {Vector2} target - The method writes the result in this target object.
  39263. * @return {Vector2} The drawing buffer size.
  39264. */
  39265. getDrawingBufferSize( target ) {
  39266. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  39267. }
  39268. /**
  39269. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  39270. *
  39271. * @param {Vector2} target - The method writes the result in this target object.
  39272. * @return {Vector2} The renderer's size in logical pixels.
  39273. */
  39274. getSize( target ) {
  39275. return target.set( this._width, this._height );
  39276. }
  39277. /**
  39278. * Sets the given pixel ratio and resizes the canvas if necessary.
  39279. *
  39280. * @param {number} [value=1] - The pixel ratio.
  39281. */
  39282. setPixelRatio( value = 1 ) {
  39283. if ( this._pixelRatio === value ) return;
  39284. this._pixelRatio = value;
  39285. this.setSize( this._width, this._height, false );
  39286. }
  39287. /**
  39288. * This method allows to define the drawing buffer size by specifying
  39289. * width, height and pixel ratio all at once. The size of the drawing
  39290. * buffer is computed with this formula:
  39291. * ```js
  39292. * size.x = width * pixelRatio;
  39293. * size.y = height * pixelRatio;
  39294. * ```
  39295. *
  39296. * @param {number} width - The width in logical pixels.
  39297. * @param {number} height - The height in logical pixels.
  39298. * @param {number} pixelRatio - The pixel ratio.
  39299. */
  39300. setDrawingBufferSize( width, height, pixelRatio ) {
  39301. // Renderer can't be resized while presenting in XR.
  39302. if ( this.xr && this.xr.isPresenting ) return;
  39303. this._width = width;
  39304. this._height = height;
  39305. this._pixelRatio = pixelRatio;
  39306. this.domElement.width = Math.floor( width * pixelRatio );
  39307. this.domElement.height = Math.floor( height * pixelRatio );
  39308. this.setViewport( 0, 0, width, height );
  39309. this._dispatchResize();
  39310. }
  39311. /**
  39312. * Sets the size of the renderer.
  39313. *
  39314. * @param {number} width - The width in logical pixels.
  39315. * @param {number} height - The height in logical pixels.
  39316. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  39317. */
  39318. setSize( width, height, updateStyle = true ) {
  39319. // Renderer can't be resized while presenting in XR.
  39320. if ( this.xr && this.xr.isPresenting ) return;
  39321. this._width = width;
  39322. this._height = height;
  39323. this.domElement.width = Math.floor( width * this._pixelRatio );
  39324. this.domElement.height = Math.floor( height * this._pixelRatio );
  39325. if ( updateStyle === true ) {
  39326. this.domElement.style.width = width + 'px';
  39327. this.domElement.style.height = height + 'px';
  39328. }
  39329. this.setViewport( 0, 0, width, height );
  39330. this._dispatchResize();
  39331. }
  39332. /**
  39333. * Returns the scissor rectangle.
  39334. *
  39335. * @param {Vector4} target - The method writes the result in this target object.
  39336. * @return {Vector4} The scissor rectangle.
  39337. */
  39338. getScissor( target ) {
  39339. const scissor = this._scissor;
  39340. target.x = scissor.x;
  39341. target.y = scissor.y;
  39342. target.width = scissor.width;
  39343. target.height = scissor.height;
  39344. return target;
  39345. }
  39346. /**
  39347. * Defines the scissor rectangle.
  39348. *
  39349. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  39350. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  39351. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  39352. * @param {number} width - The width of the scissor box in logical pixel unit.
  39353. * @param {number} height - The height of the scissor box in logical pixel unit.
  39354. */
  39355. setScissor( x, y, width, height ) {
  39356. const scissor = this._scissor;
  39357. if ( x.isVector4 ) {
  39358. scissor.copy( x );
  39359. } else {
  39360. scissor.set( x, y, width, height );
  39361. }
  39362. }
  39363. /**
  39364. * Returns the scissor test value.
  39365. *
  39366. * @return {boolean} Whether the scissor test should be enabled or not.
  39367. */
  39368. getScissorTest() {
  39369. return this._scissorTest;
  39370. }
  39371. /**
  39372. * Defines the scissor test.
  39373. *
  39374. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  39375. */
  39376. setScissorTest( boolean ) {
  39377. this._scissorTest = boolean;
  39378. }
  39379. /**
  39380. * Returns the viewport definition.
  39381. *
  39382. * @param {Vector4} target - The method writes the result in this target object.
  39383. * @return {Vector4} The viewport definition.
  39384. */
  39385. getViewport( target ) {
  39386. return target.copy( this._viewport );
  39387. }
  39388. /**
  39389. * Defines the viewport.
  39390. *
  39391. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39392. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39393. * @param {number} width - The width of the viewport in logical pixel unit.
  39394. * @param {number} height - The height of the viewport in logical pixel unit.
  39395. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  39396. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  39397. */
  39398. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  39399. const viewport = this._viewport;
  39400. if ( x.isVector4 ) {
  39401. viewport.copy( x );
  39402. } else {
  39403. viewport.set( x, y, width, height );
  39404. }
  39405. viewport.minDepth = minDepth;
  39406. viewport.maxDepth = maxDepth;
  39407. }
  39408. /**
  39409. * Dispatches the resize event.
  39410. *
  39411. * @private
  39412. */
  39413. _dispatchResize() {
  39414. this.dispatchEvent( { type: 'resize' } );
  39415. }
  39416. /**
  39417. * Frees the GPU-related resources allocated by this instance. Call this
  39418. * method whenever this instance is no longer used in your app.
  39419. *
  39420. * @fires RenderTarget#dispose
  39421. */
  39422. dispose() {
  39423. this.dispatchEvent( { type: 'dispose' } );
  39424. }
  39425. }
  39426. const _scene = /*@__PURE__*/ new Scene();
  39427. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  39428. const _screen = /*@__PURE__*/ new Vector4();
  39429. const _frustum = /*@__PURE__*/ new Frustum();
  39430. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  39431. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  39432. const _vector4 = /*@__PURE__*/ new Vector4();
  39433. /**
  39434. * Base class for renderers.
  39435. */
  39436. class Renderer {
  39437. /**
  39438. * Renderer options.
  39439. *
  39440. * @typedef {Object} Renderer~Options
  39441. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  39442. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  39443. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  39444. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  39445. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  39446. * @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
  39447. * to overwrite the default.
  39448. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  39449. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  39450. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  39451. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  39452. */
  39453. /**
  39454. * Constructs a new renderer.
  39455. *
  39456. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  39457. * @param {Renderer~Options} [parameters] - The configuration parameter.
  39458. */
  39459. constructor( backend, parameters = {} ) {
  39460. /**
  39461. * This flag can be used for type testing.
  39462. *
  39463. * @type {boolean}
  39464. * @readonly
  39465. * @default true
  39466. */
  39467. this.isRenderer = true;
  39468. //
  39469. const {
  39470. logarithmicDepthBuffer = false,
  39471. alpha = true,
  39472. depth = true,
  39473. stencil = false,
  39474. antialias = false,
  39475. samples = 0,
  39476. getFallback = null,
  39477. colorBufferType = HalfFloatType,
  39478. multiview = false
  39479. } = parameters;
  39480. /**
  39481. * A reference to the current backend.
  39482. *
  39483. * @type {Backend}
  39484. */
  39485. this.backend = backend;
  39486. /**
  39487. * Whether the renderer should automatically clear the current rendering target
  39488. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  39489. * or the current bound render target (custom framebuffer).
  39490. *
  39491. * @type {boolean}
  39492. * @default true
  39493. */
  39494. this.autoClear = true;
  39495. /**
  39496. * When `autoClear` is set to `true`, this property defines whether the renderer
  39497. * should clear the color buffer.
  39498. *
  39499. * @type {boolean}
  39500. * @default true
  39501. */
  39502. this.autoClearColor = true;
  39503. /**
  39504. * When `autoClear` is set to `true`, this property defines whether the renderer
  39505. * should clear the depth buffer.
  39506. *
  39507. * @type {boolean}
  39508. * @default true
  39509. */
  39510. this.autoClearDepth = true;
  39511. /**
  39512. * When `autoClear` is set to `true`, this property defines whether the renderer
  39513. * should clear the stencil buffer.
  39514. *
  39515. * @type {boolean}
  39516. * @default true
  39517. */
  39518. this.autoClearStencil = true;
  39519. /**
  39520. * Whether the default framebuffer should be transparent or opaque.
  39521. *
  39522. * @type {boolean}
  39523. * @default true
  39524. */
  39525. this.alpha = alpha;
  39526. /**
  39527. * Whether logarithmic depth buffer is enabled or not.
  39528. *
  39529. * @type {boolean}
  39530. * @default false
  39531. */
  39532. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  39533. /**
  39534. * Defines the output color space of the renderer.
  39535. *
  39536. * @type {string}
  39537. * @default SRGBColorSpace
  39538. */
  39539. this.outputColorSpace = SRGBColorSpace;
  39540. /**
  39541. * Defines the tone mapping of the renderer.
  39542. *
  39543. * @type {number}
  39544. * @default NoToneMapping
  39545. */
  39546. this.toneMapping = NoToneMapping;
  39547. /**
  39548. * Defines the tone mapping exposure.
  39549. *
  39550. * @type {number}
  39551. * @default 1
  39552. */
  39553. this.toneMappingExposure = 1.0;
  39554. /**
  39555. * Whether the renderer should sort its render lists or not.
  39556. *
  39557. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  39558. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  39559. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  39560. * e.g. manually determining each object's rendering order.
  39561. *
  39562. * @type {boolean}
  39563. * @default true
  39564. */
  39565. this.sortObjects = true;
  39566. /**
  39567. * Whether the default framebuffer should have a depth buffer or not.
  39568. *
  39569. * @type {boolean}
  39570. * @default true
  39571. */
  39572. this.depth = depth;
  39573. /**
  39574. * Whether the default framebuffer should have a stencil buffer or not.
  39575. *
  39576. * @type {boolean}
  39577. * @default false
  39578. */
  39579. this.stencil = stencil;
  39580. /**
  39581. * Holds a series of statistical information about the GPU memory
  39582. * and the rendering process. Useful for debugging and monitoring.
  39583. *
  39584. * @type {Info}
  39585. */
  39586. this.info = new Info();
  39587. /**
  39588. * Stores override nodes for specific transformations or calculations.
  39589. * These nodes can be used to replace default behavior in the rendering pipeline.
  39590. *
  39591. * @type {Object}
  39592. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  39593. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  39594. */
  39595. this.overrideNodes = {
  39596. modelViewMatrix: null,
  39597. modelNormalViewMatrix: null
  39598. };
  39599. /**
  39600. * The node library defines how certain library objects like materials, lights
  39601. * or tone mapping functions are mapped to node types. This is required since
  39602. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  39603. * be part of the scene graph, they are internally represented as nodes for
  39604. * further processing.
  39605. *
  39606. * @type {NodeLibrary}
  39607. */
  39608. this.library = new NodeLibrary();
  39609. /**
  39610. * A map-like data structure for managing lights.
  39611. *
  39612. * @type {Lighting}
  39613. */
  39614. this.lighting = new Lighting();
  39615. // internals
  39616. /**
  39617. * The number of MSAA samples.
  39618. *
  39619. * @private
  39620. * @type {number}
  39621. * @default 0
  39622. */
  39623. this._samples = samples || ( antialias === true ) ? 4 : 0;
  39624. /**
  39625. * OnCanvasTargetResize callback function.
  39626. *
  39627. * @private
  39628. * @type {Function}
  39629. */
  39630. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  39631. /**
  39632. * The canvas target for rendering.
  39633. *
  39634. * @private
  39635. * @type {CanvasTarget}
  39636. */
  39637. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  39638. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  39639. this._canvasTarget.isDefaultCanvasTarget = true;
  39640. /**
  39641. * The inspector provides information about the internal renderer state.
  39642. *
  39643. * @private
  39644. * @type {InspectorBase}
  39645. */
  39646. this._inspector = new InspectorBase();
  39647. this._inspector.setRenderer( this );
  39648. /**
  39649. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  39650. *
  39651. * @private
  39652. * @type {?Function}
  39653. */
  39654. this._getFallback = getFallback;
  39655. /**
  39656. * A reference to a renderer module for managing shader attributes.
  39657. *
  39658. * @private
  39659. * @type {?Attributes}
  39660. * @default null
  39661. */
  39662. this._attributes = null;
  39663. /**
  39664. * A reference to a renderer module for managing geometries.
  39665. *
  39666. * @private
  39667. * @type {?Geometries}
  39668. * @default null
  39669. */
  39670. this._geometries = null;
  39671. /**
  39672. * A reference to a renderer module for managing node related logic.
  39673. *
  39674. * @private
  39675. * @type {?Nodes}
  39676. * @default null
  39677. */
  39678. this._nodes = null;
  39679. /**
  39680. * A reference to a renderer module for managing the internal animation loop.
  39681. *
  39682. * @private
  39683. * @type {?Animation}
  39684. * @default null
  39685. */
  39686. this._animation = null;
  39687. /**
  39688. * A reference to a renderer module for managing shader program bindings.
  39689. *
  39690. * @private
  39691. * @type {?Bindings}
  39692. * @default null
  39693. */
  39694. this._bindings = null;
  39695. /**
  39696. * A reference to a renderer module for managing render objects.
  39697. *
  39698. * @private
  39699. * @type {?RenderObjects}
  39700. * @default null
  39701. */
  39702. this._objects = null;
  39703. /**
  39704. * A reference to a renderer module for managing render and compute pipelines.
  39705. *
  39706. * @private
  39707. * @type {?Pipelines}
  39708. * @default null
  39709. */
  39710. this._pipelines = null;
  39711. /**
  39712. * A reference to a renderer module for managing render bundles.
  39713. *
  39714. * @private
  39715. * @type {?RenderBundles}
  39716. * @default null
  39717. */
  39718. this._bundles = null;
  39719. /**
  39720. * A reference to a renderer module for managing render lists.
  39721. *
  39722. * @private
  39723. * @type {?RenderLists}
  39724. * @default null
  39725. */
  39726. this._renderLists = null;
  39727. /**
  39728. * A reference to a renderer module for managing render contexts.
  39729. *
  39730. * @private
  39731. * @type {?RenderContexts}
  39732. * @default null
  39733. */
  39734. this._renderContexts = null;
  39735. /**
  39736. * A reference to a renderer module for managing textures.
  39737. *
  39738. * @private
  39739. * @type {?Textures}
  39740. * @default null
  39741. */
  39742. this._textures = null;
  39743. /**
  39744. * A reference to a renderer module for backgrounds.
  39745. *
  39746. * @private
  39747. * @type {?Background}
  39748. * @default null
  39749. */
  39750. this._background = null;
  39751. /**
  39752. * This fullscreen quad is used for internal render passes
  39753. * like the tone mapping and color space output pass.
  39754. *
  39755. * @private
  39756. * @type {QuadMesh}
  39757. */
  39758. this._quad = new QuadMesh( new NodeMaterial() );
  39759. this._quad.name = 'Output Color Transform';
  39760. this._quad.material.name = 'outputColorTransform';
  39761. /**
  39762. * A reference to the current render context.
  39763. *
  39764. * @private
  39765. * @type {?RenderContext}
  39766. * @default null
  39767. */
  39768. this._currentRenderContext = null;
  39769. /**
  39770. * A custom sort function for the opaque render list.
  39771. *
  39772. * @private
  39773. * @type {?Function}
  39774. * @default null
  39775. */
  39776. this._opaqueSort = null;
  39777. /**
  39778. * A custom sort function for the transparent render list.
  39779. *
  39780. * @private
  39781. * @type {?Function}
  39782. * @default null
  39783. */
  39784. this._transparentSort = null;
  39785. /**
  39786. * The framebuffer target.
  39787. *
  39788. * @private
  39789. * @type {?RenderTarget}
  39790. * @default null
  39791. */
  39792. this._frameBufferTarget = null;
  39793. const alphaClear = this.alpha === true ? 0 : 1;
  39794. /**
  39795. * The clear color value.
  39796. *
  39797. * @private
  39798. * @type {Color4}
  39799. */
  39800. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  39801. /**
  39802. * The clear depth value.
  39803. *
  39804. * @private
  39805. * @type {number}
  39806. * @default 1
  39807. */
  39808. this._clearDepth = 1;
  39809. /**
  39810. * The clear stencil value.
  39811. *
  39812. * @private
  39813. * @type {number}
  39814. * @default 0
  39815. */
  39816. this._clearStencil = 0;
  39817. /**
  39818. * The current render target.
  39819. *
  39820. * @private
  39821. * @type {?RenderTarget}
  39822. * @default null
  39823. */
  39824. this._renderTarget = null;
  39825. /**
  39826. * The active cube face.
  39827. *
  39828. * @private
  39829. * @type {number}
  39830. * @default 0
  39831. */
  39832. this._activeCubeFace = 0;
  39833. /**
  39834. * The active mipmap level.
  39835. *
  39836. * @private
  39837. * @type {number}
  39838. * @default 0
  39839. */
  39840. this._activeMipmapLevel = 0;
  39841. /**
  39842. * The current output render target.
  39843. *
  39844. * @private
  39845. * @type {?RenderTarget}
  39846. * @default null
  39847. */
  39848. this._outputRenderTarget = null;
  39849. /**
  39850. * The MRT setting.
  39851. *
  39852. * @private
  39853. * @type {?MRTNode}
  39854. * @default null
  39855. */
  39856. this._mrt = null;
  39857. /**
  39858. * This function defines how a render object is going
  39859. * to be rendered.
  39860. *
  39861. * @private
  39862. * @type {?Function}
  39863. * @default null
  39864. */
  39865. this._renderObjectFunction = null;
  39866. /**
  39867. * Used to keep track of the current render object function.
  39868. *
  39869. * @private
  39870. * @type {?Function}
  39871. * @default null
  39872. */
  39873. this._currentRenderObjectFunction = null;
  39874. /**
  39875. * Used to keep track of the current render bundle.
  39876. *
  39877. * @private
  39878. * @type {?RenderBundle}
  39879. * @default null
  39880. */
  39881. this._currentRenderBundle = null;
  39882. /**
  39883. * Next to `_renderObjectFunction()`, this function provides another hook
  39884. * for influencing the render process of a render object. It is meant for internal
  39885. * use and only relevant for `compileAsync()` right now. Instead of using
  39886. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  39887. * a different function might be used which performs no draw but just the node
  39888. * and pipeline updates.
  39889. *
  39890. * @private
  39891. * @type {?Function}
  39892. * @default null
  39893. */
  39894. this._handleObjectFunction = this._renderObjectDirect;
  39895. /**
  39896. * Indicates whether the device has been lost or not. In WebGL terms, the device
  39897. * lost is considered as a context lost. When this is set to `true`, rendering
  39898. * isn't possible anymore.
  39899. *
  39900. * @private
  39901. * @type {boolean}
  39902. * @default false
  39903. */
  39904. this._isDeviceLost = false;
  39905. /**
  39906. * A callback function that defines what should happen when a device/context lost occurs.
  39907. *
  39908. * @type {Function}
  39909. */
  39910. this.onDeviceLost = this._onDeviceLost;
  39911. /**
  39912. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  39913. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  39914. * This will reduce rendering quality though.
  39915. *
  39916. * @private
  39917. * @type {number}
  39918. * @default HalfFloatType
  39919. */
  39920. this._colorBufferType = colorBufferType;
  39921. /**
  39922. * A cache for shadow nodes per material
  39923. *
  39924. * @private
  39925. * @type {WeakMap<Material, Object>}
  39926. */
  39927. this._cacheShadowNodes = new WeakMap();
  39928. /**
  39929. * Whether the renderer has been initialized or not.
  39930. *
  39931. * @private
  39932. * @type {boolean}
  39933. * @default false
  39934. */
  39935. this._initialized = false;
  39936. /**
  39937. * A reference to the promise which initializes the renderer.
  39938. *
  39939. * @private
  39940. * @type {?Promise<this>}
  39941. * @default null
  39942. */
  39943. this._initPromise = null;
  39944. /**
  39945. * An array of compilation promises which are used in `compileAsync()`.
  39946. *
  39947. * @private
  39948. * @type {?Array<Promise>}
  39949. * @default null
  39950. */
  39951. this._compilationPromises = null;
  39952. /**
  39953. * Whether the renderer should render transparent render objects or not.
  39954. *
  39955. * @type {boolean}
  39956. * @default true
  39957. */
  39958. this.transparent = true;
  39959. /**
  39960. * Whether the renderer should render opaque render objects or not.
  39961. *
  39962. * @type {boolean}
  39963. * @default true
  39964. */
  39965. this.opaque = true;
  39966. /**
  39967. * Shadow map configuration
  39968. * @typedef {Object} ShadowMapConfig
  39969. * @property {boolean} enabled - Whether to globally enable shadows or not.
  39970. * @property {number} type - The shadow map type.
  39971. */
  39972. /**
  39973. * The renderer's shadow configuration.
  39974. *
  39975. * @type {ShadowMapConfig}
  39976. */
  39977. this.shadowMap = {
  39978. enabled: false,
  39979. type: PCFShadowMap
  39980. };
  39981. /**
  39982. * XR configuration.
  39983. * @typedef {Object} XRConfig
  39984. * @property {boolean} enabled - Whether to globally enable XR or not.
  39985. */
  39986. /**
  39987. * The renderer's XR manager.
  39988. *
  39989. * @type {XRManager}
  39990. */
  39991. this.xr = new XRManager( this, multiview );
  39992. /**
  39993. * Debug configuration.
  39994. * @typedef {Object} DebugConfig
  39995. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  39996. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  39997. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  39998. */
  39999. /**
  40000. * The renderer's debug configuration.
  40001. *
  40002. * @type {DebugConfig}
  40003. */
  40004. this.debug = {
  40005. checkShaderErrors: true,
  40006. onShaderError: null,
  40007. getShaderAsync: async ( scene, camera, object ) => {
  40008. await this.compileAsync( scene, camera );
  40009. const renderList = this._renderLists.get( scene, camera );
  40010. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  40011. const material = scene.overrideMaterial || object.material;
  40012. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  40013. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  40014. return { fragmentShader, vertexShader };
  40015. }
  40016. };
  40017. }
  40018. /**
  40019. * Initializes the renderer so it is ready for usage.
  40020. *
  40021. * @async
  40022. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  40023. */
  40024. async init() {
  40025. if ( this._initPromise !== null ) {
  40026. return this._initPromise;
  40027. }
  40028. this._initPromise = new Promise( async ( resolve, reject ) => {
  40029. let backend = this.backend;
  40030. try {
  40031. await backend.init( this );
  40032. } catch ( error ) {
  40033. if ( this._getFallback !== null ) {
  40034. // try the fallback
  40035. try {
  40036. this.backend = backend = this._getFallback( error );
  40037. await backend.init( this );
  40038. } catch ( error ) {
  40039. reject( error );
  40040. return;
  40041. }
  40042. } else {
  40043. reject( error );
  40044. return;
  40045. }
  40046. }
  40047. this._nodes = new Nodes( this, backend );
  40048. this._animation = new Animation( this, this._nodes, this.info );
  40049. this._attributes = new Attributes( backend );
  40050. this._background = new Background( this, this._nodes );
  40051. this._geometries = new Geometries( this._attributes, this.info );
  40052. this._textures = new Textures( this, backend, this.info );
  40053. this._pipelines = new Pipelines( backend, this._nodes );
  40054. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  40055. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  40056. this._renderLists = new RenderLists( this.lighting );
  40057. this._bundles = new RenderBundles();
  40058. this._renderContexts = new RenderContexts();
  40059. //
  40060. this._animation.start();
  40061. this._initialized = true;
  40062. //
  40063. this._inspector.init();
  40064. //
  40065. resolve( this );
  40066. } );
  40067. return this._initPromise;
  40068. }
  40069. /**
  40070. * A reference to the canvas element the renderer is drawing to.
  40071. * This value of this property will automatically be created by
  40072. * the renderer.
  40073. *
  40074. * @type {HTMLCanvasElement|OffscreenCanvas}
  40075. */
  40076. get domElement() {
  40077. return this._canvasTarget.domElement;
  40078. }
  40079. /**
  40080. * The coordinate system of the renderer. The value of this property
  40081. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  40082. * `THREE.WebGPUCoordinateSystem`.
  40083. *
  40084. * @readonly
  40085. * @type {number}
  40086. */
  40087. get coordinateSystem() {
  40088. return this.backend.coordinateSystem;
  40089. }
  40090. /**
  40091. * Compiles all materials in the given scene. This can be useful to avoid a
  40092. * phenomenon which is called "shader compilation stutter", which occurs when
  40093. * rendering an object with a new shader for the first time.
  40094. *
  40095. * If you want to add a 3D object to an existing scene, use the third optional
  40096. * parameter for applying the target scene. Note that the (target) scene's lighting
  40097. * and environment must be configured before calling this method.
  40098. *
  40099. * @async
  40100. * @param {Object3D} scene - The scene or 3D object to precompile.
  40101. * @param {Camera} camera - The camera that is used to render the scene.
  40102. * @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.
  40103. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  40104. */
  40105. async compileAsync( scene, camera, targetScene = null ) {
  40106. if ( this._isDeviceLost === true ) return;
  40107. if ( this._initialized === false ) await this.init();
  40108. // preserve render tree
  40109. const nodeFrame = this._nodes.nodeFrame;
  40110. const previousRenderId = nodeFrame.renderId;
  40111. const previousRenderContext = this._currentRenderContext;
  40112. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  40113. const previousCompilationPromises = this._compilationPromises;
  40114. //
  40115. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  40116. if ( targetScene === null ) targetScene = scene;
  40117. const renderTarget = this._renderTarget;
  40118. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  40119. const activeMipmapLevel = this._activeMipmapLevel;
  40120. const compilationPromises = [];
  40121. this._currentRenderContext = renderContext;
  40122. this._currentRenderObjectFunction = this.renderObject;
  40123. this._handleObjectFunction = this._createObjectPipeline;
  40124. this._compilationPromises = compilationPromises;
  40125. nodeFrame.renderId ++;
  40126. //
  40127. nodeFrame.update();
  40128. //
  40129. renderContext.depth = this.depth;
  40130. renderContext.stencil = this.stencil;
  40131. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  40132. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  40133. //
  40134. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  40135. //
  40136. const renderList = this._renderLists.get( scene, camera );
  40137. renderList.begin();
  40138. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  40139. // include lights from target scene
  40140. if ( targetScene !== scene ) {
  40141. targetScene.traverseVisible( function ( object ) {
  40142. if ( object.isLight && object.layers.test( camera.layers ) ) {
  40143. renderList.pushLight( object );
  40144. }
  40145. } );
  40146. }
  40147. renderList.finish();
  40148. //
  40149. if ( renderTarget !== null ) {
  40150. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  40151. const renderTargetData = this._textures.get( renderTarget );
  40152. renderContext.textures = renderTargetData.textures;
  40153. renderContext.depthTexture = renderTargetData.depthTexture;
  40154. } else {
  40155. renderContext.textures = null;
  40156. renderContext.depthTexture = null;
  40157. }
  40158. //
  40159. this._background.update( sceneRef, renderList, renderContext );
  40160. // process render lists
  40161. const opaqueObjects = renderList.opaque;
  40162. const transparentObjects = renderList.transparent;
  40163. const transparentDoublePassObjects = renderList.transparentDoublePass;
  40164. const lightsNode = renderList.lightsNode;
  40165. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40166. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40167. // restore render tree
  40168. nodeFrame.renderId = previousRenderId;
  40169. this._currentRenderContext = previousRenderContext;
  40170. this._currentRenderObjectFunction = previousRenderObjectFunction;
  40171. this._compilationPromises = previousCompilationPromises;
  40172. this._handleObjectFunction = this._renderObjectDirect;
  40173. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  40174. await Promise.all( compilationPromises );
  40175. }
  40176. /**
  40177. * Renders the scene in an async fashion.
  40178. *
  40179. * @async
  40180. * @deprecated
  40181. * @param {Object3D} scene - The scene or 3D object to render.
  40182. * @param {Camera} camera - The camera.
  40183. * @return {Promise} A Promise that resolves when the render has been finished.
  40184. */
  40185. async renderAsync( scene, camera ) {
  40186. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  40187. await this.init();
  40188. this.render( scene, camera );
  40189. }
  40190. /**
  40191. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40192. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40193. *
  40194. * @async
  40195. * @deprecated
  40196. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40197. */
  40198. async waitForGPU() {
  40199. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  40200. }
  40201. //
  40202. /**
  40203. * Sets the inspector instance. The inspector can be any class that extends from `InspectorBase`.
  40204. *
  40205. * @param {InspectorBase} value - The new inspector.
  40206. */
  40207. set inspector( value ) {
  40208. if ( this._inspector !== null ) {
  40209. this._inspector.setRenderer( null );
  40210. }
  40211. this._inspector = value;
  40212. this._inspector.setRenderer( this );
  40213. }
  40214. get inspector() {
  40215. return this._inspector;
  40216. }
  40217. /**
  40218. * Enables or disables high precision for model-view and normal-view matrices.
  40219. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  40220. *
  40221. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  40222. *
  40223. * @param {boolean} value - Whether to enable or disable high precision.
  40224. * @type {boolean}
  40225. */
  40226. set highPrecision( value ) {
  40227. if ( value === true ) {
  40228. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  40229. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  40230. } else if ( this.highPrecision ) {
  40231. this.overrideNodes.modelViewMatrix = null;
  40232. this.overrideNodes.modelNormalViewMatrix = null;
  40233. }
  40234. }
  40235. /**
  40236. * Returns whether high precision is enabled or not.
  40237. *
  40238. * @return {boolean} Whether high precision is enabled or not.
  40239. * @type {boolean}
  40240. */
  40241. get highPrecision() {
  40242. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  40243. }
  40244. /**
  40245. * Sets the given MRT configuration.
  40246. *
  40247. * @param {MRTNode} mrt - The MRT node to set.
  40248. * @return {Renderer} A reference to this renderer.
  40249. */
  40250. setMRT( mrt ) {
  40251. this._mrt = mrt;
  40252. return this;
  40253. }
  40254. /**
  40255. * Returns the MRT configuration.
  40256. *
  40257. * @return {MRTNode} The MRT configuration.
  40258. */
  40259. getMRT() {
  40260. return this._mrt;
  40261. }
  40262. /**
  40263. * Returns the color buffer type.
  40264. *
  40265. * @return {number} The color buffer type.
  40266. */
  40267. getColorBufferType() {
  40268. return this._colorBufferType;
  40269. }
  40270. /**
  40271. * Default implementation of the device lost callback.
  40272. *
  40273. * @private
  40274. * @param {Object} info - Information about the context lost.
  40275. */
  40276. _onDeviceLost( info ) {
  40277. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  40278. if ( info.reason ) {
  40279. errorMessage += `\nReason: ${info.reason}`;
  40280. }
  40281. error( errorMessage );
  40282. this._isDeviceLost = true;
  40283. }
  40284. /**
  40285. * Renders the given render bundle.
  40286. *
  40287. * @private
  40288. * @param {Object} bundle - Render bundle data.
  40289. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  40290. * @param {LightsNode} lightsNode - The lights node.
  40291. */
  40292. _renderBundle( bundle, sceneRef, lightsNode ) {
  40293. const { bundleGroup, camera, renderList } = bundle;
  40294. const renderContext = this._currentRenderContext;
  40295. //
  40296. const renderBundle = this._bundles.get( bundleGroup, camera );
  40297. const renderBundleData = this.backend.get( renderBundle );
  40298. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  40299. //
  40300. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  40301. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  40302. renderBundleData.renderContexts.add( renderContext );
  40303. if ( renderBundleNeedsUpdate ) {
  40304. this.backend.beginBundle( renderContext );
  40305. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  40306. renderBundleData.renderObjects = [];
  40307. }
  40308. this._currentRenderBundle = renderBundle;
  40309. const {
  40310. transparentDoublePass: transparentDoublePassObjects,
  40311. transparent: transparentObjects,
  40312. opaque: opaqueObjects
  40313. } = renderList;
  40314. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40315. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40316. this._currentRenderBundle = null;
  40317. //
  40318. this.backend.finishBundle( renderContext, renderBundle );
  40319. renderBundleData.version = bundleGroup.version;
  40320. } else {
  40321. const { renderObjects } = renderBundleData;
  40322. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  40323. const renderObject = renderObjects[ i ];
  40324. if ( this._nodes.needsRefresh( renderObject ) ) {
  40325. this._nodes.updateBefore( renderObject );
  40326. this._nodes.updateForRender( renderObject );
  40327. this._bindings.updateForRender( renderObject );
  40328. this._nodes.updateAfter( renderObject );
  40329. }
  40330. }
  40331. }
  40332. this.backend.addBundle( renderContext, renderBundle );
  40333. }
  40334. /**
  40335. * Renders the scene or 3D object with the given camera. This method can only be called
  40336. * if the renderer has been initialized. When using `render()` inside an animation loop,
  40337. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  40338. * with {@link Renderer#setAnimationLoop} though.
  40339. *
  40340. * For all other use cases (like when using on-demand rendering), you must call
  40341. * {@link Renderer#init} before rendering.
  40342. *
  40343. * The target of the method is the default framebuffer (meaning the canvas)
  40344. * or alternatively a render target when specified via `setRenderTarget()`.
  40345. *
  40346. * @param {Object3D} scene - The scene or 3D object to render.
  40347. * @param {Camera} camera - The camera to render the scene with.
  40348. */
  40349. render( scene, camera ) {
  40350. if ( this._initialized === false ) {
  40351. throw new Error( 'Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  40352. }
  40353. this._renderScene( scene, camera );
  40354. }
  40355. /**
  40356. * Returns whether the renderer has been initialized or not.
  40357. *
  40358. * @readonly
  40359. * @return {boolean} Whether the renderer has been initialized or not.
  40360. */
  40361. get initialized() {
  40362. return this._initialized;
  40363. }
  40364. /**
  40365. * Returns an internal render target which is used when computing the output tone mapping
  40366. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  40367. * pass and not inline to achieve more correct results.
  40368. *
  40369. * @private
  40370. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  40371. */
  40372. _getFrameBufferTarget() {
  40373. const { currentToneMapping, currentColorSpace } = this;
  40374. const useToneMapping = currentToneMapping !== NoToneMapping;
  40375. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  40376. if ( useToneMapping === false && useColorSpace === false ) return null;
  40377. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  40378. const { depth, stencil } = this;
  40379. let frameBufferTarget = this._frameBufferTarget;
  40380. if ( frameBufferTarget === null ) {
  40381. frameBufferTarget = new RenderTarget( width, height, {
  40382. depthBuffer: depth,
  40383. stencilBuffer: stencil,
  40384. type: this._colorBufferType,
  40385. format: RGBAFormat,
  40386. colorSpace: ColorManagement.workingColorSpace,
  40387. generateMipmaps: false,
  40388. minFilter: LinearFilter,
  40389. magFilter: LinearFilter,
  40390. samples: this.samples
  40391. } );
  40392. frameBufferTarget.isPostProcessingRenderTarget = true;
  40393. this._frameBufferTarget = frameBufferTarget;
  40394. }
  40395. const outputRenderTarget = this.getOutputRenderTarget();
  40396. frameBufferTarget.depthBuffer = depth;
  40397. frameBufferTarget.stencilBuffer = stencil;
  40398. if ( outputRenderTarget !== null ) {
  40399. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  40400. } else {
  40401. frameBufferTarget.setSize( width, height, 1 );
  40402. }
  40403. const canvasTarget = this._canvasTarget;
  40404. frameBufferTarget.viewport.copy( canvasTarget._viewport );
  40405. frameBufferTarget.scissor.copy( canvasTarget._scissor );
  40406. frameBufferTarget.viewport.multiplyScalar( canvasTarget._pixelRatio );
  40407. frameBufferTarget.scissor.multiplyScalar( canvasTarget._pixelRatio );
  40408. frameBufferTarget.scissorTest = canvasTarget._scissorTest;
  40409. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  40410. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  40411. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  40412. return frameBufferTarget;
  40413. }
  40414. /**
  40415. * Renders the scene or 3D object with the given camera.
  40416. *
  40417. * @private
  40418. * @param {Object3D} scene - The scene or 3D object to render.
  40419. * @param {Camera} camera - The camera to render the scene with.
  40420. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  40421. * @return {RenderContext} The current render context.
  40422. */
  40423. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  40424. if ( this._isDeviceLost === true ) return;
  40425. //
  40426. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  40427. // preserve render tree
  40428. const nodeFrame = this._nodes.nodeFrame;
  40429. const previousRenderId = nodeFrame.renderId;
  40430. const previousRenderContext = this._currentRenderContext;
  40431. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  40432. //
  40433. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  40434. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  40435. const activeCubeFace = this._activeCubeFace;
  40436. const activeMipmapLevel = this._activeMipmapLevel;
  40437. //
  40438. let renderTarget;
  40439. if ( frameBufferTarget !== null ) {
  40440. renderTarget = frameBufferTarget;
  40441. this.setRenderTarget( renderTarget );
  40442. } else {
  40443. renderTarget = outputRenderTarget;
  40444. }
  40445. //
  40446. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  40447. this._currentRenderContext = renderContext;
  40448. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  40449. //
  40450. this.info.calls ++;
  40451. this.info.render.calls ++;
  40452. this.info.render.frameCalls ++;
  40453. nodeFrame.renderId = this.info.calls;
  40454. //
  40455. this.backend.updateTimeStampUID( renderContext );
  40456. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  40457. //
  40458. const coordinateSystem = this.coordinateSystem;
  40459. const xr = this.xr;
  40460. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  40461. camera.coordinateSystem = coordinateSystem;
  40462. camera.updateProjectionMatrix();
  40463. if ( camera.isArrayCamera ) {
  40464. for ( const subCamera of camera.cameras ) {
  40465. subCamera.coordinateSystem = coordinateSystem;
  40466. subCamera.updateProjectionMatrix();
  40467. }
  40468. }
  40469. }
  40470. //
  40471. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  40472. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  40473. if ( xr.enabled === true && xr.isPresenting === true ) {
  40474. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  40475. camera = xr.getCamera(); // use XR camera for rendering
  40476. }
  40477. //
  40478. const canvasTarget = this._canvasTarget;
  40479. let viewport = canvasTarget._viewport;
  40480. let scissor = canvasTarget._scissor;
  40481. let pixelRatio = canvasTarget._pixelRatio;
  40482. if ( renderTarget !== null ) {
  40483. viewport = renderTarget.viewport;
  40484. scissor = renderTarget.scissor;
  40485. pixelRatio = 1;
  40486. }
  40487. this.getDrawingBufferSize( _drawingBufferSize );
  40488. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  40489. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  40490. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  40491. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  40492. renderContext.viewportValue.width >>= activeMipmapLevel;
  40493. renderContext.viewportValue.height >>= activeMipmapLevel;
  40494. renderContext.viewportValue.minDepth = minDepth;
  40495. renderContext.viewportValue.maxDepth = maxDepth;
  40496. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  40497. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  40498. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  40499. renderContext.scissorValue.width >>= activeMipmapLevel;
  40500. renderContext.scissorValue.height >>= activeMipmapLevel;
  40501. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  40502. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  40503. //
  40504. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  40505. //
  40506. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  40507. if ( ! camera.isArrayCamera ) {
  40508. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  40509. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  40510. }
  40511. const renderList = this._renderLists.get( scene, camera );
  40512. renderList.begin();
  40513. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  40514. renderList.finish();
  40515. if ( this.sortObjects === true ) {
  40516. renderList.sort( this._opaqueSort, this._transparentSort );
  40517. }
  40518. //
  40519. if ( renderTarget !== null ) {
  40520. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  40521. const renderTargetData = this._textures.get( renderTarget );
  40522. renderContext.textures = renderTargetData.textures;
  40523. renderContext.depthTexture = renderTargetData.depthTexture;
  40524. renderContext.width = renderTargetData.width;
  40525. renderContext.height = renderTargetData.height;
  40526. renderContext.renderTarget = renderTarget;
  40527. renderContext.depth = renderTarget.depthBuffer;
  40528. renderContext.stencil = renderTarget.stencilBuffer;
  40529. } else {
  40530. renderContext.textures = null;
  40531. renderContext.depthTexture = null;
  40532. renderContext.width = _drawingBufferSize.width;
  40533. renderContext.height = _drawingBufferSize.height;
  40534. renderContext.depth = this.depth;
  40535. renderContext.stencil = this.stencil;
  40536. }
  40537. renderContext.width >>= activeMipmapLevel;
  40538. renderContext.height >>= activeMipmapLevel;
  40539. renderContext.activeCubeFace = activeCubeFace;
  40540. renderContext.activeMipmapLevel = activeMipmapLevel;
  40541. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  40542. //
  40543. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  40544. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  40545. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  40546. }
  40547. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  40548. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  40549. }
  40550. //
  40551. this._background.update( sceneRef, renderList, renderContext );
  40552. //
  40553. renderContext.camera = camera;
  40554. this.backend.beginRender( renderContext );
  40555. // process render lists
  40556. const {
  40557. bundles,
  40558. lightsNode,
  40559. transparentDoublePass: transparentDoublePassObjects,
  40560. transparent: transparentObjects,
  40561. opaque: opaqueObjects
  40562. } = renderList;
  40563. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  40564. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40565. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40566. // finish render pass
  40567. this.backend.finishRender( renderContext );
  40568. // restore render tree
  40569. nodeFrame.renderId = previousRenderId;
  40570. this._currentRenderContext = previousRenderContext;
  40571. this._currentRenderObjectFunction = previousRenderObjectFunction;
  40572. //
  40573. if ( frameBufferTarget !== null ) {
  40574. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  40575. this._renderOutput( renderTarget );
  40576. }
  40577. //
  40578. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  40579. //
  40580. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  40581. //
  40582. return renderContext;
  40583. }
  40584. _setXRLayerSize( width, height ) {
  40585. // TODO: Find a better solution to resize the canvas when in XR.
  40586. this._canvasTarget._width = width;
  40587. this._canvasTarget._height = height;
  40588. this.setViewport( 0, 0, width, height );
  40589. }
  40590. /**
  40591. * The output pass performs tone mapping and color space conversion.
  40592. *
  40593. * @private
  40594. * @param {RenderTarget} renderTarget - The current render target.
  40595. */
  40596. _renderOutput( renderTarget ) {
  40597. const quad = this._quad;
  40598. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  40599. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  40600. quad.material.needsUpdate = true;
  40601. }
  40602. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  40603. const currentAutoClear = this.autoClear;
  40604. const currentXR = this.xr.enabled;
  40605. this.autoClear = false;
  40606. this.xr.enabled = false;
  40607. this._renderScene( quad, quad.camera, false );
  40608. this.autoClear = currentAutoClear;
  40609. this.xr.enabled = currentXR;
  40610. }
  40611. /**
  40612. * Returns the maximum available anisotropy for texture filtering.
  40613. *
  40614. * @return {number} The maximum available anisotropy.
  40615. */
  40616. getMaxAnisotropy() {
  40617. return this.backend.getMaxAnisotropy();
  40618. }
  40619. /**
  40620. * Returns the active cube face.
  40621. *
  40622. * @return {number} The active cube face.
  40623. */
  40624. getActiveCubeFace() {
  40625. return this._activeCubeFace;
  40626. }
  40627. /**
  40628. * Returns the active mipmap level.
  40629. *
  40630. * @return {number} The active mipmap level.
  40631. */
  40632. getActiveMipmapLevel() {
  40633. return this._activeMipmapLevel;
  40634. }
  40635. /**
  40636. * Applications are advised to always define the animation loop
  40637. * with this method and not manually with `requestAnimationFrame()`
  40638. * for best compatibility.
  40639. *
  40640. * @async
  40641. * @param {?onAnimationCallback} callback - The application's animation loop.
  40642. * @return {Promise} A Promise that resolves when the set has been executed.
  40643. */
  40644. async setAnimationLoop( callback ) {
  40645. if ( this._initialized === false ) await this.init();
  40646. this._animation.setAnimationLoop( callback );
  40647. }
  40648. /**
  40649. * Returns the current animation loop callback.
  40650. *
  40651. * @return {?Function} The current animation loop callback.
  40652. */
  40653. getAnimationLoop() {
  40654. return this._animation.getAnimationLoop();
  40655. }
  40656. /**
  40657. * Can be used to transfer buffer data from a storage buffer attribute
  40658. * from the GPU to the CPU in context of compute shaders.
  40659. *
  40660. * @async
  40661. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40662. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40663. */
  40664. async getArrayBufferAsync( attribute ) {
  40665. return await this.backend.getArrayBufferAsync( attribute );
  40666. }
  40667. /**
  40668. * Returns the rendering context.
  40669. *
  40670. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  40671. */
  40672. getContext() {
  40673. return this.backend.getContext();
  40674. }
  40675. /**
  40676. * Returns the pixel ratio.
  40677. *
  40678. * @return {number} The pixel ratio.
  40679. */
  40680. getPixelRatio() {
  40681. return this._canvasTarget.getPixelRatio();
  40682. }
  40683. /**
  40684. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  40685. *
  40686. * @param {Vector2} target - The method writes the result in this target object.
  40687. * @return {Vector2} The drawing buffer size.
  40688. */
  40689. getDrawingBufferSize( target ) {
  40690. return this._canvasTarget.getDrawingBufferSize( target );
  40691. }
  40692. /**
  40693. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  40694. *
  40695. * @param {Vector2} target - The method writes the result in this target object.
  40696. * @return {Vector2} The renderer's size in logical pixels.
  40697. */
  40698. getSize( target ) {
  40699. return this._canvasTarget.getSize( target );
  40700. }
  40701. /**
  40702. * Sets the given pixel ratio and resizes the canvas if necessary.
  40703. *
  40704. * @param {number} [value=1] - The pixel ratio.
  40705. */
  40706. setPixelRatio( value = 1 ) {
  40707. this._canvasTarget.setPixelRatio( value );
  40708. }
  40709. /**
  40710. * This method allows to define the drawing buffer size by specifying
  40711. * width, height and pixel ratio all at once. The size of the drawing
  40712. * buffer is computed with this formula:
  40713. * ```js
  40714. * size.x = width * pixelRatio;
  40715. * size.y = height * pixelRatio;
  40716. * ```
  40717. *
  40718. * @param {number} width - The width in logical pixels.
  40719. * @param {number} height - The height in logical pixels.
  40720. * @param {number} pixelRatio - The pixel ratio.
  40721. */
  40722. setDrawingBufferSize( width, height, pixelRatio ) {
  40723. // Renderer can't be resized while presenting in XR.
  40724. if ( this.xr && this.xr.isPresenting ) return;
  40725. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  40726. }
  40727. /**
  40728. * Sets the size of the renderer.
  40729. *
  40730. * @param {number} width - The width in logical pixels.
  40731. * @param {number} height - The height in logical pixels.
  40732. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  40733. */
  40734. setSize( width, height, updateStyle = true ) {
  40735. // Renderer can't be resized while presenting in XR.
  40736. if ( this.xr && this.xr.isPresenting ) return;
  40737. this._canvasTarget.setSize( width, height, updateStyle );
  40738. }
  40739. /**
  40740. * Defines a manual sort function for the opaque render list.
  40741. * Pass `null` to use the default sort.
  40742. *
  40743. * @param {Function} method - The sort function.
  40744. */
  40745. setOpaqueSort( method ) {
  40746. this._opaqueSort = method;
  40747. }
  40748. /**
  40749. * Defines a manual sort function for the transparent render list.
  40750. * Pass `null` to use the default sort.
  40751. *
  40752. * @param {Function} method - The sort function.
  40753. */
  40754. setTransparentSort( method ) {
  40755. this._transparentSort = method;
  40756. }
  40757. /**
  40758. * Returns the scissor rectangle.
  40759. *
  40760. * @param {Vector4} target - The method writes the result in this target object.
  40761. * @return {Vector4} The scissor rectangle.
  40762. */
  40763. getScissor( target ) {
  40764. return this._canvasTarget.getScissor( target );
  40765. }
  40766. /**
  40767. * Defines the scissor rectangle.
  40768. *
  40769. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  40770. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  40771. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  40772. * @param {number} width - The width of the scissor box in logical pixel unit.
  40773. * @param {number} height - The height of the scissor box in logical pixel unit.
  40774. */
  40775. setScissor( x, y, width, height ) {
  40776. this._canvasTarget.setScissor( x, y, width, height );
  40777. }
  40778. /**
  40779. * Returns the scissor test value.
  40780. *
  40781. * @return {boolean} Whether the scissor test should be enabled or not.
  40782. */
  40783. getScissorTest() {
  40784. return this._canvasTarget.getScissorTest();
  40785. }
  40786. /**
  40787. * Defines the scissor test.
  40788. *
  40789. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40790. */
  40791. setScissorTest( boolean ) {
  40792. this._canvasTarget.setScissorTest( boolean );
  40793. // TODO: Move it to CanvasTarget event listener.
  40794. this.backend.setScissorTest( boolean );
  40795. }
  40796. /**
  40797. * Returns the viewport definition.
  40798. *
  40799. * @param {Vector4} target - The method writes the result in this target object.
  40800. * @return {Vector4} The viewport definition.
  40801. */
  40802. getViewport( target ) {
  40803. return this._canvasTarget.getViewport( target );
  40804. }
  40805. /**
  40806. * Defines the viewport.
  40807. *
  40808. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40809. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40810. * @param {number} width - The width of the viewport in logical pixel unit.
  40811. * @param {number} height - The height of the viewport in logical pixel unit.
  40812. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  40813. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  40814. */
  40815. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  40816. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  40817. }
  40818. /**
  40819. * Returns the clear color.
  40820. *
  40821. * @param {Color} target - The method writes the result in this target object.
  40822. * @return {Color} The clear color.
  40823. */
  40824. getClearColor( target ) {
  40825. return target.copy( this._clearColor );
  40826. }
  40827. /**
  40828. * Defines the clear color and optionally the clear alpha.
  40829. *
  40830. * @param {Color} color - The clear color.
  40831. * @param {number} [alpha=1] - The clear alpha.
  40832. */
  40833. setClearColor( color, alpha = 1 ) {
  40834. this._clearColor.set( color );
  40835. this._clearColor.a = alpha;
  40836. }
  40837. /**
  40838. * Returns the clear alpha.
  40839. *
  40840. * @return {number} The clear alpha.
  40841. */
  40842. getClearAlpha() {
  40843. return this._clearColor.a;
  40844. }
  40845. /**
  40846. * Defines the clear alpha.
  40847. *
  40848. * @param {number} alpha - The clear alpha.
  40849. */
  40850. setClearAlpha( alpha ) {
  40851. this._clearColor.a = alpha;
  40852. }
  40853. /**
  40854. * Returns the clear depth.
  40855. *
  40856. * @return {number} The clear depth.
  40857. */
  40858. getClearDepth() {
  40859. return this._clearDepth;
  40860. }
  40861. /**
  40862. * Defines the clear depth.
  40863. *
  40864. * @param {number} depth - The clear depth.
  40865. */
  40866. setClearDepth( depth ) {
  40867. this._clearDepth = depth;
  40868. }
  40869. /**
  40870. * Returns the clear stencil.
  40871. *
  40872. * @return {number} The clear stencil.
  40873. */
  40874. getClearStencil() {
  40875. return this._clearStencil;
  40876. }
  40877. /**
  40878. * Defines the clear stencil.
  40879. *
  40880. * @param {number} stencil - The clear stencil.
  40881. */
  40882. setClearStencil( stencil ) {
  40883. this._clearStencil = stencil;
  40884. }
  40885. /**
  40886. * This method performs an occlusion query for the given 3D object.
  40887. * It returns `true` if the given 3D object is fully occluded by other
  40888. * 3D objects in the scene.
  40889. *
  40890. * @param {Object3D} object - The 3D object to test.
  40891. * @return {boolean} Whether the 3D object is fully occluded or not.
  40892. */
  40893. isOccluded( object ) {
  40894. const renderContext = this._currentRenderContext;
  40895. return renderContext && this.backend.isOccluded( renderContext, object );
  40896. }
  40897. /**
  40898. * Performs a manual clear operation. This method ignores `autoClear` properties.
  40899. *
  40900. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  40901. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  40902. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  40903. */
  40904. clear( color = true, depth = true, stencil = true ) {
  40905. if ( this._initialized === false ) {
  40906. throw new Error( 'Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  40907. }
  40908. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  40909. let renderContext = null;
  40910. if ( renderTarget !== null ) {
  40911. this._textures.updateRenderTarget( renderTarget );
  40912. const renderTargetData = this._textures.get( renderTarget );
  40913. renderContext = this._renderContexts.getForClear( renderTarget );
  40914. renderContext.textures = renderTargetData.textures;
  40915. renderContext.depthTexture = renderTargetData.depthTexture;
  40916. renderContext.width = renderTargetData.width;
  40917. renderContext.height = renderTargetData.height;
  40918. renderContext.renderTarget = renderTarget;
  40919. renderContext.depth = renderTarget.depthBuffer;
  40920. renderContext.stencil = renderTarget.stencilBuffer;
  40921. // #30329
  40922. renderContext.clearColorValue = this.backend.getClearColor();
  40923. renderContext.activeCubeFace = this.getActiveCubeFace();
  40924. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  40925. }
  40926. this.backend.clear( color, depth, stencil, renderContext );
  40927. if ( renderTarget !== null && this._renderTarget === null ) {
  40928. this._renderOutput( renderTarget );
  40929. }
  40930. }
  40931. /**
  40932. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  40933. */
  40934. clearColor() {
  40935. this.clear( true, false, false );
  40936. }
  40937. /**
  40938. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  40939. */
  40940. clearDepth() {
  40941. this.clear( false, true, false );
  40942. }
  40943. /**
  40944. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  40945. */
  40946. clearStencil() {
  40947. this.clear( false, false, true );
  40948. }
  40949. /**
  40950. * Async version of {@link Renderer#clear}.
  40951. *
  40952. * @async
  40953. * @deprecated
  40954. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  40955. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  40956. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  40957. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40958. */
  40959. async clearAsync( color = true, depth = true, stencil = true ) {
  40960. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  40961. await this.init();
  40962. this.clear( color, depth, stencil );
  40963. }
  40964. /**
  40965. * Async version of {@link Renderer#clearColor}.
  40966. *
  40967. * @async
  40968. * @deprecated
  40969. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40970. */
  40971. async clearColorAsync() {
  40972. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  40973. this.clear( true, false, false );
  40974. }
  40975. /**
  40976. * Async version of {@link Renderer#clearDepth}.
  40977. *
  40978. * @async
  40979. * @deprecated
  40980. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40981. */
  40982. async clearDepthAsync() {
  40983. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  40984. this.clear( false, true, false );
  40985. }
  40986. /**
  40987. * Async version of {@link Renderer#clearStencil}.
  40988. *
  40989. * @async
  40990. * @deprecated
  40991. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40992. */
  40993. async clearStencilAsync() {
  40994. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  40995. this.clear( false, false, true );
  40996. }
  40997. /**
  40998. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  40999. * If this is the case, the renderer allocates an internal render target for that purpose.
  41000. *
  41001. */
  41002. get needsFrameBufferTarget() {
  41003. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  41004. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  41005. return useToneMapping || useColorSpace;
  41006. }
  41007. /**
  41008. * The number of samples used for multi-sample anti-aliasing (MSAA).
  41009. *
  41010. * @type {number}
  41011. * @default 0
  41012. */
  41013. get samples() {
  41014. return this._samples;
  41015. }
  41016. /**
  41017. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  41018. *
  41019. * When rendering to a custom render target, the number of samples of that render target is used.
  41020. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  41021. * the number of samples is set to 0.
  41022. *
  41023. * @type {number}
  41024. */
  41025. get currentSamples() {
  41026. let samples = this._samples;
  41027. if ( this._renderTarget !== null ) {
  41028. samples = this._renderTarget.samples;
  41029. } else if ( this.needsFrameBufferTarget ) {
  41030. samples = 0;
  41031. }
  41032. return samples;
  41033. }
  41034. /**
  41035. * The current tone mapping of the renderer. When not producing screen output,
  41036. * the tone mapping is always `NoToneMapping`.
  41037. *
  41038. * @type {number}
  41039. */
  41040. get currentToneMapping() {
  41041. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  41042. }
  41043. /**
  41044. * The current color space of the renderer. When not producing screen output,
  41045. * the color space is always the working color space.
  41046. *
  41047. * @type {string}
  41048. */
  41049. get currentColorSpace() {
  41050. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  41051. }
  41052. /**
  41053. * Returns `true` if the rendering settings are set to screen output.
  41054. *
  41055. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  41056. */
  41057. get isOutputTarget() {
  41058. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  41059. }
  41060. /**
  41061. * Frees all internal resources of the renderer. Call this method if the renderer
  41062. * is no longer in use by your app.
  41063. */
  41064. dispose() {
  41065. if ( this._initialized === true ) {
  41066. this.info.dispose();
  41067. this.backend.dispose();
  41068. this._animation.dispose();
  41069. this._objects.dispose();
  41070. this._geometries.dispose();
  41071. this._pipelines.dispose();
  41072. this._nodes.dispose();
  41073. this._bindings.dispose();
  41074. this._renderLists.dispose();
  41075. this._renderContexts.dispose();
  41076. this._textures.dispose();
  41077. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  41078. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  41079. if ( queryPool !== null ) queryPool.dispose();
  41080. } );
  41081. }
  41082. this.setRenderTarget( null );
  41083. this.setAnimationLoop( null );
  41084. }
  41085. /**
  41086. * Sets the given render target. Calling this method means the renderer does not
  41087. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  41088. * Use `null` as the first argument to reset the state.
  41089. *
  41090. * @param {?RenderTarget} renderTarget - The render target to set.
  41091. * @param {number} [activeCubeFace=0] - The active cube face.
  41092. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  41093. */
  41094. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  41095. this._renderTarget = renderTarget;
  41096. this._activeCubeFace = activeCubeFace;
  41097. this._activeMipmapLevel = activeMipmapLevel;
  41098. }
  41099. /**
  41100. * Returns the current render target.
  41101. *
  41102. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  41103. */
  41104. getRenderTarget() {
  41105. return this._renderTarget;
  41106. }
  41107. /**
  41108. * Sets the output render target for the renderer.
  41109. *
  41110. * @param {Object} renderTarget - The render target to set as the output target.
  41111. */
  41112. setOutputRenderTarget( renderTarget ) {
  41113. this._outputRenderTarget = renderTarget;
  41114. }
  41115. /**
  41116. * Returns the current output target.
  41117. *
  41118. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  41119. */
  41120. getOutputRenderTarget() {
  41121. return this._outputRenderTarget;
  41122. }
  41123. /**
  41124. * Sets the canvas target. The canvas target manages the HTML canvas
  41125. * or the offscreen canvas the renderer draws into.
  41126. *
  41127. * @param {CanvasTarget} canvasTarget - The canvas target.
  41128. */
  41129. setCanvasTarget( canvasTarget ) {
  41130. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  41131. this._canvasTarget = canvasTarget;
  41132. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  41133. }
  41134. /**
  41135. * Returns the current canvas target.
  41136. *
  41137. * @return {CanvasTarget} The current canvas target.
  41138. */
  41139. getCanvasTarget() {
  41140. return this._canvasTarget;
  41141. }
  41142. /**
  41143. * Resets the renderer to the initial state before WebXR started.
  41144. *
  41145. */
  41146. _resetXRState() {
  41147. this.backend.setXRTarget( null );
  41148. this.setOutputRenderTarget( null );
  41149. this.setRenderTarget( null );
  41150. this._frameBufferTarget.dispose();
  41151. this._frameBufferTarget = null;
  41152. }
  41153. /**
  41154. * Callback for {@link Renderer#setRenderObjectFunction}.
  41155. *
  41156. * @callback renderObjectFunction
  41157. * @param {Object3D} object - The 3D object.
  41158. * @param {Scene} scene - The scene the 3D object belongs to.
  41159. * @param {Camera} camera - The camera the object should be rendered with.
  41160. * @param {BufferGeometry} geometry - The object's geometry.
  41161. * @param {Material} material - The object's material.
  41162. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41163. * @param {LightsNode} lightsNode - The current lights node.
  41164. * @param {ClippingContext} clippingContext - The clipping context.
  41165. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41166. */
  41167. /**
  41168. * Sets the given render object function. Calling this method overwrites the default implementation
  41169. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  41170. * if you want to modify the way objects are rendered. For example you can define things like "every
  41171. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  41172. * The custom function must always call `renderObject()` in its implementation.
  41173. *
  41174. * Use `null` as the first argument to reset the state.
  41175. *
  41176. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  41177. */
  41178. setRenderObjectFunction( renderObjectFunction ) {
  41179. this._renderObjectFunction = renderObjectFunction;
  41180. }
  41181. /**
  41182. * Returns the current render object function.
  41183. *
  41184. * @return {?Function} The current render object function. Returns `null` if no function is set.
  41185. */
  41186. getRenderObjectFunction() {
  41187. return this._renderObjectFunction;
  41188. }
  41189. /**
  41190. * Execute a single or an array of compute nodes. This method can only be called
  41191. * if the renderer has been initialized.
  41192. *
  41193. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  41194. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  41195. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  41196. */
  41197. compute( computeNodes, dispatchSizeOrCount = null ) {
  41198. if ( this._isDeviceLost === true ) return;
  41199. if ( this._initialized === false ) {
  41200. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  41201. return this.computeAsync( computeNodes );
  41202. }
  41203. //
  41204. const nodeFrame = this._nodes.nodeFrame;
  41205. const previousRenderId = nodeFrame.renderId;
  41206. //
  41207. this.info.calls ++;
  41208. this.info.compute.calls ++;
  41209. this.info.compute.frameCalls ++;
  41210. nodeFrame.renderId = this.info.calls;
  41211. //
  41212. this.backend.updateTimeStampUID( computeNodes );
  41213. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  41214. //
  41215. const backend = this.backend;
  41216. const pipelines = this._pipelines;
  41217. const bindings = this._bindings;
  41218. const nodes = this._nodes;
  41219. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  41220. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  41221. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  41222. }
  41223. backend.beginCompute( computeNodes );
  41224. for ( const computeNode of computeList ) {
  41225. // onInit
  41226. if ( pipelines.has( computeNode ) === false ) {
  41227. const dispose = () => {
  41228. computeNode.removeEventListener( 'dispose', dispose );
  41229. pipelines.delete( computeNode );
  41230. bindings.deleteForCompute( computeNode );
  41231. nodes.delete( computeNode );
  41232. };
  41233. computeNode.addEventListener( 'dispose', dispose );
  41234. //
  41235. const onInitFn = computeNode.onInitFunction;
  41236. if ( onInitFn !== null ) {
  41237. onInitFn.call( computeNode, { renderer: this } );
  41238. }
  41239. }
  41240. nodes.updateForCompute( computeNode );
  41241. bindings.updateForCompute( computeNode );
  41242. const computeBindings = bindings.getForCompute( computeNode );
  41243. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  41244. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSizeOrCount );
  41245. }
  41246. backend.finishCompute( computeNodes );
  41247. //
  41248. nodeFrame.renderId = previousRenderId;
  41249. //
  41250. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  41251. }
  41252. /**
  41253. * Execute a single or an array of compute nodes.
  41254. *
  41255. * @async
  41256. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  41257. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  41258. * @return {Promise} A Promise that resolve when the compute has finished.
  41259. */
  41260. async computeAsync( computeNodes, dispatchSizeOrCount = null ) {
  41261. warnOnce( 'Renderer: "computeAsync()" has been deprecated. Use "compute()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41262. await this.init();
  41263. this.compute( computeNodes, dispatchSizeOrCount );
  41264. }
  41265. /**
  41266. * Checks if the given feature is supported by the selected backend.
  41267. *
  41268. * @async
  41269. * @deprecated
  41270. * @param {string} name - The feature's name.
  41271. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  41272. */
  41273. async hasFeatureAsync( name ) {
  41274. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41275. await this.init();
  41276. return this.hasFeature( name );
  41277. }
  41278. async resolveTimestampsAsync( type = 'render' ) {
  41279. if ( this._initialized === false ) await this.init();
  41280. return this.backend.resolveTimestampsAsync( type );
  41281. }
  41282. /**
  41283. * Checks if the given feature is supported by the selected backend. If the
  41284. * renderer has not been initialized, this method always returns `false`.
  41285. *
  41286. * @param {string} name - The feature's name.
  41287. * @return {boolean} Whether the feature is supported or not.
  41288. */
  41289. hasFeature( name ) {
  41290. if ( this._initialized === false ) {
  41291. throw new Error( 'Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  41292. }
  41293. return this.backend.hasFeature( name );
  41294. }
  41295. /**
  41296. * Returns `true` when the renderer has been initialized.
  41297. *
  41298. * @return {boolean} Whether the renderer has been initialized or not.
  41299. */
  41300. hasInitialized() {
  41301. return this._initialized;
  41302. }
  41303. /**
  41304. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  41305. * (which can cause noticeable lags due to decode and GPU upload overhead).
  41306. *
  41307. * @async
  41308. * @deprecated
  41309. * @param {Texture} texture - The texture.
  41310. * @return {Promise} A Promise that resolves when the texture has been initialized.
  41311. */
  41312. async initTextureAsync( texture ) {
  41313. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41314. await this.init();
  41315. this.initTexture( texture );
  41316. }
  41317. /**
  41318. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  41319. * (which can cause noticeable lags due to decode and GPU upload overhead).
  41320. *
  41321. * This method can only be used if the renderer has been initialized.
  41322. *
  41323. * @param {Texture} texture - The texture.
  41324. */
  41325. initTexture( texture ) {
  41326. if ( this._initialized === false ) {
  41327. throw new Error( 'Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  41328. }
  41329. this._textures.updateTexture( texture );
  41330. }
  41331. /**
  41332. * Copies the current bound framebuffer into the given texture.
  41333. *
  41334. * @param {FramebufferTexture} framebufferTexture - The texture.
  41335. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  41336. */
  41337. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  41338. if ( rectangle !== null ) {
  41339. if ( rectangle.isVector2 ) {
  41340. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  41341. } else if ( rectangle.isVector4 ) {
  41342. rectangle = _vector4.copy( rectangle ).floor();
  41343. } else {
  41344. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  41345. return;
  41346. }
  41347. } else {
  41348. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  41349. }
  41350. //
  41351. let renderContext = this._currentRenderContext;
  41352. let renderTarget;
  41353. if ( renderContext !== null ) {
  41354. renderTarget = renderContext.renderTarget;
  41355. } else {
  41356. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  41357. if ( renderTarget !== null ) {
  41358. this._textures.updateRenderTarget( renderTarget );
  41359. renderContext = this._textures.get( renderTarget );
  41360. }
  41361. }
  41362. //
  41363. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  41364. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  41365. this._inspector.copyFramebufferToTexture( framebufferTexture );
  41366. }
  41367. /**
  41368. * Copies data of the given source texture into a destination texture.
  41369. *
  41370. * @param {Texture} srcTexture - The source texture.
  41371. * @param {Texture} dstTexture - The destination texture.
  41372. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  41373. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  41374. * @param {number} [srcLevel=0] - The source mip level to copy from.
  41375. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  41376. */
  41377. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  41378. this._textures.updateTexture( srcTexture );
  41379. this._textures.updateTexture( dstTexture );
  41380. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  41381. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  41382. }
  41383. /**
  41384. * Reads pixel data from the given render target.
  41385. *
  41386. * @async
  41387. * @param {RenderTarget} renderTarget - The render target to read from.
  41388. * @param {number} x - The `x` coordinate of the copy region's origin.
  41389. * @param {number} y - The `y` coordinate of the copy region's origin.
  41390. * @param {number} width - The width of the copy region.
  41391. * @param {number} height - The height of the copy region.
  41392. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  41393. * @param {number} [faceIndex=0] - The active cube face index.
  41394. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  41395. */
  41396. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  41397. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  41398. }
  41399. /**
  41400. * Analyzes the given 3D object's hierarchy and builds render lists from the
  41401. * processed hierarchy.
  41402. *
  41403. * @param {Object3D} object - The 3D object to process (usually a scene).
  41404. * @param {Camera} camera - The camera the object is rendered with.
  41405. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  41406. * @param {RenderList} renderList - The current render list.
  41407. * @param {ClippingContext} clippingContext - The current clipping context.
  41408. */
  41409. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  41410. if ( object.visible === false ) return;
  41411. const visible = object.layers.test( camera.layers );
  41412. if ( visible ) {
  41413. if ( object.isGroup ) {
  41414. groupOrder = object.renderOrder;
  41415. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  41416. } else if ( object.isLOD ) {
  41417. if ( object.autoUpdate === true ) object.update( camera );
  41418. } else if ( object.isLight ) {
  41419. renderList.pushLight( object );
  41420. } else if ( object.isSprite ) {
  41421. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41422. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  41423. if ( this.sortObjects === true ) {
  41424. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  41425. }
  41426. const { geometry, material } = object;
  41427. if ( material.visible ) {
  41428. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  41429. }
  41430. }
  41431. } else if ( object.isLineLoop ) {
  41432. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  41433. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  41434. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41435. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  41436. const { geometry, material } = object;
  41437. if ( this.sortObjects === true ) {
  41438. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  41439. _vector4
  41440. .copy( geometry.boundingSphere.center )
  41441. .applyMatrix4( object.matrixWorld )
  41442. .applyMatrix4( _projScreenMatrix );
  41443. }
  41444. if ( Array.isArray( material ) ) {
  41445. const groups = geometry.groups;
  41446. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  41447. const group = groups[ i ];
  41448. const groupMaterial = material[ group.materialIndex ];
  41449. if ( groupMaterial && groupMaterial.visible ) {
  41450. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  41451. }
  41452. }
  41453. } else if ( material.visible ) {
  41454. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  41455. }
  41456. }
  41457. }
  41458. }
  41459. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  41460. const baseRenderList = renderList;
  41461. // replace render list
  41462. renderList = this._renderLists.get( object, camera );
  41463. renderList.begin();
  41464. baseRenderList.pushBundle( {
  41465. bundleGroup: object,
  41466. camera,
  41467. renderList,
  41468. } );
  41469. renderList.finish();
  41470. }
  41471. const children = object.children;
  41472. for ( let i = 0, l = children.length; i < l; i ++ ) {
  41473. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  41474. }
  41475. }
  41476. /**
  41477. * Renders the given render bundles.
  41478. *
  41479. * @private
  41480. * @param {Array<Object>} bundles - Array with render bundle data.
  41481. * @param {Scene} sceneRef - The scene the render bundles belong to.
  41482. * @param {LightsNode} lightsNode - The current lights node.
  41483. */
  41484. _renderBundles( bundles, sceneRef, lightsNode ) {
  41485. for ( const bundle of bundles ) {
  41486. this._renderBundle( bundle, sceneRef, lightsNode );
  41487. }
  41488. }
  41489. /**
  41490. * Renders the transparent objects from the given render lists.
  41491. *
  41492. * @private
  41493. * @param {Array<Object>} renderList - The transparent render list.
  41494. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  41495. * @param {Camera} camera - The camera the render list should be rendered with.
  41496. * @param {Scene} scene - The scene the render list belongs to.
  41497. * @param {LightsNode} lightsNode - The current lights node.
  41498. */
  41499. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  41500. if ( doublePassList.length > 0 ) {
  41501. // render back side
  41502. for ( const { material } of doublePassList ) {
  41503. material.side = BackSide;
  41504. }
  41505. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  41506. // render front side
  41507. for ( const { material } of doublePassList ) {
  41508. material.side = FrontSide;
  41509. }
  41510. this._renderObjects( renderList, camera, scene, lightsNode );
  41511. // restore
  41512. for ( const { material } of doublePassList ) {
  41513. material.side = DoubleSide;
  41514. }
  41515. } else {
  41516. this._renderObjects( renderList, camera, scene, lightsNode );
  41517. }
  41518. }
  41519. /**
  41520. * Renders the objects from the given render list.
  41521. *
  41522. * @private
  41523. * @param {Array<Object>} renderList - The render list.
  41524. * @param {Camera} camera - The camera the render list should be rendered with.
  41525. * @param {Scene} scene - The scene the render list belongs to.
  41526. * @param {LightsNode} lightsNode - The current lights node.
  41527. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41528. */
  41529. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  41530. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  41531. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  41532. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  41533. }
  41534. }
  41535. /**
  41536. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  41537. * The result is cached per material and updated when the material's version changes.
  41538. *
  41539. * @param {Material} material
  41540. * @returns {Object} - The shadow nodes for the material.
  41541. */
  41542. _getShadowNodes( material ) {
  41543. const version = material.version;
  41544. let cache = this._cacheShadowNodes.get( material );
  41545. if ( cache === undefined || cache.version !== version ) {
  41546. const hasMap = material.map !== null;
  41547. const hasColorNode = material.colorNode && material.colorNode.isNode;
  41548. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  41549. let positionNode = null;
  41550. let colorNode = null;
  41551. let depthNode = null;
  41552. if ( hasMap || hasColorNode || hasCastShadowNode ) {
  41553. let shadowRGB;
  41554. let shadowAlpha;
  41555. if ( hasCastShadowNode ) {
  41556. shadowRGB = material.castShadowNode.rgb;
  41557. shadowAlpha = material.castShadowNode.a;
  41558. } else {
  41559. shadowRGB = vec3( 0 );
  41560. shadowAlpha = float( 1 );
  41561. }
  41562. if ( hasMap ) {
  41563. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  41564. }
  41565. if ( hasColorNode ) {
  41566. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  41567. }
  41568. colorNode = vec4( shadowRGB, shadowAlpha );
  41569. }
  41570. if ( material.depthNode && material.depthNode.isNode ) {
  41571. depthNode = material.depthNode;
  41572. }
  41573. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  41574. positionNode = material.castShadowPositionNode;
  41575. } else if ( material.positionNode && material.positionNode.isNode ) {
  41576. positionNode = material.positionNode;
  41577. }
  41578. cache = {
  41579. version,
  41580. colorNode,
  41581. depthNode,
  41582. positionNode
  41583. };
  41584. this._cacheShadowNodes.set( material, cache );
  41585. }
  41586. return cache;
  41587. }
  41588. /**
  41589. * This method represents the default render object function that manages the render lifecycle
  41590. * of the object.
  41591. *
  41592. * @param {Object3D} object - The 3D object.
  41593. * @param {Scene} scene - The scene the 3D object belongs to.
  41594. * @param {Camera} camera - The camera the object should be rendered with.
  41595. * @param {BufferGeometry} geometry - The object's geometry.
  41596. * @param {Material} material - The object's material.
  41597. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41598. * @param {LightsNode} lightsNode - The current lights node.
  41599. * @param {?ClippingContext} clippingContext - The clipping context.
  41600. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41601. */
  41602. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  41603. let materialOverride = false;
  41604. let materialColorNode;
  41605. let materialDepthNode;
  41606. let materialPositionNode;
  41607. let materialSide;
  41608. //
  41609. object.onBeforeRender( this, scene, camera, geometry, material, group );
  41610. //
  41611. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  41612. const overrideMaterial = scene.overrideMaterial;
  41613. materialOverride = true;
  41614. // store original nodes
  41615. materialColorNode = scene.overrideMaterial.colorNode;
  41616. materialDepthNode = scene.overrideMaterial.depthNode;
  41617. materialPositionNode = scene.overrideMaterial.positionNode;
  41618. materialSide = scene.overrideMaterial.side;
  41619. if ( material.positionNode && material.positionNode.isNode ) {
  41620. overrideMaterial.positionNode = material.positionNode;
  41621. }
  41622. overrideMaterial.alphaTest = material.alphaTest;
  41623. overrideMaterial.alphaMap = material.alphaMap;
  41624. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  41625. if ( overrideMaterial.isShadowPassMaterial ) {
  41626. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  41627. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  41628. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  41629. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  41630. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  41631. }
  41632. material = overrideMaterial;
  41633. }
  41634. //
  41635. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  41636. material.side = BackSide;
  41637. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  41638. material.side = FrontSide;
  41639. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  41640. material.side = DoubleSide;
  41641. } else {
  41642. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  41643. }
  41644. //
  41645. if ( materialOverride ) {
  41646. scene.overrideMaterial.colorNode = materialColorNode;
  41647. scene.overrideMaterial.depthNode = materialDepthNode;
  41648. scene.overrideMaterial.positionNode = materialPositionNode;
  41649. scene.overrideMaterial.side = materialSide;
  41650. }
  41651. //
  41652. object.onAfterRender( this, scene, camera, geometry, material, group );
  41653. }
  41654. /**
  41655. * This method represents the default `_handleObjectFunction` implementation which creates
  41656. * a render object from the given data and performs the draw command with the selected backend.
  41657. *
  41658. * @private
  41659. * @param {Object3D} object - The 3D object.
  41660. * @param {Material} material - The object's material.
  41661. * @param {Scene} scene - The scene the 3D object belongs to.
  41662. * @param {Camera} camera - The camera the object should be rendered with.
  41663. * @param {LightsNode} lightsNode - The current lights node.
  41664. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41665. * @param {ClippingContext} clippingContext - The clipping context.
  41666. * @param {string} [passId] - An optional ID for identifying the pass.
  41667. */
  41668. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  41669. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  41670. renderObject.drawRange = object.geometry.drawRange;
  41671. renderObject.group = group;
  41672. //
  41673. const needsRefresh = this._nodes.needsRefresh( renderObject );
  41674. if ( needsRefresh ) {
  41675. this._nodes.updateBefore( renderObject );
  41676. this._geometries.updateForRender( renderObject );
  41677. this._nodes.updateForRender( renderObject );
  41678. this._bindings.updateForRender( renderObject );
  41679. }
  41680. this._pipelines.updateForRender( renderObject );
  41681. //
  41682. if ( this._currentRenderBundle !== null ) {
  41683. const renderBundleData = this.backend.get( this._currentRenderBundle );
  41684. renderBundleData.renderObjects.push( renderObject );
  41685. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  41686. }
  41687. this.backend.draw( renderObject, this.info );
  41688. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  41689. }
  41690. /**
  41691. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  41692. * Used in `compileAsync()`.
  41693. *
  41694. * @private
  41695. * @param {Object3D} object - The 3D object.
  41696. * @param {Material} material - The object's material.
  41697. * @param {Scene} scene - The scene the 3D object belongs to.
  41698. * @param {Camera} camera - The camera the object should be rendered with.
  41699. * @param {LightsNode} lightsNode - The current lights node.
  41700. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41701. * @param {ClippingContext} clippingContext - The clipping context.
  41702. * @param {string} [passId] - An optional ID for identifying the pass.
  41703. */
  41704. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  41705. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  41706. renderObject.drawRange = object.geometry.drawRange;
  41707. renderObject.group = group;
  41708. //
  41709. this._nodes.updateBefore( renderObject );
  41710. this._geometries.updateForRender( renderObject );
  41711. this._nodes.updateForRender( renderObject );
  41712. this._bindings.updateForRender( renderObject );
  41713. this._pipelines.getForRender( renderObject, this._compilationPromises );
  41714. this._nodes.updateAfter( renderObject );
  41715. }
  41716. /**
  41717. * Callback when the canvas has been resized.
  41718. *
  41719. * @private
  41720. */
  41721. _onCanvasTargetResize() {
  41722. if ( this._initialized ) this.backend.updateSize();
  41723. }
  41724. /**
  41725. * Alias for `compileAsync()`.
  41726. *
  41727. * @method
  41728. * @param {Object3D} scene - The scene or 3D object to precompile.
  41729. * @param {Camera} camera - The camera that is used to render the scene.
  41730. * @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.
  41731. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  41732. */
  41733. get compile() {
  41734. return this.compileAsync;
  41735. }
  41736. }
  41737. /**
  41738. * A binding represents the connection between a resource (like a texture, sampler
  41739. * or uniform buffer) and the resource definition in a shader stage.
  41740. *
  41741. * This module is an abstract base class for all concrete bindings types.
  41742. *
  41743. * @abstract
  41744. * @private
  41745. */
  41746. class Binding {
  41747. /**
  41748. * Constructs a new binding.
  41749. *
  41750. * @param {string} [name=''] - The binding's name.
  41751. */
  41752. constructor( name = '' ) {
  41753. /**
  41754. * The binding's name.
  41755. *
  41756. * @type {string}
  41757. */
  41758. this.name = name;
  41759. /**
  41760. * A bitmask that defines in what shader stages the
  41761. * binding's resource is accessible.
  41762. *
  41763. * @type {number}
  41764. */
  41765. this.visibility = 0;
  41766. }
  41767. /**
  41768. * Makes sure binding's resource is visible for the given shader stage.
  41769. *
  41770. * @param {number} visibility - The shader stage.
  41771. */
  41772. setVisibility( visibility ) {
  41773. this.visibility |= visibility;
  41774. }
  41775. /**
  41776. * Clones the binding.
  41777. *
  41778. * @return {Binding} The cloned binding.
  41779. */
  41780. clone() {
  41781. return Object.assign( new this.constructor(), this );
  41782. }
  41783. }
  41784. /**
  41785. * This function is usually called with the length in bytes of an array buffer.
  41786. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  41787. *
  41788. * @function
  41789. * @param {number} floatLength - The buffer length.
  41790. * @return {number} The padded length.
  41791. */
  41792. function getFloatLength( floatLength ) {
  41793. // ensure chunk size alignment (STD140 layout)
  41794. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  41795. }
  41796. /**
  41797. * Represents a buffer binding type.
  41798. *
  41799. * @private
  41800. * @abstract
  41801. * @augments Binding
  41802. */
  41803. class Buffer extends Binding {
  41804. /**
  41805. * Constructs a new buffer.
  41806. *
  41807. * @param {string} name - The buffer's name.
  41808. * @param {TypedArray} [buffer=null] - The buffer.
  41809. */
  41810. constructor( name, buffer = null ) {
  41811. super( name );
  41812. /**
  41813. * This flag can be used for type testing.
  41814. *
  41815. * @type {boolean}
  41816. * @readonly
  41817. * @default true
  41818. */
  41819. this.isBuffer = true;
  41820. /**
  41821. * The bytes per element.
  41822. *
  41823. * @type {number}
  41824. */
  41825. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  41826. /**
  41827. * A reference to the internal buffer.
  41828. *
  41829. * @private
  41830. * @type {TypedArray}
  41831. */
  41832. this._buffer = buffer;
  41833. }
  41834. /**
  41835. * The buffer's byte length.
  41836. *
  41837. * @type {number}
  41838. * @readonly
  41839. */
  41840. get byteLength() {
  41841. return getFloatLength( this._buffer.byteLength );
  41842. }
  41843. /**
  41844. * A reference to the internal buffer.
  41845. *
  41846. * @type {Float32Array}
  41847. * @readonly
  41848. */
  41849. get buffer() {
  41850. return this._buffer;
  41851. }
  41852. /**
  41853. * Updates the binding.
  41854. *
  41855. * @return {boolean} Whether the buffer has been updated and must be
  41856. * uploaded to the GPU.
  41857. */
  41858. update() {
  41859. return true;
  41860. }
  41861. }
  41862. /**
  41863. * Represents a uniform buffer binding type.
  41864. *
  41865. * @private
  41866. * @augments Buffer
  41867. */
  41868. class UniformBuffer extends Buffer {
  41869. /**
  41870. * Constructs a new uniform buffer.
  41871. *
  41872. * @param {string} name - The buffer's name.
  41873. * @param {TypedArray} [buffer=null] - The buffer.
  41874. */
  41875. constructor( name, buffer = null ) {
  41876. super( name, buffer );
  41877. /**
  41878. * This flag can be used for type testing.
  41879. *
  41880. * @type {boolean}
  41881. * @readonly
  41882. * @default true
  41883. */
  41884. this.isUniformBuffer = true;
  41885. }
  41886. }
  41887. let _id$4 = 0;
  41888. /**
  41889. * A special form of uniform buffer binding type.
  41890. * It's buffer value is managed by a node object.
  41891. *
  41892. * @private
  41893. * @augments UniformBuffer
  41894. */
  41895. class NodeUniformBuffer extends UniformBuffer {
  41896. /**
  41897. * Constructs a new node-based uniform buffer.
  41898. *
  41899. * @param {BufferNode} nodeUniform - The uniform buffer node.
  41900. * @param {UniformGroupNode} groupNode - The uniform group node.
  41901. */
  41902. constructor( nodeUniform, groupNode ) {
  41903. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  41904. /**
  41905. * The uniform buffer node.
  41906. *
  41907. * @type {BufferNode}
  41908. */
  41909. this.nodeUniform = nodeUniform;
  41910. /**
  41911. * The uniform group node.
  41912. *
  41913. * @type {UniformGroupNode}
  41914. */
  41915. this.groupNode = groupNode;
  41916. }
  41917. /**
  41918. * The uniform buffer.
  41919. *
  41920. * @type {Float32Array}
  41921. */
  41922. get buffer() {
  41923. return this.nodeUniform.value;
  41924. }
  41925. }
  41926. /**
  41927. * This class represents a uniform buffer binding but with
  41928. * an API that allows to maintain individual uniform objects.
  41929. *
  41930. * @private
  41931. * @augments UniformBuffer
  41932. */
  41933. class UniformsGroup extends UniformBuffer {
  41934. /**
  41935. * Constructs a new uniforms group.
  41936. *
  41937. * @param {string} name - The group's name.
  41938. */
  41939. constructor( name ) {
  41940. super( name );
  41941. /**
  41942. * This flag can be used for type testing.
  41943. *
  41944. * @type {boolean}
  41945. * @readonly
  41946. * @default true
  41947. */
  41948. this.isUniformsGroup = true;
  41949. /**
  41950. * An array with the raw uniform values.
  41951. *
  41952. * @private
  41953. * @type {?Array<number>}
  41954. * @default null
  41955. */
  41956. this._values = null;
  41957. /**
  41958. * An array of uniform objects.
  41959. *
  41960. * The order of uniforms in this array must match the order of uniforms in the shader.
  41961. *
  41962. * @type {Array<Uniform>}
  41963. */
  41964. this.uniforms = [];
  41965. }
  41966. /**
  41967. * Adds a uniform to this group.
  41968. *
  41969. * @param {Uniform} uniform - The uniform to add.
  41970. * @return {UniformsGroup} A reference to this group.
  41971. */
  41972. addUniform( uniform ) {
  41973. this.uniforms.push( uniform );
  41974. return this;
  41975. }
  41976. /**
  41977. * Removes a uniform from this group.
  41978. *
  41979. * @param {Uniform} uniform - The uniform to remove.
  41980. * @return {UniformsGroup} A reference to this group.
  41981. */
  41982. removeUniform( uniform ) {
  41983. const index = this.uniforms.indexOf( uniform );
  41984. if ( index !== -1 ) {
  41985. this.uniforms.splice( index, 1 );
  41986. }
  41987. return this;
  41988. }
  41989. /**
  41990. * An array with the raw uniform values.
  41991. *
  41992. * @type {Array<number>}
  41993. */
  41994. get values() {
  41995. if ( this._values === null ) {
  41996. this._values = Array.from( this.buffer );
  41997. }
  41998. return this._values;
  41999. }
  42000. /**
  42001. * A Float32 array buffer with the uniform values.
  42002. *
  42003. * @type {Float32Array}
  42004. */
  42005. get buffer() {
  42006. let buffer = this._buffer;
  42007. if ( buffer === null ) {
  42008. const byteLength = this.byteLength;
  42009. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  42010. this._buffer = buffer;
  42011. }
  42012. return buffer;
  42013. }
  42014. /**
  42015. * The byte length of the buffer with correct buffer alignment.
  42016. *
  42017. * @type {number}
  42018. */
  42019. get byteLength() {
  42020. const bytesPerElement = this.bytesPerElement;
  42021. let offset = 0; // global buffer offset in bytes
  42022. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  42023. const uniform = this.uniforms[ i ];
  42024. const boundary = uniform.boundary;
  42025. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  42026. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  42027. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  42028. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  42029. offset += chunkPadding;
  42030. // Check for chunk overflow
  42031. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  42032. // Add padding to the end of the chunk
  42033. offset += ( GPU_CHUNK_BYTES - chunkStart );
  42034. }
  42035. uniform.offset = offset / bytesPerElement;
  42036. offset += itemSize;
  42037. }
  42038. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  42039. }
  42040. /**
  42041. * Updates this group by updating each uniform object of
  42042. * the internal uniform list. The uniform objects check if their
  42043. * values has actually changed so this method only returns
  42044. * `true` if there is a real value change.
  42045. *
  42046. * @return {boolean} Whether the uniforms have been updated and
  42047. * must be uploaded to the GPU.
  42048. */
  42049. update() {
  42050. let updated = false;
  42051. for ( const uniform of this.uniforms ) {
  42052. if ( this.updateByType( uniform ) === true ) {
  42053. updated = true;
  42054. }
  42055. }
  42056. return updated;
  42057. }
  42058. /**
  42059. * Updates a given uniform by calling an update method matching
  42060. * the uniforms type.
  42061. *
  42062. * @param {Uniform} uniform - The uniform to update.
  42063. * @return {boolean} Whether the uniform has been updated or not.
  42064. */
  42065. updateByType( uniform ) {
  42066. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  42067. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  42068. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  42069. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  42070. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  42071. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  42072. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  42073. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  42074. }
  42075. /**
  42076. * Updates a given Number uniform.
  42077. *
  42078. * @param {NumberUniform} uniform - The Number uniform.
  42079. * @return {boolean} Whether the uniform has been updated or not.
  42080. */
  42081. updateNumber( uniform ) {
  42082. let updated = false;
  42083. const a = this.values;
  42084. const v = uniform.getValue();
  42085. const offset = uniform.offset;
  42086. const type = uniform.getType();
  42087. if ( a[ offset ] !== v ) {
  42088. const b = this._getBufferForType( type );
  42089. b[ offset ] = a[ offset ] = v;
  42090. updated = true;
  42091. }
  42092. return updated;
  42093. }
  42094. /**
  42095. * Updates a given Vector2 uniform.
  42096. *
  42097. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  42098. * @return {boolean} Whether the uniform has been updated or not.
  42099. */
  42100. updateVector2( uniform ) {
  42101. let updated = false;
  42102. const a = this.values;
  42103. const v = uniform.getValue();
  42104. const offset = uniform.offset;
  42105. const type = uniform.getType();
  42106. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  42107. const b = this._getBufferForType( type );
  42108. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42109. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42110. updated = true;
  42111. }
  42112. return updated;
  42113. }
  42114. /**
  42115. * Updates a given Vector3 uniform.
  42116. *
  42117. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  42118. * @return {boolean} Whether the uniform has been updated or not.
  42119. */
  42120. updateVector3( uniform ) {
  42121. let updated = false;
  42122. const a = this.values;
  42123. const v = uniform.getValue();
  42124. const offset = uniform.offset;
  42125. const type = uniform.getType();
  42126. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  42127. const b = this._getBufferForType( type );
  42128. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42129. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42130. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  42131. updated = true;
  42132. }
  42133. return updated;
  42134. }
  42135. /**
  42136. * Updates a given Vector4 uniform.
  42137. *
  42138. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  42139. * @return {boolean} Whether the uniform has been updated or not.
  42140. */
  42141. updateVector4( uniform ) {
  42142. let updated = false;
  42143. const a = this.values;
  42144. const v = uniform.getValue();
  42145. const offset = uniform.offset;
  42146. const type = uniform.getType();
  42147. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  42148. const b = this._getBufferForType( type );
  42149. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42150. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42151. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  42152. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  42153. updated = true;
  42154. }
  42155. return updated;
  42156. }
  42157. /**
  42158. * Updates a given Color uniform.
  42159. *
  42160. * @param {ColorUniform} uniform - The Color uniform.
  42161. * @return {boolean} Whether the uniform has been updated or not.
  42162. */
  42163. updateColor( uniform ) {
  42164. let updated = false;
  42165. const a = this.values;
  42166. const c = uniform.getValue();
  42167. const offset = uniform.offset;
  42168. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  42169. const b = this.buffer;
  42170. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  42171. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  42172. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  42173. updated = true;
  42174. }
  42175. return updated;
  42176. }
  42177. /**
  42178. * Updates a given Matrix3 uniform.
  42179. *
  42180. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  42181. * @return {boolean} Whether the uniform has been updated or not.
  42182. */
  42183. updateMatrix3( uniform ) {
  42184. let updated = false;
  42185. const a = this.values;
  42186. const e = uniform.getValue().elements;
  42187. const offset = uniform.offset;
  42188. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  42189. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  42190. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  42191. const b = this.buffer;
  42192. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  42193. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  42194. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  42195. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  42196. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  42197. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  42198. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  42199. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  42200. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  42201. updated = true;
  42202. }
  42203. return updated;
  42204. }
  42205. /**
  42206. * Updates a given Matrix4 uniform.
  42207. *
  42208. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  42209. * @return {boolean} Whether the uniform has been updated or not.
  42210. */
  42211. updateMatrix4( uniform ) {
  42212. let updated = false;
  42213. const a = this.values;
  42214. const e = uniform.getValue().elements;
  42215. const offset = uniform.offset;
  42216. if ( arraysEqual( a, e, offset ) === false ) {
  42217. const b = this.buffer;
  42218. b.set( e, offset );
  42219. setArray( a, e, offset );
  42220. updated = true;
  42221. }
  42222. return updated;
  42223. }
  42224. /**
  42225. * Returns a typed array that matches the given data type.
  42226. *
  42227. * @param {string} type - The data type.
  42228. * @return {TypedArray} The typed array.
  42229. */
  42230. _getBufferForType( type ) {
  42231. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  42232. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  42233. return this.buffer;
  42234. }
  42235. }
  42236. /**
  42237. * Sets the values of the second array to the first array.
  42238. *
  42239. * @private
  42240. * @param {TypedArray} a - The first array.
  42241. * @param {TypedArray} b - The second array.
  42242. * @param {number} offset - An index offset for the first array.
  42243. */
  42244. function setArray( a, b, offset ) {
  42245. for ( let i = 0, l = b.length; i < l; i ++ ) {
  42246. a[ offset + i ] = b[ i ];
  42247. }
  42248. }
  42249. /**
  42250. * Returns `true` if the given arrays are equal.
  42251. *
  42252. * @private
  42253. * @param {TypedArray} a - The first array.
  42254. * @param {TypedArray} b - The second array.
  42255. * @param {number} offset - An index offset for the first array.
  42256. * @return {boolean} Whether the given arrays are equal or not.
  42257. */
  42258. function arraysEqual( a, b, offset ) {
  42259. for ( let i = 0, l = b.length; i < l; i ++ ) {
  42260. if ( a[ offset + i ] !== b[ i ] ) return false;
  42261. }
  42262. return true;
  42263. }
  42264. let _id$3 = 0;
  42265. /**
  42266. * A special form of uniforms group that represents
  42267. * the individual uniforms as node-based uniforms.
  42268. *
  42269. * @private
  42270. * @augments UniformsGroup
  42271. */
  42272. class NodeUniformsGroup extends UniformsGroup {
  42273. /**
  42274. * Constructs a new node-based uniforms group.
  42275. *
  42276. * @param {string} name - The group's name.
  42277. * @param {UniformGroupNode} groupNode - The uniform group node.
  42278. */
  42279. constructor( name, groupNode ) {
  42280. super( name );
  42281. /**
  42282. * The group's ID.
  42283. *
  42284. * @type {number}
  42285. */
  42286. this.id = _id$3 ++;
  42287. /**
  42288. * The uniform group node.
  42289. *
  42290. * @type {UniformGroupNode}
  42291. */
  42292. this.groupNode = groupNode;
  42293. /**
  42294. * This flag can be used for type testing.
  42295. *
  42296. * @type {boolean}
  42297. * @readonly
  42298. * @default true
  42299. */
  42300. this.isNodeUniformsGroup = true;
  42301. }
  42302. }
  42303. /**
  42304. * Represents a sampler binding type.
  42305. *
  42306. * @private
  42307. * @augments Binding
  42308. */
  42309. class Sampler extends Binding {
  42310. /**
  42311. * Constructs a new sampler.
  42312. *
  42313. * @param {string} name - The samplers's name.
  42314. * @param {?Texture} texture - The texture this binding is referring to.
  42315. */
  42316. constructor( name, texture ) {
  42317. super( name );
  42318. /**
  42319. * The texture the sampler is referring to.
  42320. *
  42321. * @private
  42322. * @type {?Texture}
  42323. */
  42324. this._texture = null;
  42325. /**
  42326. * An event listener which is added to {@link texture}'s dispose event.
  42327. *
  42328. * @private
  42329. * @type {Function}
  42330. */
  42331. this._onTextureDispose = () => {
  42332. this.generation = null;
  42333. this.version = 0;
  42334. };
  42335. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  42336. this.texture = texture;
  42337. /**
  42338. * The binding's version.
  42339. *
  42340. * @type {number}
  42341. */
  42342. this.version = texture ? texture.version : 0;
  42343. /**
  42344. * The binding's generation which is an additional version
  42345. * qualifier.
  42346. *
  42347. * @type {?number}
  42348. * @default null
  42349. */
  42350. this.generation = null;
  42351. /**
  42352. * The binding's sampler key.
  42353. *
  42354. * @type {string}
  42355. * @default ''
  42356. */
  42357. this.samplerKey = '';
  42358. /**
  42359. * This flag can be used for type testing.
  42360. *
  42361. * @type {boolean}
  42362. * @readonly
  42363. * @default true
  42364. */
  42365. this.isSampler = true;
  42366. }
  42367. /**
  42368. * Sets the texture of this sampler.
  42369. *
  42370. * @param {Texture} value - The texture to set.
  42371. */
  42372. set texture( value ) {
  42373. if ( this._texture === value ) return;
  42374. if ( this._texture ) {
  42375. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  42376. }
  42377. this._texture = value;
  42378. this.generation = null;
  42379. this.version = 0;
  42380. if ( this._texture ) {
  42381. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  42382. }
  42383. }
  42384. /**
  42385. * Gets the texture of this sampler.
  42386. * @return {?Texture} The texture.
  42387. */
  42388. get texture() {
  42389. return this._texture;
  42390. }
  42391. /**
  42392. * Updates the binding.
  42393. *
  42394. * @return {boolean} Whether the texture has been updated and must be
  42395. * uploaded to the GPU.
  42396. */
  42397. update() {
  42398. const { texture, version } = this;
  42399. if ( version !== texture.version ) {
  42400. this.version = texture.version;
  42401. return true;
  42402. }
  42403. return false;
  42404. }
  42405. clone() {
  42406. const clonedSampler = super.clone();
  42407. // fix dispose handler for cloned instances
  42408. // TODO: Find better solution, see #31747
  42409. clonedSampler._texture = null;
  42410. clonedSampler._onTextureDispose = () => {
  42411. clonedSampler.generation = null;
  42412. clonedSampler.version = 0;
  42413. };
  42414. clonedSampler.texture = this.texture;
  42415. return clonedSampler;
  42416. }
  42417. }
  42418. let _id$2 = 0;
  42419. /**
  42420. * Represents a sampled texture binding type.
  42421. *
  42422. * @private
  42423. * @augments Sampler
  42424. */
  42425. class SampledTexture extends Sampler {
  42426. /**
  42427. * Constructs a new sampled texture.
  42428. *
  42429. * @param {string} name - The sampled texture's name.
  42430. * @param {?Texture} texture - The texture this binding is referring to.
  42431. */
  42432. constructor( name, texture ) {
  42433. super( name, texture );
  42434. /**
  42435. * This identifier.
  42436. *
  42437. * @type {number}
  42438. */
  42439. this.id = _id$2 ++;
  42440. /**
  42441. * Whether the texture is a storage texture or not.
  42442. *
  42443. * @type {boolean}
  42444. * @default false
  42445. */
  42446. this.store = false;
  42447. /**
  42448. * The mip level to bind for storage textures.
  42449. *
  42450. * @type {number}
  42451. * @default 0
  42452. */
  42453. this.mipLevel = 0;
  42454. /**
  42455. * This flag can be used for type testing.
  42456. *
  42457. * @type {boolean}
  42458. * @readonly
  42459. * @default true
  42460. */
  42461. this.isSampledTexture = true;
  42462. }
  42463. }
  42464. /**
  42465. * A special form of sampled texture binding type.
  42466. * It's texture value is managed by a node object.
  42467. *
  42468. * @private
  42469. * @augments SampledTexture
  42470. */
  42471. class NodeSampledTexture extends SampledTexture {
  42472. /**
  42473. * Constructs a new node-based sampled texture.
  42474. *
  42475. * @param {string} name - The textures's name.
  42476. * @param {TextureNode} textureNode - The texture node.
  42477. * @param {UniformGroupNode} groupNode - The uniform group node.
  42478. * @param {?string} [access=null] - The access type.
  42479. */
  42480. constructor( name, textureNode, groupNode, access = null ) {
  42481. super( name, textureNode ? textureNode.value : null );
  42482. /**
  42483. * The texture node.
  42484. *
  42485. * @type {TextureNode}
  42486. */
  42487. this.textureNode = textureNode;
  42488. /**
  42489. * The uniform group node.
  42490. *
  42491. * @type {UniformGroupNode}
  42492. */
  42493. this.groupNode = groupNode;
  42494. /**
  42495. * The access type.
  42496. *
  42497. * @type {?string}
  42498. * @default null
  42499. */
  42500. this.access = access;
  42501. }
  42502. /**
  42503. * Updates the binding.
  42504. *
  42505. * @return {boolean} Whether the texture has been updated and must be
  42506. * uploaded to the GPU.
  42507. */
  42508. update() {
  42509. const { textureNode } = this;
  42510. if ( this.texture !== textureNode.value ) {
  42511. this.texture = textureNode.value;
  42512. return true;
  42513. }
  42514. return super.update();
  42515. }
  42516. }
  42517. /**
  42518. * A special form of sampled cube texture binding type.
  42519. * It's texture value is managed by a node object.
  42520. *
  42521. * @private
  42522. * @augments NodeSampledTexture
  42523. */
  42524. class NodeSampledCubeTexture extends NodeSampledTexture {
  42525. /**
  42526. * Constructs a new node-based sampled cube texture.
  42527. *
  42528. * @param {string} name - The textures's name.
  42529. * @param {TextureNode} textureNode - The texture node.
  42530. * @param {UniformGroupNode} groupNode - The uniform group node.
  42531. * @param {?string} [access=null] - The access type.
  42532. */
  42533. constructor( name, textureNode, groupNode, access = null ) {
  42534. super( name, textureNode, groupNode, access );
  42535. /**
  42536. * This flag can be used for type testing.
  42537. *
  42538. * @type {boolean}
  42539. * @readonly
  42540. * @default true
  42541. */
  42542. this.isSampledCubeTexture = true;
  42543. }
  42544. }
  42545. /**
  42546. * A special form of sampled 3D texture binding type.
  42547. * It's texture value is managed by a node object.
  42548. *
  42549. * @private
  42550. * @augments NodeSampledTexture
  42551. */
  42552. class NodeSampledTexture3D extends NodeSampledTexture {
  42553. /**
  42554. * Constructs a new node-based sampled 3D texture.
  42555. *
  42556. * @param {string} name - The textures's name.
  42557. * @param {TextureNode} textureNode - The texture node.
  42558. * @param {UniformGroupNode} groupNode - The uniform group node.
  42559. * @param {?string} [access=null] - The access type.
  42560. */
  42561. constructor( name, textureNode, groupNode, access = null ) {
  42562. super( name, textureNode, groupNode, access );
  42563. /**
  42564. * This flag can be used for type testing.
  42565. *
  42566. * @type {boolean}
  42567. * @readonly
  42568. * @default true
  42569. */
  42570. this.isSampledTexture3D = true;
  42571. }
  42572. }
  42573. const glslPolyfills = {
  42574. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( int x ) { return floatBitsToInt( uintBitsToFloat( x ) ); }' ),
  42575. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' )
  42576. };
  42577. const glslMethods = {
  42578. textureDimensions: 'textureSize',
  42579. equals: 'equal',
  42580. bitcast_float_int: 'floatBitsToInt',
  42581. bitcast_int_float: 'intBitsToFloat',
  42582. bitcast_uint_float: 'uintBitsToFloat',
  42583. bitcast_float_uint: 'floatBitsToUint',
  42584. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  42585. bitcast_int_uint: 'tsl_bitcast_int_to_uint'
  42586. };
  42587. const precisionLib = {
  42588. low: 'lowp',
  42589. medium: 'mediump',
  42590. high: 'highp'
  42591. };
  42592. const supports$1 = {
  42593. swizzleAssign: true,
  42594. storageBuffer: false
  42595. };
  42596. const interpolationTypeMap = {
  42597. perspective: 'smooth',
  42598. linear: 'noperspective'
  42599. };
  42600. const interpolationModeMap = {
  42601. 'centroid': 'centroid'
  42602. };
  42603. const defaultPrecisions = `
  42604. precision highp float;
  42605. precision highp int;
  42606. precision highp sampler2D;
  42607. precision highp sampler3D;
  42608. precision highp samplerCube;
  42609. precision highp sampler2DArray;
  42610. precision highp usampler2D;
  42611. precision highp usampler3D;
  42612. precision highp usamplerCube;
  42613. precision highp usampler2DArray;
  42614. precision highp isampler2D;
  42615. precision highp isampler3D;
  42616. precision highp isamplerCube;
  42617. precision highp isampler2DArray;
  42618. precision lowp sampler2DShadow;
  42619. precision lowp sampler2DArrayShadow;
  42620. precision lowp samplerCubeShadow;
  42621. `;
  42622. /**
  42623. * A node builder targeting GLSL.
  42624. *
  42625. * This module generates GLSL shader code from node materials and also
  42626. * generates the respective bindings and vertex buffer definitions. These
  42627. * data are later used by the renderer to create render and compute pipelines
  42628. * for render objects.
  42629. *
  42630. * @augments NodeBuilder
  42631. */
  42632. class GLSLNodeBuilder extends NodeBuilder {
  42633. /**
  42634. * Constructs a new GLSL node builder renderer.
  42635. *
  42636. * @param {Object3D} object - The 3D object.
  42637. * @param {Renderer} renderer - The renderer.
  42638. */
  42639. constructor( object, renderer ) {
  42640. super( object, renderer, new GLSLNodeParser() );
  42641. /**
  42642. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  42643. * another dictionary which manages UBOs per group ('render','frame','object').
  42644. *
  42645. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  42646. */
  42647. this.uniformGroups = {};
  42648. /**
  42649. * An array that holds objects defining the varying and attribute data in
  42650. * context of Transform Feedback.
  42651. *
  42652. * @type {Array<Object<string,AttributeNode|string>>}
  42653. */
  42654. this.transforms = [];
  42655. /**
  42656. * A dictionary that holds for each shader stage a Map of used extensions.
  42657. *
  42658. * @type {Object<string,Map<string,Object>>}
  42659. */
  42660. this.extensions = {};
  42661. /**
  42662. * A dictionary that holds for each shader stage an Array of used builtins.
  42663. *
  42664. * @type {Object<string,Array<string>>}
  42665. */
  42666. this.builtins = { vertex: [], fragment: [], compute: [] };
  42667. }
  42668. /**
  42669. * Checks if the given texture requires a manual conversion to the working color space.
  42670. *
  42671. * @param {Texture} texture - The texture to check.
  42672. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  42673. */
  42674. needsToWorkingColorSpace( texture ) {
  42675. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  42676. }
  42677. /**
  42678. * Includes the given method name into the current
  42679. * function node.
  42680. *
  42681. * @private
  42682. * @param {string} name - The method name to include.
  42683. * @return {CodeNode} The respective code node.
  42684. */
  42685. _include( name ) {
  42686. const codeNode = glslPolyfills[ name ];
  42687. codeNode.build( this );
  42688. this.addInclude( codeNode );
  42689. return codeNode;
  42690. }
  42691. /**
  42692. * Returns the native shader method name for a given generic name.
  42693. *
  42694. * @param {string} method - The method name to resolve.
  42695. * @return {string} The resolved GLSL method name.
  42696. */
  42697. getMethod( method ) {
  42698. if ( glslPolyfills[ method ] !== undefined ) {
  42699. this._include( method );
  42700. }
  42701. return glslMethods[ method ] || method;
  42702. }
  42703. /**
  42704. * Returns the bitcast method name for a given input and outputType.
  42705. *
  42706. * @param {string} type - The output type to bitcast to.
  42707. * @param {string} inputType - The input type of the.
  42708. * @return {string} The resolved WGSL bitcast invocation.
  42709. */
  42710. getBitcastMethod( type, inputType ) {
  42711. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  42712. }
  42713. /**
  42714. * Returns the native snippet for a ternary operation.
  42715. *
  42716. * @param {string} condSnippet - The condition determining which expression gets resolved.
  42717. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  42718. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  42719. * @return {string} The resolved method name.
  42720. */
  42721. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  42722. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  42723. }
  42724. /**
  42725. * Returns the output struct name. Not relevant for GLSL.
  42726. *
  42727. * @return {string}
  42728. */
  42729. getOutputStructName() {
  42730. return '';
  42731. }
  42732. /**
  42733. * Builds the given shader node.
  42734. *
  42735. * @param {ShaderNodeInternal} shaderNode - The shader node.
  42736. * @return {string} The GLSL function code.
  42737. */
  42738. buildFunctionCode( shaderNode ) {
  42739. const layout = shaderNode.layout;
  42740. const flowData = this.flowShaderNode( shaderNode );
  42741. const parameters = [];
  42742. for ( const input of layout.inputs ) {
  42743. parameters.push( this.getType( input.type ) + ' ' + input.name );
  42744. }
  42745. //
  42746. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  42747. ${ flowData.vars }
  42748. ${ flowData.code }
  42749. return ${ flowData.result };
  42750. }`;
  42751. //
  42752. return code;
  42753. }
  42754. /**
  42755. * Setups the Pixel Buffer Object (PBO) for the given storage
  42756. * buffer node.
  42757. *
  42758. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  42759. */
  42760. setupPBO( storageBufferNode ) {
  42761. const attribute = storageBufferNode.value;
  42762. if ( attribute.pbo === undefined ) {
  42763. const originalArray = attribute.array;
  42764. const numElements = attribute.count * attribute.itemSize;
  42765. const { itemSize } = attribute;
  42766. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  42767. let format = isInteger ? RedIntegerFormat : RedFormat;
  42768. if ( itemSize === 2 ) {
  42769. format = isInteger ? RGIntegerFormat : RGFormat;
  42770. } else if ( itemSize === 3 ) {
  42771. format = isInteger ? RGBIntegerFormat : RGBFormat;
  42772. } else if ( itemSize === 4 ) {
  42773. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  42774. }
  42775. const typeMap = {
  42776. Float32Array: FloatType,
  42777. Uint8Array: UnsignedByteType,
  42778. Uint16Array: UnsignedShortType,
  42779. Uint32Array: UnsignedIntType,
  42780. Int8Array: ByteType,
  42781. Int16Array: ShortType,
  42782. Int32Array: IntType,
  42783. Uint8ClampedArray: UnsignedByteType,
  42784. };
  42785. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  42786. let height = Math.ceil( ( numElements / itemSize ) / width );
  42787. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  42788. const newSize = width * height * itemSize;
  42789. const newArray = new originalArray.constructor( newSize );
  42790. newArray.set( originalArray, 0 );
  42791. attribute.array = newArray;
  42792. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  42793. pboTexture.needsUpdate = true;
  42794. pboTexture.isPBOTexture = true;
  42795. const pbo = new TextureNode( pboTexture, null, null );
  42796. pbo.setPrecision( 'high' );
  42797. attribute.pboNode = pbo;
  42798. attribute.pbo = pbo.value;
  42799. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  42800. }
  42801. }
  42802. /**
  42803. * Returns a GLSL snippet that represents the property name of the given node.
  42804. *
  42805. * @param {Node} node - The node.
  42806. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42807. * @return {string} The property name.
  42808. */
  42809. getPropertyName( node, shaderStage = this.shaderStage ) {
  42810. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  42811. return shaderStage.charAt( 0 ) + '_' + node.name;
  42812. }
  42813. return super.getPropertyName( node, shaderStage );
  42814. }
  42815. /**
  42816. * Setups the Pixel Buffer Object (PBO) for the given storage
  42817. * buffer node.
  42818. *
  42819. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  42820. * @return {string} The property name.
  42821. */
  42822. generatePBO( storageArrayElementNode ) {
  42823. const { node, indexNode } = storageArrayElementNode;
  42824. const attribute = node.value;
  42825. if ( this.renderer.backend.has( attribute ) ) {
  42826. const attributeData = this.renderer.backend.get( attribute );
  42827. attributeData.pbo = attribute.pbo;
  42828. }
  42829. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  42830. const textureName = this.getPropertyName( nodeUniform );
  42831. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  42832. const indexSnippet = indexNode.build( this, 'uint' );
  42833. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  42834. let propertyName = elementNodeData.propertyName;
  42835. if ( propertyName === undefined ) {
  42836. // property element
  42837. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  42838. propertyName = this.getPropertyName( nodeVar );
  42839. // property size
  42840. const bufferNodeData = this.getDataFromNode( node );
  42841. let propertySizeName = bufferNodeData.propertySizeName;
  42842. if ( propertySizeName === undefined ) {
  42843. propertySizeName = propertyName + 'Size';
  42844. this.getVarFromNode( node, propertySizeName, 'uint' );
  42845. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  42846. bufferNodeData.propertySizeName = propertySizeName;
  42847. }
  42848. //
  42849. const { itemSize } = attribute;
  42850. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  42851. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  42852. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  42853. //
  42854. let prefix = 'vec4';
  42855. if ( attribute.pbo.type === UnsignedIntType ) {
  42856. prefix = 'uvec4';
  42857. } else if ( attribute.pbo.type === IntType ) {
  42858. prefix = 'ivec4';
  42859. }
  42860. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  42861. elementNodeData.propertyName = propertyName;
  42862. }
  42863. return propertyName;
  42864. }
  42865. /**
  42866. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  42867. *
  42868. * @param {?Texture} texture - The texture.
  42869. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42870. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42871. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42872. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  42873. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42874. * @return {string} The GLSL snippet.
  42875. */
  42876. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  42877. if ( levelSnippet === null ) levelSnippet = '0';
  42878. let snippet;
  42879. if ( depthSnippet ) {
  42880. if ( offsetSnippet ) {
  42881. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  42882. } else {
  42883. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  42884. }
  42885. } else {
  42886. if ( offsetSnippet ) {
  42887. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  42888. } else {
  42889. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  42890. }
  42891. }
  42892. if ( texture !== null && texture.isDepthTexture ) {
  42893. snippet += '.x';
  42894. }
  42895. return snippet;
  42896. }
  42897. /**
  42898. * Generates the GLSL snippet for sampling/loading the given texture.
  42899. *
  42900. * @param {Texture} texture - The texture.
  42901. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42902. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42903. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  42904. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42905. * @return {string} The GLSL snippet.
  42906. */
  42907. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  42908. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  42909. if ( texture.isDepthTexture ) {
  42910. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  42911. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  42912. }
  42913. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  42914. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  42915. }
  42916. /**
  42917. * Generates the GLSL snippet when sampling textures with explicit mip level.
  42918. *
  42919. * @param {Texture} texture - The texture.
  42920. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42921. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42922. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42923. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42924. * @return {string} The GLSL snippet.
  42925. */
  42926. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  42927. if ( offsetSnippet ) {
  42928. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  42929. }
  42930. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  42931. }
  42932. /**
  42933. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  42934. *
  42935. * @param {Texture} texture - The texture.
  42936. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42937. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42938. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  42939. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42940. * @return {string} The GLSL snippet.
  42941. */
  42942. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  42943. if ( offsetSnippet ) {
  42944. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  42945. }
  42946. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  42947. }
  42948. /**
  42949. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  42950. *
  42951. * @param {Texture} texture - The texture.
  42952. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42953. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42954. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  42955. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42956. * @return {string} The GLSL snippet.
  42957. */
  42958. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  42959. if ( offsetSnippet ) {
  42960. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  42961. }
  42962. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  42963. }
  42964. /**
  42965. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  42966. * against a reference value.
  42967. *
  42968. * @param {Texture} texture - The texture.
  42969. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42970. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42971. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  42972. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  42973. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42974. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42975. * @return {string} The GLSL snippet.
  42976. */
  42977. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  42978. if ( shaderStage === 'fragment' ) {
  42979. if ( depthSnippet ) {
  42980. if ( offsetSnippet ) {
  42981. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  42982. }
  42983. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  42984. }
  42985. if ( offsetSnippet ) {
  42986. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  42987. }
  42988. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  42989. } else {
  42990. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  42991. }
  42992. }
  42993. /**
  42994. * Returns the variables of the given shader stage as a GLSL string.
  42995. *
  42996. * @param {string} shaderStage - The shader stage.
  42997. * @return {string} The GLSL snippet that defines the variables.
  42998. */
  42999. getVars( shaderStage ) {
  43000. const snippets = [];
  43001. const vars = this.vars[ shaderStage ];
  43002. if ( vars !== undefined ) {
  43003. for ( const variable of vars ) {
  43004. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  43005. }
  43006. }
  43007. return snippets.join( '\n\t' );
  43008. }
  43009. /**
  43010. * Returns the uniforms of the given shader stage as a GLSL string.
  43011. *
  43012. * @param {string} shaderStage - The shader stage.
  43013. * @return {string} The GLSL snippet that defines the uniforms.
  43014. */
  43015. getUniforms( shaderStage ) {
  43016. const uniforms = this.uniforms[ shaderStage ];
  43017. const bindingSnippets = [];
  43018. const uniformGroups = {};
  43019. for ( const uniform of uniforms ) {
  43020. let snippet = null;
  43021. let group = false;
  43022. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  43023. const texture = uniform.node.value;
  43024. let typePrefix = '';
  43025. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  43026. if ( texture.type === UnsignedIntType ) {
  43027. typePrefix = 'u';
  43028. } else if ( texture.type === IntType ) {
  43029. typePrefix = 'i';
  43030. }
  43031. }
  43032. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  43033. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  43034. } else if ( texture.compareFunction ) {
  43035. if ( texture.isArrayTexture === true ) {
  43036. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  43037. } else {
  43038. snippet = `sampler2DShadow ${ uniform.name };`;
  43039. }
  43040. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43041. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  43042. } else {
  43043. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  43044. }
  43045. } else if ( uniform.type === 'cubeTexture' ) {
  43046. snippet = `samplerCube ${ uniform.name };`;
  43047. } else if ( uniform.type === 'buffer' ) {
  43048. const bufferNode = uniform.node;
  43049. const bufferType = this.getType( bufferNode.bufferType );
  43050. const bufferCount = bufferNode.bufferCount;
  43051. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  43052. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  43053. } else {
  43054. const vectorType = this.getVectorType( uniform.type );
  43055. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  43056. group = true;
  43057. }
  43058. const precision = uniform.node.precision;
  43059. if ( precision !== null ) {
  43060. snippet = precisionLib[ precision ] + ' ' + snippet;
  43061. }
  43062. if ( group ) {
  43063. snippet = '\t' + snippet;
  43064. const groupName = uniform.groupNode.name;
  43065. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  43066. groupSnippets.push( snippet );
  43067. } else {
  43068. snippet = 'uniform ' + snippet;
  43069. bindingSnippets.push( snippet );
  43070. }
  43071. }
  43072. let output = '';
  43073. for ( const name in uniformGroups ) {
  43074. const groupSnippets = uniformGroups[ name ];
  43075. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  43076. }
  43077. output += bindingSnippets.join( '\n' );
  43078. return output;
  43079. }
  43080. /**
  43081. * Returns the type for a given buffer attribute.
  43082. *
  43083. * @param {BufferAttribute} attribute - The buffer attribute.
  43084. * @return {string} The type.
  43085. */
  43086. getTypeFromAttribute( attribute ) {
  43087. let nodeType = super.getTypeFromAttribute( attribute );
  43088. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  43089. let dataAttribute = attribute;
  43090. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  43091. const array = dataAttribute.array;
  43092. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  43093. nodeType = nodeType.slice( 1 );
  43094. }
  43095. }
  43096. return nodeType;
  43097. }
  43098. /**
  43099. * Returns the shader attributes of the given shader stage as a GLSL string.
  43100. *
  43101. * @param {string} shaderStage - The shader stage.
  43102. * @return {string} The GLSL snippet that defines the shader attributes.
  43103. */
  43104. getAttributes( shaderStage ) {
  43105. let snippet = '';
  43106. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43107. const attributes = this.getAttributesArray();
  43108. let location = 0;
  43109. for ( const attribute of attributes ) {
  43110. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  43111. }
  43112. }
  43113. return snippet;
  43114. }
  43115. /**
  43116. * Returns the members of the given struct type node as a GLSL string.
  43117. *
  43118. * @param {StructTypeNode} struct - The struct type node.
  43119. * @return {string} The GLSL snippet that defines the struct members.
  43120. */
  43121. getStructMembers( struct ) {
  43122. const snippets = [];
  43123. for ( const member of struct.members ) {
  43124. snippets.push( `\t${ member.type } ${ member.name };` );
  43125. }
  43126. return snippets.join( '\n' );
  43127. }
  43128. /**
  43129. * Returns the structs of the given shader stage as a GLSL string.
  43130. *
  43131. * @param {string} shaderStage - The shader stage.
  43132. * @return {string} The GLSL snippet that defines the structs.
  43133. */
  43134. getStructs( shaderStage ) {
  43135. const snippets = [];
  43136. const structs = this.structs[ shaderStage ];
  43137. const outputSnippet = [];
  43138. for ( const struct of structs ) {
  43139. if ( struct.output ) {
  43140. for ( const member of struct.members ) {
  43141. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  43142. }
  43143. } else {
  43144. let snippet = 'struct ' + struct.name + ' {\n';
  43145. snippet += this.getStructMembers( struct );
  43146. snippet += '\n};\n';
  43147. snippets.push( snippet );
  43148. }
  43149. }
  43150. if ( outputSnippet.length === 0 ) {
  43151. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  43152. }
  43153. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  43154. }
  43155. /**
  43156. * Returns the varyings of the given shader stage as a GLSL string.
  43157. *
  43158. * @param {string} shaderStage - The shader stage.
  43159. * @return {string} The GLSL snippet that defines the varyings.
  43160. */
  43161. getVaryings( shaderStage ) {
  43162. let snippet = '';
  43163. const varyings = this.varyings;
  43164. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43165. for ( const varying of varyings ) {
  43166. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  43167. const type = this.getType( varying.type );
  43168. if ( varying.needsInterpolation ) {
  43169. if ( varying.interpolationType ) {
  43170. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  43171. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  43172. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  43173. } else {
  43174. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  43175. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  43176. }
  43177. } else {
  43178. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  43179. }
  43180. }
  43181. } else if ( shaderStage === 'fragment' ) {
  43182. for ( const varying of varyings ) {
  43183. if ( varying.needsInterpolation ) {
  43184. const type = this.getType( varying.type );
  43185. if ( varying.interpolationType ) {
  43186. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  43187. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  43188. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  43189. } else {
  43190. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  43191. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  43192. }
  43193. }
  43194. }
  43195. }
  43196. for ( const builtin of this.builtins[ shaderStage ] ) {
  43197. snippet += `${builtin};\n`;
  43198. }
  43199. return snippet;
  43200. }
  43201. /**
  43202. * Returns the vertex index builtin.
  43203. *
  43204. * @return {string} The vertex index.
  43205. */
  43206. getVertexIndex() {
  43207. return 'uint( gl_VertexID )';
  43208. }
  43209. /**
  43210. * Contextually returns either the vertex stage instance index builtin
  43211. * or the linearized index of an compute invocation within a grid of workgroups.
  43212. *
  43213. * @return {string} The instance index.
  43214. */
  43215. getInstanceIndex() {
  43216. return 'uint( gl_InstanceID )';
  43217. }
  43218. /**
  43219. * Returns a builtin representing the index of an invocation within its workgroup.
  43220. *
  43221. * @return {string} The invocation local index.
  43222. */
  43223. getInvocationLocalIndex() {
  43224. const workgroupSize = this.object.workgroupSize;
  43225. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  43226. return `uint( gl_InstanceID ) % ${size}u`;
  43227. }
  43228. /**
  43229. * Returns a builtin representing the size of a subgroup within the current shader.
  43230. */
  43231. getSubgroupSize() {
  43232. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  43233. }
  43234. /**
  43235. * Returns a builtin representing the index of an invocation within its subgroup.
  43236. */
  43237. getInvocationSubgroupIndex() {
  43238. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  43239. }
  43240. /**
  43241. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  43242. */
  43243. getSubgroupIndex() {
  43244. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  43245. }
  43246. /**
  43247. * Returns the draw index builtin.
  43248. *
  43249. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  43250. */
  43251. getDrawIndex() {
  43252. const extensions = this.renderer.backend.extensions;
  43253. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  43254. return 'uint( gl_DrawID )';
  43255. }
  43256. return null;
  43257. }
  43258. /**
  43259. * Returns the front facing builtin.
  43260. *
  43261. * @return {string} The front facing builtin.
  43262. */
  43263. getFrontFacing() {
  43264. return 'gl_FrontFacing';
  43265. }
  43266. /**
  43267. * Returns the frag coord builtin.
  43268. *
  43269. * @return {string} The frag coord builtin.
  43270. */
  43271. getFragCoord() {
  43272. return 'gl_FragCoord.xy';
  43273. }
  43274. /**
  43275. * Returns the frag depth builtin.
  43276. *
  43277. * @return {string} The frag depth builtin.
  43278. */
  43279. getFragDepth() {
  43280. return 'gl_FragDepth';
  43281. }
  43282. /**
  43283. * Enables the given extension.
  43284. *
  43285. * @param {string} name - The extension name.
  43286. * @param {string} behavior - The extension behavior.
  43287. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  43288. */
  43289. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  43290. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  43291. if ( map.has( name ) === false ) {
  43292. map.set( name, {
  43293. name,
  43294. behavior
  43295. } );
  43296. }
  43297. }
  43298. /**
  43299. * Returns the enabled extensions of the given shader stage as a GLSL string.
  43300. *
  43301. * @param {string} shaderStage - The shader stage.
  43302. * @return {string} The GLSL snippet that defines the enabled extensions.
  43303. */
  43304. getExtensions( shaderStage ) {
  43305. const snippets = [];
  43306. if ( shaderStage === 'vertex' ) {
  43307. const ext = this.renderer.backend.extensions;
  43308. const isBatchedMesh = this.object.isBatchedMesh;
  43309. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  43310. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  43311. }
  43312. }
  43313. const extensions = this.extensions[ shaderStage ];
  43314. if ( extensions !== undefined ) {
  43315. for ( const { name, behavior } of extensions.values() ) {
  43316. snippets.push( `#extension ${name} : ${behavior}` );
  43317. }
  43318. }
  43319. return snippets.join( '\n' );
  43320. }
  43321. /**
  43322. * Returns the clip distances builtin.
  43323. *
  43324. * @return {string} The clip distances builtin.
  43325. */
  43326. getClipDistance() {
  43327. return 'gl_ClipDistance';
  43328. }
  43329. /**
  43330. * Whether the requested feature is available or not.
  43331. *
  43332. * @param {string} name - The requested feature.
  43333. * @return {boolean} Whether the requested feature is supported or not.
  43334. */
  43335. isAvailable( name ) {
  43336. let result = supports$1[ name ];
  43337. if ( result === undefined ) {
  43338. let extensionName;
  43339. result = false;
  43340. switch ( name ) {
  43341. case 'float32Filterable':
  43342. extensionName = 'OES_texture_float_linear';
  43343. break;
  43344. case 'clipDistance':
  43345. extensionName = 'WEBGL_clip_cull_distance';
  43346. break;
  43347. }
  43348. if ( extensionName !== undefined ) {
  43349. const extensions = this.renderer.backend.extensions;
  43350. if ( extensions.has( extensionName ) ) {
  43351. extensions.get( extensionName );
  43352. result = true;
  43353. }
  43354. }
  43355. supports$1[ name ] = result;
  43356. }
  43357. return result;
  43358. }
  43359. /**
  43360. * Whether to flip texture data along its vertical axis or not.
  43361. *
  43362. * @return {boolean} Returns always `true` in context of GLSL.
  43363. */
  43364. isFlipY() {
  43365. return true;
  43366. }
  43367. /**
  43368. * Enables hardware clipping.
  43369. *
  43370. * @param {string} planeCount - The clipping plane count.
  43371. */
  43372. enableHardwareClipping( planeCount ) {
  43373. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  43374. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  43375. }
  43376. /**
  43377. * Enables multiview.
  43378. */
  43379. enableMultiview() {
  43380. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  43381. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  43382. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  43383. }
  43384. /**
  43385. * Registers a transform in context of Transform Feedback.
  43386. *
  43387. * @param {string} varyingName - The varying name.
  43388. * @param {AttributeNode} attributeNode - The attribute node.
  43389. */
  43390. registerTransform( varyingName, attributeNode ) {
  43391. this.transforms.push( { varyingName, attributeNode } );
  43392. }
  43393. /**
  43394. * Returns the transforms of the given shader stage as a GLSL string.
  43395. *
  43396. * @param {string} shaderStage - The shader stage.
  43397. * @return {string} The GLSL snippet that defines the transforms.
  43398. */
  43399. getTransforms( /* shaderStage */ ) {
  43400. const transforms = this.transforms;
  43401. let snippet = '';
  43402. for ( let i = 0; i < transforms.length; i ++ ) {
  43403. const transform = transforms[ i ];
  43404. const attributeName = this.getPropertyName( transform.attributeNode );
  43405. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  43406. }
  43407. return snippet;
  43408. }
  43409. /**
  43410. * Returns a GLSL struct based on the given name and variables.
  43411. *
  43412. * @private
  43413. * @param {string} name - The struct name.
  43414. * @param {string} vars - The struct variables.
  43415. * @return {string} The GLSL snippet representing a struct.
  43416. */
  43417. _getGLSLUniformStruct( name, vars ) {
  43418. return `
  43419. layout( std140 ) uniform ${name} {
  43420. ${vars}
  43421. };`;
  43422. }
  43423. /**
  43424. * Returns a GLSL vertex shader based on the given shader data.
  43425. *
  43426. * @private
  43427. * @param {Object} shaderData - The shader data.
  43428. * @return {string} The vertex shader.
  43429. */
  43430. _getGLSLVertexCode( shaderData ) {
  43431. return `#version 300 es
  43432. ${ this.getSignature() }
  43433. // extensions
  43434. ${shaderData.extensions}
  43435. // precision
  43436. ${ defaultPrecisions }
  43437. // uniforms
  43438. ${shaderData.uniforms}
  43439. // varyings
  43440. ${shaderData.varyings}
  43441. // attributes
  43442. ${shaderData.attributes}
  43443. // codes
  43444. ${shaderData.codes}
  43445. void main() {
  43446. // vars
  43447. ${shaderData.vars}
  43448. // transforms
  43449. ${shaderData.transforms}
  43450. // flow
  43451. ${shaderData.flow}
  43452. gl_PointSize = 1.0;
  43453. }
  43454. `;
  43455. }
  43456. /**
  43457. * Returns a GLSL fragment shader based on the given shader data.
  43458. *
  43459. * @private
  43460. * @param {Object} shaderData - The shader data.
  43461. * @return {string} The vertex shader.
  43462. */
  43463. _getGLSLFragmentCode( shaderData ) {
  43464. return `#version 300 es
  43465. ${ this.getSignature() }
  43466. // extensions
  43467. ${shaderData.extensions}
  43468. // precision
  43469. ${ defaultPrecisions }
  43470. // structs
  43471. ${shaderData.structs}
  43472. // uniforms
  43473. ${shaderData.uniforms}
  43474. // varyings
  43475. ${shaderData.varyings}
  43476. // codes
  43477. ${shaderData.codes}
  43478. void main() {
  43479. // vars
  43480. ${shaderData.vars}
  43481. // flow
  43482. ${shaderData.flow}
  43483. }
  43484. `;
  43485. }
  43486. /**
  43487. * Controls the code build of the shader stages.
  43488. */
  43489. buildCode() {
  43490. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  43491. this.sortBindingGroups();
  43492. for ( const shaderStage in shadersData ) {
  43493. let flow = '// code\n\n';
  43494. flow += this.flowCode[ shaderStage ];
  43495. const flowNodes = this.flowNodes[ shaderStage ];
  43496. const mainNode = flowNodes[ flowNodes.length - 1 ];
  43497. for ( const node of flowNodes ) {
  43498. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  43499. const slotName = node.name;
  43500. if ( slotName ) {
  43501. if ( flow.length > 0 ) flow += '\n';
  43502. flow += `\t// flow -> ${ slotName }\n\t`;
  43503. }
  43504. flow += `${ flowSlotData.code }\n\t`;
  43505. if ( node === mainNode && shaderStage !== 'compute' ) {
  43506. flow += '// result\n\t';
  43507. if ( shaderStage === 'vertex' ) {
  43508. flow += 'gl_Position = ';
  43509. flow += `${ flowSlotData.result };`;
  43510. } else if ( shaderStage === 'fragment' ) {
  43511. if ( ! node.outputNode.isOutputStructNode ) {
  43512. flow += 'fragColor = ';
  43513. flow += `${ flowSlotData.result };`;
  43514. }
  43515. }
  43516. }
  43517. }
  43518. const stageData = shadersData[ shaderStage ];
  43519. stageData.extensions = this.getExtensions( shaderStage );
  43520. stageData.uniforms = this.getUniforms( shaderStage );
  43521. stageData.attributes = this.getAttributes( shaderStage );
  43522. stageData.varyings = this.getVaryings( shaderStage );
  43523. stageData.vars = this.getVars( shaderStage );
  43524. stageData.structs = this.getStructs( shaderStage );
  43525. stageData.codes = this.getCodes( shaderStage );
  43526. stageData.transforms = this.getTransforms( shaderStage );
  43527. stageData.flow = flow;
  43528. }
  43529. if ( this.material !== null ) {
  43530. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  43531. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  43532. } else {
  43533. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  43534. }
  43535. }
  43536. /**
  43537. * This method is one of the more important ones since it's responsible
  43538. * for generating a matching binding instance for the given uniform node.
  43539. *
  43540. * These bindings are later used in the renderer to create bind groups
  43541. * and layouts.
  43542. *
  43543. * @param {UniformNode} node - The uniform node.
  43544. * @param {string} type - The node data type.
  43545. * @param {string} shaderStage - The shader stage.
  43546. * @param {?string} [name=null] - An optional uniform name.
  43547. * @return {NodeUniform} The node uniform object.
  43548. */
  43549. getUniformFromNode( node, type, shaderStage, name = null ) {
  43550. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  43551. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  43552. let uniformGPU = nodeData.uniformGPU;
  43553. if ( uniformGPU === undefined ) {
  43554. const group = node.groupNode;
  43555. const groupName = group.name;
  43556. const bindings = this.getBindGroupArray( groupName, shaderStage );
  43557. if ( type === 'texture' ) {
  43558. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  43559. bindings.push( uniformGPU );
  43560. } else if ( type === 'cubeTexture' ) {
  43561. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  43562. bindings.push( uniformGPU );
  43563. } else if ( type === 'texture3D' ) {
  43564. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  43565. bindings.push( uniformGPU );
  43566. } else if ( type === 'buffer' ) {
  43567. node.name = `NodeBuffer_${ node.id }`;
  43568. uniformNode.name = `buffer${ node.id }`;
  43569. const buffer = new NodeUniformBuffer( node, group );
  43570. buffer.name = node.name;
  43571. bindings.push( buffer );
  43572. uniformGPU = buffer;
  43573. } else {
  43574. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  43575. let uniformsGroup = uniformsStage[ groupName ];
  43576. if ( uniformsGroup === undefined ) {
  43577. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  43578. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43579. uniformsStage[ groupName ] = uniformsGroup;
  43580. bindings.push( uniformsGroup );
  43581. }
  43582. uniformGPU = this.getNodeUniform( uniformNode, type );
  43583. uniformsGroup.addUniform( uniformGPU );
  43584. }
  43585. nodeData.uniformGPU = uniformGPU;
  43586. }
  43587. return uniformNode;
  43588. }
  43589. }
  43590. let _vector2 = null;
  43591. let _color4 = null;
  43592. /**
  43593. * Most of the rendering related logic is implemented in the
  43594. * {@link Renderer} module and related management components.
  43595. * Sometimes it is required though to execute commands which are
  43596. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  43597. * This abstract base class defines an interface that encapsulates
  43598. * all backend-related logic. Derived classes for each backend must
  43599. * implement the interface.
  43600. *
  43601. * @abstract
  43602. * @private
  43603. */
  43604. class Backend {
  43605. /**
  43606. * Constructs a new backend.
  43607. *
  43608. * @param {Object} parameters - An object holding parameters for the backend.
  43609. */
  43610. constructor( parameters = {} ) {
  43611. /**
  43612. * The parameters of the backend.
  43613. *
  43614. * @type {Object}
  43615. */
  43616. this.parameters = Object.assign( {}, parameters );
  43617. /**
  43618. * This weak map holds backend-specific data of objects
  43619. * like textures, attributes or render targets.
  43620. *
  43621. * @type {WeakMap<Object, Object>}
  43622. */
  43623. this.data = new WeakMap();
  43624. /**
  43625. * A reference to the renderer.
  43626. *
  43627. * @type {?Renderer}
  43628. * @default null
  43629. */
  43630. this.renderer = null;
  43631. /**
  43632. * A reference to the canvas element the renderer is drawing to.
  43633. *
  43634. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  43635. * @default null
  43636. */
  43637. this.domElement = null;
  43638. /**
  43639. * A reference to the timestamp query pool.
  43640. *
  43641. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  43642. */
  43643. this.timestampQueryPool = {
  43644. [ TimestampQuery.RENDER ]: null,
  43645. [ TimestampQuery.COMPUTE ]: null
  43646. };
  43647. /**
  43648. * Whether to track timestamps with a Timestamp Query API or not.
  43649. *
  43650. * @type {boolean}
  43651. * @default false
  43652. */
  43653. this.trackTimestamp = ( parameters.trackTimestamp === true );
  43654. }
  43655. /**
  43656. * Initializes the backend so it is ready for usage. Concrete backends
  43657. * are supposed to implement their rendering context creation and related
  43658. * operations in this method.
  43659. *
  43660. * @async
  43661. * @param {Renderer} renderer - The renderer.
  43662. * @return {Promise} A Promise that resolves when the backend has been initialized.
  43663. */
  43664. async init( renderer ) {
  43665. this.renderer = renderer;
  43666. }
  43667. /**
  43668. * The coordinate system of the backend.
  43669. *
  43670. * @abstract
  43671. * @type {number}
  43672. * @readonly
  43673. */
  43674. get coordinateSystem() {}
  43675. // render context
  43676. /**
  43677. * This method is executed at the beginning of a render call and
  43678. * can be used by the backend to prepare the state for upcoming
  43679. * draw calls.
  43680. *
  43681. * @abstract
  43682. * @param {RenderContext} renderContext - The render context.
  43683. */
  43684. beginRender( /*renderContext*/ ) {}
  43685. /**
  43686. * This method is executed at the end of a render call and
  43687. * can be used by the backend to finalize work after draw
  43688. * calls.
  43689. *
  43690. * @abstract
  43691. * @param {RenderContext} renderContext - The render context.
  43692. */
  43693. finishRender( /*renderContext*/ ) {}
  43694. /**
  43695. * This method is executed at the beginning of a compute call and
  43696. * can be used by the backend to prepare the state for upcoming
  43697. * compute tasks.
  43698. *
  43699. * @abstract
  43700. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43701. */
  43702. beginCompute( /*computeGroup*/ ) {}
  43703. /**
  43704. * This method is executed at the end of a compute call and
  43705. * can be used by the backend to finalize work after compute
  43706. * tasks.
  43707. *
  43708. * @abstract
  43709. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43710. */
  43711. finishCompute( /*computeGroup*/ ) {}
  43712. // render object
  43713. /**
  43714. * Executes a draw command for the given render object.
  43715. *
  43716. * @abstract
  43717. * @param {RenderObject} renderObject - The render object to draw.
  43718. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  43719. */
  43720. draw( /*renderObject, info*/ ) { }
  43721. // compute node
  43722. /**
  43723. * Executes a compute command for the given compute node.
  43724. *
  43725. * @abstract
  43726. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  43727. * @param {Node} computeNode - The compute node.
  43728. * @param {Array<BindGroup>} bindings - The bindings.
  43729. * @param {ComputePipeline} computePipeline - The compute pipeline.
  43730. */
  43731. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  43732. // program
  43733. /**
  43734. * Creates a shader program from the given programmable stage.
  43735. *
  43736. * @abstract
  43737. * @param {ProgrammableStage} program - The programmable stage.
  43738. */
  43739. createProgram( /*program*/ ) { }
  43740. /**
  43741. * Destroys the shader program of the given programmable stage.
  43742. *
  43743. * @abstract
  43744. * @param {ProgrammableStage} program - The programmable stage.
  43745. */
  43746. destroyProgram( /*program*/ ) { }
  43747. // bindings
  43748. /**
  43749. * Creates bindings from the given bind group definition.
  43750. *
  43751. * @abstract
  43752. * @param {BindGroup} bindGroup - The bind group.
  43753. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43754. * @param {number} cacheIndex - The cache index.
  43755. * @param {number} version - The version.
  43756. */
  43757. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  43758. /**
  43759. * Updates the given bind group definition.
  43760. *
  43761. * @abstract
  43762. * @param {BindGroup} bindGroup - The bind group.
  43763. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43764. * @param {number} cacheIndex - The cache index.
  43765. * @param {number} version - The version.
  43766. */
  43767. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  43768. /**
  43769. * Updates a buffer binding.
  43770. *
  43771. * @abstract
  43772. * @param {Buffer} binding - The buffer binding to update.
  43773. */
  43774. updateBinding( /*binding*/ ) { }
  43775. // pipeline
  43776. /**
  43777. * Creates a render pipeline for the given render object.
  43778. *
  43779. * @abstract
  43780. * @param {RenderObject} renderObject - The render object.
  43781. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  43782. */
  43783. createRenderPipeline( /*renderObject, promises*/ ) { }
  43784. /**
  43785. * Creates a compute pipeline for the given compute node.
  43786. *
  43787. * @abstract
  43788. * @param {ComputePipeline} computePipeline - The compute pipeline.
  43789. * @param {Array<BindGroup>} bindings - The bindings.
  43790. */
  43791. createComputePipeline( /*computePipeline, bindings*/ ) { }
  43792. // cache key
  43793. /**
  43794. * Returns `true` if the render pipeline requires an update.
  43795. *
  43796. * @abstract
  43797. * @param {RenderObject} renderObject - The render object.
  43798. * @return {boolean} Whether the render pipeline requires an update or not.
  43799. */
  43800. needsRenderUpdate( /*renderObject*/ ) { }
  43801. /**
  43802. * Returns a cache key that is used to identify render pipelines.
  43803. *
  43804. * @abstract
  43805. * @param {RenderObject} renderObject - The render object.
  43806. * @return {string} The cache key.
  43807. */
  43808. getRenderCacheKey( /*renderObject*/ ) { }
  43809. // node builder
  43810. /**
  43811. * Returns a node builder for the given render object.
  43812. *
  43813. * @abstract
  43814. * @param {RenderObject} renderObject - The render object.
  43815. * @param {Renderer} renderer - The renderer.
  43816. * @return {NodeBuilder} The node builder.
  43817. */
  43818. createNodeBuilder( /*renderObject, renderer*/ ) { }
  43819. // textures
  43820. /**
  43821. * Updates a GPU sampler for the given texture.
  43822. *
  43823. * @abstract
  43824. * @param {Texture} texture - The texture to update the sampler for.
  43825. * @return {string} The current sampler key.
  43826. */
  43827. updateSampler( /*texture*/ ) { }
  43828. /**
  43829. * Creates a default texture for the given texture that can be used
  43830. * as a placeholder until the actual texture is ready for usage.
  43831. *
  43832. * @abstract
  43833. * @param {Texture} texture - The texture to create a default texture for.
  43834. */
  43835. createDefaultTexture( /*texture*/ ) { }
  43836. /**
  43837. * Defines a texture on the GPU for the given texture object.
  43838. *
  43839. * @abstract
  43840. * @param {Texture} texture - The texture.
  43841. * @param {Object} [options={}] - Optional configuration parameter.
  43842. */
  43843. createTexture( /*texture, options={}*/ ) { }
  43844. /**
  43845. * Uploads the updated texture data to the GPU.
  43846. *
  43847. * @abstract
  43848. * @param {Texture} texture - The texture.
  43849. * @param {Object} [options={}] - Optional configuration parameter.
  43850. */
  43851. updateTexture( /*texture, options = {}*/ ) { }
  43852. /**
  43853. * Generates mipmaps for the given texture.
  43854. *
  43855. * @abstract
  43856. * @param {Texture} texture - The texture.
  43857. */
  43858. generateMipmaps( /*texture*/ ) { }
  43859. /**
  43860. * Destroys the GPU data for the given texture object.
  43861. *
  43862. * @abstract
  43863. * @param {Texture} texture - The texture.
  43864. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  43865. */
  43866. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  43867. /**
  43868. * Returns texture data as a typed array.
  43869. *
  43870. * @abstract
  43871. * @async
  43872. * @param {Texture} texture - The texture to copy.
  43873. * @param {number} x - The x coordinate of the copy origin.
  43874. * @param {number} y - The y coordinate of the copy origin.
  43875. * @param {number} width - The width of the copy.
  43876. * @param {number} height - The height of the copy.
  43877. * @param {number} faceIndex - The face index.
  43878. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  43879. */
  43880. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  43881. /**
  43882. * Copies data of the given source texture to the given destination texture.
  43883. *
  43884. * @abstract
  43885. * @param {Texture} srcTexture - The source texture.
  43886. * @param {Texture} dstTexture - The destination texture.
  43887. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  43888. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  43889. * @param {number} [srcLevel=0] - The source mip level to copy from.
  43890. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  43891. */
  43892. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  43893. /**
  43894. * Copies the current bound framebuffer to the given texture.
  43895. *
  43896. * @abstract
  43897. * @param {Texture} texture - The destination texture.
  43898. * @param {RenderContext} renderContext - The render context.
  43899. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  43900. */
  43901. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  43902. // attributes
  43903. /**
  43904. * Creates the GPU buffer of a shader attribute.
  43905. *
  43906. * @abstract
  43907. * @param {BufferAttribute} attribute - The buffer attribute.
  43908. */
  43909. createAttribute( /*attribute*/ ) { }
  43910. /**
  43911. * Creates the GPU buffer of an indexed shader attribute.
  43912. *
  43913. * @abstract
  43914. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  43915. */
  43916. createIndexAttribute( /*attribute*/ ) { }
  43917. /**
  43918. * Creates the GPU buffer of a storage attribute.
  43919. *
  43920. * @abstract
  43921. * @param {BufferAttribute} attribute - The buffer attribute.
  43922. */
  43923. createStorageAttribute( /*attribute*/ ) { }
  43924. /**
  43925. * Updates the GPU buffer of a shader attribute.
  43926. *
  43927. * @abstract
  43928. * @param {BufferAttribute} attribute - The buffer attribute to update.
  43929. */
  43930. updateAttribute( /*attribute*/ ) { }
  43931. /**
  43932. * Destroys the GPU buffer of a shader attribute.
  43933. *
  43934. * @abstract
  43935. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  43936. */
  43937. destroyAttribute( /*attribute*/ ) { }
  43938. // canvas
  43939. /**
  43940. * Returns the backend's rendering context.
  43941. *
  43942. * @abstract
  43943. * @return {Object} The rendering context.
  43944. */
  43945. getContext() { }
  43946. /**
  43947. * Backends can use this method if they have to run
  43948. * logic when the renderer gets resized.
  43949. *
  43950. * @abstract
  43951. */
  43952. updateSize() { }
  43953. /**
  43954. * Updates the viewport with the values from the given render context.
  43955. *
  43956. * @abstract
  43957. * @param {RenderContext} renderContext - The render context.
  43958. */
  43959. updateViewport( /*renderContext*/ ) {}
  43960. // utils
  43961. /**
  43962. * Updates a unique identifier for the given render context that can be used
  43963. * to allocate resources like occlusion queries or timestamp queries.
  43964. *
  43965. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  43966. */
  43967. updateTimeStampUID( abstractRenderContext ) {
  43968. const contextData = this.get( abstractRenderContext );
  43969. const frame = this.renderer.info.frame;
  43970. let prefix;
  43971. if ( abstractRenderContext.isComputeNode === true ) {
  43972. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  43973. } else {
  43974. prefix = 'r:' + this.renderer.info.render.frameCalls;
  43975. }
  43976. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  43977. }
  43978. /**
  43979. * Returns a unique identifier for the given render context that can be used
  43980. * to allocate resources like occlusion queries or timestamp queries.
  43981. *
  43982. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  43983. * @return {string} The unique identifier.
  43984. */
  43985. getTimestampUID( abstractRenderContext ) {
  43986. return this.get( abstractRenderContext ).timestampUID;
  43987. }
  43988. /**
  43989. * Returns all timestamp frames for the given type.
  43990. *
  43991. * @param {string} type - The type of the time stamp.
  43992. * @return {Array<number>} The timestamp frames.
  43993. */
  43994. getTimestampFrames( type ) {
  43995. const queryPool = this.timestampQueryPool[ type ];
  43996. return queryPool ? queryPool.getTimestampFrames() : [];
  43997. }
  43998. /**
  43999. * Returns the query pool for the given uid.
  44000. *
  44001. * @param {string} uid - The unique identifier.
  44002. * @return {TimestampQueryPool} The query pool.
  44003. */
  44004. _getQueryPool( uid ) {
  44005. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  44006. const queryPool = this.timestampQueryPool[ type ];
  44007. return queryPool;
  44008. }
  44009. /**
  44010. * Returns the timestamp for the given uid.
  44011. *
  44012. * @param {string} uid - The unique identifier.
  44013. * @return {number} The timestamp.
  44014. */
  44015. getTimestamp( uid ) {
  44016. const queryPool = this._getQueryPool( uid );
  44017. return queryPool.getTimestamp( uid );
  44018. }
  44019. /**
  44020. * Returns `true` if a timestamp for the given uid is available.
  44021. *
  44022. * @param {string} uid - The unique identifier.
  44023. * @return {boolean} Whether the timestamp is available or not.
  44024. */
  44025. hasTimestamp( uid ) {
  44026. const queryPool = this._getQueryPool( uid );
  44027. return queryPool.hasTimestamp( uid );
  44028. }
  44029. /**
  44030. * Returns `true` if the given 3D object is fully occluded by other
  44031. * 3D objects in the scene. Backends must implement this method by using
  44032. * a Occlusion Query API.
  44033. *
  44034. * @abstract
  44035. * @param {RenderContext} renderContext - The render context.
  44036. * @param {Object3D} object - The 3D object to test.
  44037. * @return {boolean} Whether the 3D object is fully occluded or not.
  44038. */
  44039. isOccluded( /*renderContext, object*/ ) {}
  44040. /**
  44041. * Resolves the time stamp for the given render context and type.
  44042. *
  44043. * @async
  44044. * @abstract
  44045. * @param {string} [type='render'] - The type of the time stamp.
  44046. * @return {Promise<number>} A Promise that resolves with the time stamp.
  44047. */
  44048. async resolveTimestampsAsync( type = 'render' ) {
  44049. if ( ! this.trackTimestamp ) {
  44050. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  44051. return;
  44052. }
  44053. const queryPool = this.timestampQueryPool[ type ];
  44054. if ( ! queryPool ) {
  44055. return;
  44056. }
  44057. const duration = await queryPool.resolveQueriesAsync();
  44058. this.renderer.info[ type ].timestamp = duration;
  44059. return duration;
  44060. }
  44061. /**
  44062. * This method performs a readback operation by moving buffer data from
  44063. * a storage buffer attribute from the GPU to the CPU.
  44064. *
  44065. * @async
  44066. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44067. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44068. */
  44069. async getArrayBufferAsync( /* attribute */ ) {}
  44070. /**
  44071. * Checks if the given feature is supported by the backend.
  44072. *
  44073. * @async
  44074. * @abstract
  44075. * @param {string} name - The feature's name.
  44076. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  44077. */
  44078. async hasFeatureAsync( /*name*/ ) { }
  44079. /**
  44080. * Checks if the given feature is supported by the backend.
  44081. *
  44082. * @abstract
  44083. * @param {string} name - The feature's name.
  44084. * @return {boolean} Whether the feature is supported or not.
  44085. */
  44086. hasFeature( /*name*/ ) {}
  44087. /**
  44088. * Returns the maximum anisotropy texture filtering value.
  44089. *
  44090. * @abstract
  44091. * @return {number} The maximum anisotropy texture filtering value.
  44092. */
  44093. getMaxAnisotropy() {}
  44094. /**
  44095. * Returns the drawing buffer size.
  44096. *
  44097. * @return {Vector2} The drawing buffer size.
  44098. */
  44099. getDrawingBufferSize() {
  44100. _vector2 = _vector2 || new Vector2();
  44101. return this.renderer.getDrawingBufferSize( _vector2 );
  44102. }
  44103. /**
  44104. * Defines the scissor test.
  44105. *
  44106. * @abstract
  44107. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  44108. */
  44109. setScissorTest( /*boolean*/ ) { }
  44110. /**
  44111. * Returns the clear color and alpha into a single
  44112. * color object.
  44113. *
  44114. * @return {Color4} The clear color.
  44115. */
  44116. getClearColor() {
  44117. const renderer = this.renderer;
  44118. _color4 = _color4 || new Color4();
  44119. renderer.getClearColor( _color4 );
  44120. _color4.getRGB( _color4 );
  44121. return _color4;
  44122. }
  44123. /**
  44124. * Returns the DOM element. If no DOM element exists, the backend
  44125. * creates a new one.
  44126. *
  44127. * @return {HTMLCanvasElement} The DOM element.
  44128. */
  44129. getDomElement() {
  44130. let domElement = this.domElement;
  44131. if ( domElement === null ) {
  44132. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  44133. // OffscreenCanvas does not have setAttribute, see #22811
  44134. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  44135. this.domElement = domElement;
  44136. }
  44137. return domElement;
  44138. }
  44139. /**
  44140. * Sets a dictionary for the given object into the
  44141. * internal data structure.
  44142. *
  44143. * @param {Object} object - The object.
  44144. * @param {Object} value - The dictionary to set.
  44145. */
  44146. set( object, value ) {
  44147. this.data.set( object, value );
  44148. }
  44149. /**
  44150. * Returns the dictionary for the given object.
  44151. *
  44152. * @param {Object} object - The object.
  44153. * @return {Object} The object's dictionary.
  44154. */
  44155. get( object ) {
  44156. let map = this.data.get( object );
  44157. if ( map === undefined ) {
  44158. map = {};
  44159. this.data.set( object, map );
  44160. }
  44161. return map;
  44162. }
  44163. /**
  44164. * Checks if the given object has a dictionary
  44165. * with data defined.
  44166. *
  44167. * @param {Object} object - The object.
  44168. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  44169. */
  44170. has( object ) {
  44171. return this.data.has( object );
  44172. }
  44173. /**
  44174. * Deletes an object from the internal data structure.
  44175. *
  44176. * @param {Object} object - The object to delete.
  44177. */
  44178. delete( object ) {
  44179. this.data.delete( object );
  44180. }
  44181. /**
  44182. * Frees internal resources.
  44183. *
  44184. * @abstract
  44185. */
  44186. dispose() { }
  44187. }
  44188. let _id$1 = 0;
  44189. /**
  44190. * This module is internally used in context of compute shaders.
  44191. * This type of shader is not natively supported in WebGL 2 and
  44192. * thus implemented via Transform Feedback. `DualAttributeData`
  44193. * manages the related data.
  44194. *
  44195. * @private
  44196. */
  44197. class DualAttributeData {
  44198. constructor( attributeData, dualBuffer ) {
  44199. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  44200. this.type = attributeData.type;
  44201. this.bufferType = attributeData.bufferType;
  44202. this.pbo = attributeData.pbo;
  44203. this.byteLength = attributeData.byteLength;
  44204. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  44205. this.version = attributeData.version;
  44206. this.isInteger = attributeData.isInteger;
  44207. this.activeBufferIndex = 0;
  44208. this.baseId = attributeData.id;
  44209. }
  44210. get id() {
  44211. return `${ this.baseId }|${ this.activeBufferIndex }`;
  44212. }
  44213. get bufferGPU() {
  44214. return this.buffers[ this.activeBufferIndex ];
  44215. }
  44216. get transformBuffer() {
  44217. return this.buffers[ this.activeBufferIndex ^ 1 ];
  44218. }
  44219. switchBuffers() {
  44220. this.activeBufferIndex ^= 1;
  44221. }
  44222. }
  44223. /**
  44224. * A WebGL 2 backend utility module for managing shader attributes.
  44225. *
  44226. * @private
  44227. */
  44228. class WebGLAttributeUtils {
  44229. /**
  44230. * Constructs a new utility object.
  44231. *
  44232. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44233. */
  44234. constructor( backend ) {
  44235. /**
  44236. * A reference to the WebGL 2 backend.
  44237. *
  44238. * @type {WebGLBackend}
  44239. */
  44240. this.backend = backend;
  44241. }
  44242. /**
  44243. * Creates the GPU buffer for the given buffer attribute.
  44244. *
  44245. * @param {BufferAttribute} attribute - The buffer attribute.
  44246. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  44247. */
  44248. createAttribute( attribute, bufferType ) {
  44249. const backend = this.backend;
  44250. const { gl } = backend;
  44251. const array = attribute.array;
  44252. const usage = attribute.usage || gl.STATIC_DRAW;
  44253. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44254. const bufferData = backend.get( bufferAttribute );
  44255. let bufferGPU = bufferData.bufferGPU;
  44256. if ( bufferGPU === undefined ) {
  44257. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  44258. bufferData.bufferGPU = bufferGPU;
  44259. bufferData.bufferType = bufferType;
  44260. bufferData.version = bufferAttribute.version;
  44261. }
  44262. //attribute.onUploadCallback();
  44263. let type;
  44264. if ( array instanceof Float32Array ) {
  44265. type = gl.FLOAT;
  44266. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  44267. type = gl.HALF_FLOAT;
  44268. } else if ( array instanceof Uint16Array ) {
  44269. if ( attribute.isFloat16BufferAttribute ) {
  44270. type = gl.HALF_FLOAT;
  44271. } else {
  44272. type = gl.UNSIGNED_SHORT;
  44273. }
  44274. } else if ( array instanceof Int16Array ) {
  44275. type = gl.SHORT;
  44276. } else if ( array instanceof Uint32Array ) {
  44277. type = gl.UNSIGNED_INT;
  44278. } else if ( array instanceof Int32Array ) {
  44279. type = gl.INT;
  44280. } else if ( array instanceof Int8Array ) {
  44281. type = gl.BYTE;
  44282. } else if ( array instanceof Uint8Array ) {
  44283. type = gl.UNSIGNED_BYTE;
  44284. } else if ( array instanceof Uint8ClampedArray ) {
  44285. type = gl.UNSIGNED_BYTE;
  44286. } else {
  44287. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  44288. }
  44289. let attributeData = {
  44290. bufferGPU,
  44291. bufferType,
  44292. type,
  44293. byteLength: array.byteLength,
  44294. bytesPerElement: array.BYTES_PER_ELEMENT,
  44295. version: attribute.version,
  44296. pbo: attribute.pbo,
  44297. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  44298. id: _id$1 ++
  44299. };
  44300. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  44301. // create buffer for transform feedback use
  44302. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  44303. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  44304. }
  44305. backend.set( attribute, attributeData );
  44306. }
  44307. /**
  44308. * Updates the GPU buffer of the given buffer attribute.
  44309. *
  44310. * @param {BufferAttribute} attribute - The buffer attribute.
  44311. */
  44312. updateAttribute( attribute ) {
  44313. const backend = this.backend;
  44314. const { gl } = backend;
  44315. const array = attribute.array;
  44316. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44317. const bufferData = backend.get( bufferAttribute );
  44318. const bufferType = bufferData.bufferType;
  44319. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  44320. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  44321. if ( updateRanges.length === 0 ) {
  44322. // Not using update ranges
  44323. gl.bufferSubData( bufferType, 0, array );
  44324. } else {
  44325. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  44326. const range = updateRanges[ i ];
  44327. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  44328. array, range.start, range.count );
  44329. }
  44330. bufferAttribute.clearUpdateRanges();
  44331. }
  44332. gl.bindBuffer( bufferType, null );
  44333. bufferData.version = bufferAttribute.version;
  44334. }
  44335. /**
  44336. * Destroys the GPU buffer of the given buffer attribute.
  44337. *
  44338. * @param {BufferAttribute} attribute - The buffer attribute.
  44339. */
  44340. destroyAttribute( attribute ) {
  44341. const backend = this.backend;
  44342. const { gl } = backend;
  44343. if ( attribute.isInterleavedBufferAttribute ) {
  44344. backend.delete( attribute.data );
  44345. }
  44346. const attributeData = backend.get( attribute );
  44347. gl.deleteBuffer( attributeData.bufferGPU );
  44348. backend.delete( attribute );
  44349. }
  44350. /**
  44351. * This method performs a readback operation by moving buffer data from
  44352. * a storage buffer attribute from the GPU to the CPU.
  44353. *
  44354. * @async
  44355. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44356. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44357. */
  44358. async getArrayBufferAsync( attribute ) {
  44359. const backend = this.backend;
  44360. const { gl } = backend;
  44361. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44362. const { bufferGPU } = backend.get( bufferAttribute );
  44363. const array = attribute.array;
  44364. const byteLength = array.byteLength;
  44365. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  44366. const writeBuffer = gl.createBuffer();
  44367. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  44368. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  44369. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  44370. await backend.utils._clientWaitAsync();
  44371. const dstBuffer = new attribute.array.constructor( array.length );
  44372. // Ensure the buffer is bound before reading
  44373. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  44374. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  44375. gl.deleteBuffer( writeBuffer );
  44376. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  44377. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  44378. return dstBuffer.buffer;
  44379. }
  44380. /**
  44381. * Creates a WebGL buffer with the given data.
  44382. *
  44383. * @private
  44384. * @param {WebGL2RenderingContext} gl - The rendering context.
  44385. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  44386. * @param {TypedArray} array - The array of the buffer attribute.
  44387. * @param {GLenum} usage - The usage.
  44388. * @return {WebGLBuffer} The WebGL buffer.
  44389. */
  44390. _createBuffer( gl, bufferType, array, usage ) {
  44391. const bufferGPU = gl.createBuffer();
  44392. gl.bindBuffer( bufferType, bufferGPU );
  44393. gl.bufferData( bufferType, array, usage );
  44394. gl.bindBuffer( bufferType, null );
  44395. return bufferGPU;
  44396. }
  44397. }
  44398. let equationToGL, factorToGL;
  44399. /**
  44400. * A WebGL 2 backend utility module for managing the WebGL state.
  44401. *
  44402. * The major goal of this module is to reduce the number of state changes
  44403. * by caching the WEbGL state with a series of variables. In this way, the
  44404. * renderer only executes state change commands when necessary which
  44405. * improves the overall performance.
  44406. *
  44407. * @private
  44408. */
  44409. class WebGLState {
  44410. /**
  44411. * Constructs a new utility object.
  44412. *
  44413. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44414. */
  44415. constructor( backend ) {
  44416. /**
  44417. * A reference to the WebGL 2 backend.
  44418. *
  44419. * @type {WebGLBackend}
  44420. */
  44421. this.backend = backend;
  44422. /**
  44423. * A reference to the rendering context.
  44424. *
  44425. * @type {WebGL2RenderingContext}
  44426. */
  44427. this.gl = this.backend.gl;
  44428. // Below properties are intended to cache
  44429. // the WebGL state and are not explicitly
  44430. // documented for convenience reasons.
  44431. this.enabled = {};
  44432. this.currentFlipSided = null;
  44433. this.currentCullFace = null;
  44434. this.currentProgram = null;
  44435. this.currentBlendingEnabled = false;
  44436. this.currentBlending = null;
  44437. this.currentBlendSrc = null;
  44438. this.currentBlendDst = null;
  44439. this.currentBlendSrcAlpha = null;
  44440. this.currentBlendDstAlpha = null;
  44441. this.currentPremultipledAlpha = null;
  44442. this.currentPolygonOffsetFactor = null;
  44443. this.currentPolygonOffsetUnits = null;
  44444. this.currentColorMask = null;
  44445. this.currentDepthFunc = null;
  44446. this.currentDepthMask = null;
  44447. this.currentStencilFunc = null;
  44448. this.currentStencilRef = null;
  44449. this.currentStencilFuncMask = null;
  44450. this.currentStencilFail = null;
  44451. this.currentStencilZFail = null;
  44452. this.currentStencilZPass = null;
  44453. this.currentStencilMask = null;
  44454. this.currentLineWidth = null;
  44455. this.currentClippingPlanes = 0;
  44456. this.currentVAO = null;
  44457. this.currentIndex = null;
  44458. this.currentBoundFramebuffers = {};
  44459. this.currentDrawbuffers = new WeakMap();
  44460. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  44461. this.currentTextureSlot = null;
  44462. this.currentBoundTextures = {};
  44463. this.currentBoundBufferBases = {};
  44464. this._init();
  44465. }
  44466. /**
  44467. * Inits the state of the utility.
  44468. *
  44469. * @private
  44470. */
  44471. _init() {
  44472. const gl = this.gl;
  44473. // Store only WebGL constants here.
  44474. equationToGL = {
  44475. [ AddEquation ]: gl.FUNC_ADD,
  44476. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  44477. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  44478. };
  44479. factorToGL = {
  44480. [ ZeroFactor ]: gl.ZERO,
  44481. [ OneFactor ]: gl.ONE,
  44482. [ SrcColorFactor ]: gl.SRC_COLOR,
  44483. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  44484. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  44485. [ DstColorFactor ]: gl.DST_COLOR,
  44486. [ DstAlphaFactor ]: gl.DST_ALPHA,
  44487. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  44488. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  44489. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  44490. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  44491. };
  44492. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  44493. const viewportParam = gl.getParameter( gl.VIEWPORT );
  44494. this.currentScissor = new Vector4().fromArray( scissorParam );
  44495. this.currentViewport = new Vector4().fromArray( viewportParam );
  44496. this._tempVec4 = new Vector4();
  44497. }
  44498. /**
  44499. * Enables the given WebGL capability.
  44500. *
  44501. * This method caches the capability state so
  44502. * `gl.enable()` is only called when necessary.
  44503. *
  44504. * @param {GLenum} id - The capability to enable.
  44505. */
  44506. enable( id ) {
  44507. const { enabled } = this;
  44508. if ( enabled[ id ] !== true ) {
  44509. this.gl.enable( id );
  44510. enabled[ id ] = true;
  44511. }
  44512. }
  44513. /**
  44514. * Disables the given WebGL capability.
  44515. *
  44516. * This method caches the capability state so
  44517. * `gl.disable()` is only called when necessary.
  44518. *
  44519. * @param {GLenum} id - The capability to enable.
  44520. */
  44521. disable( id ) {
  44522. const { enabled } = this;
  44523. if ( enabled[ id ] !== false ) {
  44524. this.gl.disable( id );
  44525. enabled[ id ] = false;
  44526. }
  44527. }
  44528. /**
  44529. * Specifies whether polygons are front- or back-facing
  44530. * by setting the winding orientation.
  44531. *
  44532. * This method caches the state so `gl.frontFace()` is only
  44533. * called when necessary.
  44534. *
  44535. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  44536. */
  44537. setFlipSided( flipSided ) {
  44538. if ( this.currentFlipSided !== flipSided ) {
  44539. const { gl } = this;
  44540. if ( flipSided ) {
  44541. gl.frontFace( gl.CW );
  44542. } else {
  44543. gl.frontFace( gl.CCW );
  44544. }
  44545. this.currentFlipSided = flipSided;
  44546. }
  44547. }
  44548. /**
  44549. * Specifies whether or not front- and/or back-facing
  44550. * polygons can be culled.
  44551. *
  44552. * This method caches the state so `gl.cullFace()` is only
  44553. * called when necessary.
  44554. *
  44555. * @param {number} cullFace - Defines which polygons are candidates for culling.
  44556. */
  44557. setCullFace( cullFace ) {
  44558. const { gl } = this;
  44559. if ( cullFace !== CullFaceNone ) {
  44560. this.enable( gl.CULL_FACE );
  44561. if ( cullFace !== this.currentCullFace ) {
  44562. if ( cullFace === CullFaceBack ) {
  44563. gl.cullFace( gl.BACK );
  44564. } else if ( cullFace === CullFaceFront ) {
  44565. gl.cullFace( gl.FRONT );
  44566. } else {
  44567. gl.cullFace( gl.FRONT_AND_BACK );
  44568. }
  44569. }
  44570. } else {
  44571. this.disable( gl.CULL_FACE );
  44572. }
  44573. this.currentCullFace = cullFace;
  44574. }
  44575. /**
  44576. * Specifies the width of line primitives.
  44577. *
  44578. * This method caches the state so `gl.lineWidth()` is only
  44579. * called when necessary.
  44580. *
  44581. * @param {number} width - The line width.
  44582. */
  44583. setLineWidth( width ) {
  44584. const { currentLineWidth, gl } = this;
  44585. if ( width !== currentLineWidth ) {
  44586. gl.lineWidth( width );
  44587. this.currentLineWidth = width;
  44588. }
  44589. }
  44590. /**
  44591. * Defines the blending.
  44592. *
  44593. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  44594. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  44595. *
  44596. * @param {number} blending - The blending type.
  44597. * @param {number} blendEquation - The blending equation.
  44598. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  44599. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  44600. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  44601. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  44602. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  44603. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  44604. */
  44605. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  44606. const { gl } = this;
  44607. if ( blending === NoBlending ) {
  44608. if ( this.currentBlendingEnabled === true ) {
  44609. this.disable( gl.BLEND );
  44610. this.currentBlendingEnabled = false;
  44611. }
  44612. return;
  44613. }
  44614. if ( this.currentBlendingEnabled === false ) {
  44615. this.enable( gl.BLEND );
  44616. this.currentBlendingEnabled = true;
  44617. }
  44618. if ( blending !== CustomBlending ) {
  44619. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  44620. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  44621. gl.blendEquation( gl.FUNC_ADD );
  44622. this.currentBlendEquation = AddEquation;
  44623. this.currentBlendEquationAlpha = AddEquation;
  44624. }
  44625. if ( premultipliedAlpha ) {
  44626. switch ( blending ) {
  44627. case NormalBlending:
  44628. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  44629. break;
  44630. case AdditiveBlending:
  44631. gl.blendFunc( gl.ONE, gl.ONE );
  44632. break;
  44633. case SubtractiveBlending:
  44634. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  44635. break;
  44636. case MultiplyBlending:
  44637. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  44638. break;
  44639. default:
  44640. error( 'WebGLState: Invalid blending: ', blending );
  44641. break;
  44642. }
  44643. } else {
  44644. switch ( blending ) {
  44645. case NormalBlending:
  44646. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  44647. break;
  44648. case AdditiveBlending:
  44649. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  44650. break;
  44651. case SubtractiveBlending:
  44652. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  44653. break;
  44654. case MultiplyBlending:
  44655. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  44656. break;
  44657. default:
  44658. error( 'WebGLState: Invalid blending: ', blending );
  44659. break;
  44660. }
  44661. }
  44662. this.currentBlendSrc = null;
  44663. this.currentBlendDst = null;
  44664. this.currentBlendSrcAlpha = null;
  44665. this.currentBlendDstAlpha = null;
  44666. this.currentBlending = blending;
  44667. this.currentPremultipledAlpha = premultipliedAlpha;
  44668. }
  44669. return;
  44670. }
  44671. // custom blending
  44672. blendEquationAlpha = blendEquationAlpha || blendEquation;
  44673. blendSrcAlpha = blendSrcAlpha || blendSrc;
  44674. blendDstAlpha = blendDstAlpha || blendDst;
  44675. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  44676. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  44677. this.currentBlendEquation = blendEquation;
  44678. this.currentBlendEquationAlpha = blendEquationAlpha;
  44679. }
  44680. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  44681. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  44682. this.currentBlendSrc = blendSrc;
  44683. this.currentBlendDst = blendDst;
  44684. this.currentBlendSrcAlpha = blendSrcAlpha;
  44685. this.currentBlendDstAlpha = blendDstAlpha;
  44686. }
  44687. this.currentBlending = blending;
  44688. this.currentPremultipledAlpha = false;
  44689. }
  44690. /**
  44691. * Specifies whether colors can be written when rendering
  44692. * into a framebuffer or not.
  44693. *
  44694. * This method caches the state so `gl.colorMask()` is only
  44695. * called when necessary.
  44696. *
  44697. * @param {boolean} colorMask - The color mask.
  44698. */
  44699. setColorMask( colorMask ) {
  44700. if ( this.currentColorMask !== colorMask ) {
  44701. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  44702. this.currentColorMask = colorMask;
  44703. }
  44704. }
  44705. /**
  44706. * Specifies whether the depth test is enabled or not.
  44707. *
  44708. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  44709. */
  44710. setDepthTest( depthTest ) {
  44711. const { gl } = this;
  44712. if ( depthTest ) {
  44713. this.enable( gl.DEPTH_TEST );
  44714. } else {
  44715. this.disable( gl.DEPTH_TEST );
  44716. }
  44717. }
  44718. /**
  44719. * Specifies whether depth values can be written when rendering
  44720. * into a framebuffer or not.
  44721. *
  44722. * This method caches the state so `gl.depthMask()` is only
  44723. * called when necessary.
  44724. *
  44725. * @param {boolean} depthMask - The depth mask.
  44726. */
  44727. setDepthMask( depthMask ) {
  44728. if ( this.currentDepthMask !== depthMask ) {
  44729. this.gl.depthMask( depthMask );
  44730. this.currentDepthMask = depthMask;
  44731. }
  44732. }
  44733. /**
  44734. * Specifies the depth compare function.
  44735. *
  44736. * This method caches the state so `gl.depthFunc()` is only
  44737. * called when necessary.
  44738. *
  44739. * @param {number} depthFunc - The depth compare function.
  44740. */
  44741. setDepthFunc( depthFunc ) {
  44742. if ( this.currentDepthFunc !== depthFunc ) {
  44743. const { gl } = this;
  44744. switch ( depthFunc ) {
  44745. case NeverDepth:
  44746. gl.depthFunc( gl.NEVER );
  44747. break;
  44748. case AlwaysDepth:
  44749. gl.depthFunc( gl.ALWAYS );
  44750. break;
  44751. case LessDepth:
  44752. gl.depthFunc( gl.LESS );
  44753. break;
  44754. case LessEqualDepth:
  44755. gl.depthFunc( gl.LEQUAL );
  44756. break;
  44757. case EqualDepth:
  44758. gl.depthFunc( gl.EQUAL );
  44759. break;
  44760. case GreaterEqualDepth:
  44761. gl.depthFunc( gl.GEQUAL );
  44762. break;
  44763. case GreaterDepth:
  44764. gl.depthFunc( gl.GREATER );
  44765. break;
  44766. case NotEqualDepth:
  44767. gl.depthFunc( gl.NOTEQUAL );
  44768. break;
  44769. default:
  44770. gl.depthFunc( gl.LEQUAL );
  44771. }
  44772. this.currentDepthFunc = depthFunc;
  44773. }
  44774. }
  44775. /**
  44776. * Specifies the scissor box.
  44777. *
  44778. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  44779. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  44780. * @param {number} width - The width of the viewport.
  44781. * @param {number} height - The height of the viewport.
  44782. *
  44783. */
  44784. scissor( x, y, width, height ) {
  44785. const scissor = this._tempVec4.set( x, y, width, height );
  44786. if ( this.currentScissor.equals( scissor ) === false ) {
  44787. const { gl } = this;
  44788. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  44789. this.currentScissor.copy( scissor );
  44790. }
  44791. }
  44792. /**
  44793. * Specifies the viewport.
  44794. *
  44795. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  44796. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  44797. * @param {number} width - The width of the viewport.
  44798. * @param {number} height - The height of the viewport.
  44799. *
  44800. */
  44801. viewport( x, y, width, height ) {
  44802. const viewport = this._tempVec4.set( x, y, width, height );
  44803. if ( this.currentViewport.equals( viewport ) === false ) {
  44804. const { gl } = this;
  44805. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  44806. this.currentViewport.copy( viewport );
  44807. }
  44808. }
  44809. /**
  44810. * Defines the scissor test.
  44811. *
  44812. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  44813. */
  44814. setScissorTest( boolean ) {
  44815. const gl = this.gl;
  44816. if ( boolean ) {
  44817. gl.enable( gl.SCISSOR_TEST );
  44818. } else {
  44819. gl.disable( gl.SCISSOR_TEST );
  44820. }
  44821. }
  44822. /**
  44823. * Specifies whether the stencil test is enabled or not.
  44824. *
  44825. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  44826. */
  44827. setStencilTest( stencilTest ) {
  44828. const { gl } = this;
  44829. if ( stencilTest ) {
  44830. this.enable( gl.STENCIL_TEST );
  44831. } else {
  44832. this.disable( gl.STENCIL_TEST );
  44833. }
  44834. }
  44835. /**
  44836. * Specifies whether stencil values can be written when rendering
  44837. * into a framebuffer or not.
  44838. *
  44839. * This method caches the state so `gl.stencilMask()` is only
  44840. * called when necessary.
  44841. *
  44842. * @param {boolean} stencilMask - The stencil mask.
  44843. */
  44844. setStencilMask( stencilMask ) {
  44845. if ( this.currentStencilMask !== stencilMask ) {
  44846. this.gl.stencilMask( stencilMask );
  44847. this.currentStencilMask = stencilMask;
  44848. }
  44849. }
  44850. /**
  44851. * Specifies whether the stencil test functions.
  44852. *
  44853. * This method caches the state so `gl.stencilFunc()` is only
  44854. * called when necessary.
  44855. *
  44856. * @param {number} stencilFunc - The stencil compare function.
  44857. * @param {number} stencilRef - The reference value for the stencil test.
  44858. * @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.
  44859. */
  44860. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  44861. if ( this.currentStencilFunc !== stencilFunc ||
  44862. this.currentStencilRef !== stencilRef ||
  44863. this.currentStencilFuncMask !== stencilMask ) {
  44864. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  44865. this.currentStencilFunc = stencilFunc;
  44866. this.currentStencilRef = stencilRef;
  44867. this.currentStencilFuncMask = stencilMask;
  44868. }
  44869. }
  44870. /**
  44871. * Specifies whether the stencil test operation.
  44872. *
  44873. * This method caches the state so `gl.stencilOp()` is only
  44874. * called when necessary.
  44875. *
  44876. * @param {number} stencilFail - The function to use when the stencil test fails.
  44877. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  44878. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  44879. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  44880. */
  44881. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  44882. if ( this.currentStencilFail !== stencilFail ||
  44883. this.currentStencilZFail !== stencilZFail ||
  44884. this.currentStencilZPass !== stencilZPass ) {
  44885. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  44886. this.currentStencilFail = stencilFail;
  44887. this.currentStencilZFail = stencilZFail;
  44888. this.currentStencilZPass = stencilZPass;
  44889. }
  44890. }
  44891. /**
  44892. * Configures the WebGL state for the given material.
  44893. *
  44894. * @param {Material} material - The material to configure the state for.
  44895. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  44896. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  44897. */
  44898. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  44899. const { gl } = this;
  44900. material.side === DoubleSide
  44901. ? this.disable( gl.CULL_FACE )
  44902. : this.enable( gl.CULL_FACE );
  44903. let flipSided = ( material.side === BackSide );
  44904. if ( frontFaceCW ) flipSided = ! flipSided;
  44905. this.setFlipSided( flipSided );
  44906. ( material.blending === NormalBlending && material.transparent === false )
  44907. ? this.setBlending( NoBlending )
  44908. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  44909. this.setDepthFunc( material.depthFunc );
  44910. this.setDepthTest( material.depthTest );
  44911. this.setDepthMask( material.depthWrite );
  44912. this.setColorMask( material.colorWrite );
  44913. const stencilWrite = material.stencilWrite;
  44914. this.setStencilTest( stencilWrite );
  44915. if ( stencilWrite ) {
  44916. this.setStencilMask( material.stencilWriteMask );
  44917. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  44918. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  44919. }
  44920. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  44921. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  44922. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  44923. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  44924. if ( hardwareClippingPlanes > 0 ) {
  44925. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  44926. const CLIP_DISTANCE0_WEBGL = 0x3000;
  44927. for ( let i = 0; i < 8; i ++ ) {
  44928. if ( i < hardwareClippingPlanes ) {
  44929. this.enable( CLIP_DISTANCE0_WEBGL + i );
  44930. } else {
  44931. this.disable( CLIP_DISTANCE0_WEBGL + i );
  44932. }
  44933. }
  44934. }
  44935. }
  44936. }
  44937. /**
  44938. * Specifies the polygon offset.
  44939. *
  44940. * This method caches the state so `gl.polygonOffset()` is only
  44941. * called when necessary.
  44942. *
  44943. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  44944. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  44945. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  44946. */
  44947. setPolygonOffset( polygonOffset, factor, units ) {
  44948. const { gl } = this;
  44949. if ( polygonOffset ) {
  44950. this.enable( gl.POLYGON_OFFSET_FILL );
  44951. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  44952. gl.polygonOffset( factor, units );
  44953. this.currentPolygonOffsetFactor = factor;
  44954. this.currentPolygonOffsetUnits = units;
  44955. }
  44956. } else {
  44957. this.disable( gl.POLYGON_OFFSET_FILL );
  44958. }
  44959. }
  44960. /**
  44961. * Defines the usage of the given WebGL program.
  44962. *
  44963. * This method caches the state so `gl.useProgram()` is only
  44964. * called when necessary.
  44965. *
  44966. * @param {WebGLProgram} program - The WebGL program to use.
  44967. * @return {boolean} Whether a program change has been executed or not.
  44968. */
  44969. useProgram( program ) {
  44970. if ( this.currentProgram !== program ) {
  44971. this.gl.useProgram( program );
  44972. this.currentProgram = program;
  44973. return true;
  44974. }
  44975. return false;
  44976. }
  44977. /**
  44978. * Sets the vertex state by binding the given VAO and element buffer.
  44979. *
  44980. * @param {WebGLVertexArrayObject} vao - The VAO.
  44981. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  44982. * @return {boolean} Whether a vertex state has been changed or not.
  44983. */
  44984. setVertexState( vao, indexBuffer = null ) {
  44985. const gl = this.gl;
  44986. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  44987. gl.bindVertexArray( vao );
  44988. if ( indexBuffer !== null ) {
  44989. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  44990. }
  44991. this.currentVAO = vao;
  44992. this.currentIndex = indexBuffer;
  44993. return true;
  44994. }
  44995. return false;
  44996. }
  44997. /**
  44998. * Resets the vertex array state by resetting the VAO and element buffer.
  44999. */
  45000. resetVertexState() {
  45001. const gl = this.gl;
  45002. gl.bindVertexArray( null );
  45003. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  45004. this.currentVAO = null;
  45005. this.currentIndex = null;
  45006. }
  45007. // framebuffer
  45008. /**
  45009. * Binds the given framebuffer.
  45010. *
  45011. * This method caches the state so `gl.bindFramebuffer()` is only
  45012. * called when necessary.
  45013. *
  45014. * @param {number} target - The binding point (target).
  45015. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  45016. * @return {boolean} Whether a bind has been executed or not.
  45017. */
  45018. bindFramebuffer( target, framebuffer ) {
  45019. const { gl, currentBoundFramebuffers } = this;
  45020. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  45021. gl.bindFramebuffer( target, framebuffer );
  45022. currentBoundFramebuffers[ target ] = framebuffer;
  45023. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  45024. if ( target === gl.DRAW_FRAMEBUFFER ) {
  45025. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  45026. }
  45027. if ( target === gl.FRAMEBUFFER ) {
  45028. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  45029. }
  45030. return true;
  45031. }
  45032. return false;
  45033. }
  45034. /**
  45035. * Defines draw buffers to which fragment colors are written into.
  45036. * Configures the MRT setup of custom framebuffers.
  45037. *
  45038. * This method caches the state so `gl.drawBuffers()` is only
  45039. * called when necessary.
  45040. *
  45041. * @param {RenderContext} renderContext - The render context.
  45042. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  45043. */
  45044. drawBuffers( renderContext, framebuffer ) {
  45045. const { gl } = this;
  45046. let drawBuffers = [];
  45047. let needsUpdate = false;
  45048. if ( renderContext.textures !== null ) {
  45049. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  45050. if ( drawBuffers === undefined ) {
  45051. drawBuffers = [];
  45052. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  45053. }
  45054. const textures = renderContext.textures;
  45055. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  45056. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  45057. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  45058. }
  45059. drawBuffers.length = textures.length;
  45060. needsUpdate = true;
  45061. }
  45062. } else {
  45063. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  45064. drawBuffers[ 0 ] = gl.BACK;
  45065. needsUpdate = true;
  45066. }
  45067. }
  45068. if ( needsUpdate ) {
  45069. gl.drawBuffers( drawBuffers );
  45070. }
  45071. }
  45072. // texture
  45073. /**
  45074. * Makes the given texture unit active.
  45075. *
  45076. * This method caches the state so `gl.activeTexture()` is only
  45077. * called when necessary.
  45078. *
  45079. * @param {number} webglSlot - The texture unit to make active.
  45080. */
  45081. activeTexture( webglSlot ) {
  45082. const { gl, currentTextureSlot, maxTextures } = this;
  45083. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  45084. if ( currentTextureSlot !== webglSlot ) {
  45085. gl.activeTexture( webglSlot );
  45086. this.currentTextureSlot = webglSlot;
  45087. }
  45088. }
  45089. /**
  45090. * Binds the given WebGL texture to a target.
  45091. *
  45092. * This method caches the state so `gl.bindTexture()` is only
  45093. * called when necessary.
  45094. *
  45095. * @param {number} webglType - The binding point (target).
  45096. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  45097. * @param {number} webglSlot - The texture.
  45098. */
  45099. bindTexture( webglType, webglTexture, webglSlot ) {
  45100. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  45101. if ( webglSlot === undefined ) {
  45102. if ( currentTextureSlot === null ) {
  45103. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  45104. } else {
  45105. webglSlot = currentTextureSlot;
  45106. }
  45107. }
  45108. let boundTexture = currentBoundTextures[ webglSlot ];
  45109. if ( boundTexture === undefined ) {
  45110. boundTexture = { type: undefined, texture: undefined };
  45111. currentBoundTextures[ webglSlot ] = boundTexture;
  45112. }
  45113. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  45114. if ( currentTextureSlot !== webglSlot ) {
  45115. gl.activeTexture( webglSlot );
  45116. this.currentTextureSlot = webglSlot;
  45117. }
  45118. gl.bindTexture( webglType, webglTexture );
  45119. boundTexture.type = webglType;
  45120. boundTexture.texture = webglTexture;
  45121. }
  45122. }
  45123. /**
  45124. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  45125. *
  45126. * This method caches the state so `gl.bindBufferBase()` is only
  45127. * called when necessary.
  45128. *
  45129. * @param {number} target - The target for the bind operation.
  45130. * @param {number} index - The index of the target.
  45131. * @param {WebGLBuffer} buffer - The WebGL buffer.
  45132. * @return {boolean} Whether a bind has been executed or not.
  45133. */
  45134. bindBufferBase( target, index, buffer ) {
  45135. const { gl } = this;
  45136. const key = `${target}-${index}`;
  45137. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  45138. gl.bindBufferBase( target, index, buffer );
  45139. this.currentBoundBufferBases[ key ] = buffer;
  45140. return true;
  45141. }
  45142. return false;
  45143. }
  45144. /**
  45145. * Unbinds the current bound texture.
  45146. *
  45147. * This method caches the state so `gl.bindTexture()` is only
  45148. * called when necessary.
  45149. */
  45150. unbindTexture() {
  45151. const { gl, currentTextureSlot, currentBoundTextures } = this;
  45152. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  45153. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  45154. gl.bindTexture( boundTexture.type, null );
  45155. boundTexture.type = undefined;
  45156. boundTexture.texture = undefined;
  45157. }
  45158. }
  45159. }
  45160. /**
  45161. * A WebGL 2 backend utility module with common helpers.
  45162. *
  45163. * @private
  45164. */
  45165. class WebGLUtils {
  45166. /**
  45167. * Constructs a new utility object.
  45168. *
  45169. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45170. */
  45171. constructor( backend ) {
  45172. /**
  45173. * A reference to the WebGL 2 backend.
  45174. *
  45175. * @type {WebGLBackend}
  45176. */
  45177. this.backend = backend;
  45178. /**
  45179. * A reference to the rendering context.
  45180. *
  45181. * @type {WebGL2RenderingContext}
  45182. */
  45183. this.gl = this.backend.gl;
  45184. /**
  45185. * A reference to a backend module holding extension-related
  45186. * utility functions.
  45187. *
  45188. * @type {WebGLExtensions}
  45189. */
  45190. this.extensions = backend.extensions;
  45191. }
  45192. /**
  45193. * Converts the given three.js constant into a WebGL constant.
  45194. * The method currently supports the conversion of texture formats
  45195. * and types.
  45196. *
  45197. * @param {number} p - The three.js constant.
  45198. * @param {string} [colorSpace=NoColorSpace] - The color space.
  45199. * @return {?number} The corresponding WebGL constant.
  45200. */
  45201. convert( p, colorSpace = NoColorSpace ) {
  45202. const { gl, extensions } = this;
  45203. let extension;
  45204. const transfer = ColorManagement.getTransfer( colorSpace );
  45205. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  45206. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  45207. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  45208. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  45209. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  45210. if ( p === ByteType ) return gl.BYTE;
  45211. if ( p === ShortType ) return gl.SHORT;
  45212. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  45213. if ( p === IntType ) return gl.INT;
  45214. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  45215. if ( p === FloatType ) return gl.FLOAT;
  45216. if ( p === HalfFloatType ) {
  45217. return gl.HALF_FLOAT;
  45218. }
  45219. if ( p === AlphaFormat ) return gl.ALPHA;
  45220. if ( p === RGBFormat ) return gl.RGB;
  45221. if ( p === RGBAFormat ) return gl.RGBA;
  45222. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  45223. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  45224. // WebGL2 formats.
  45225. if ( p === RedFormat ) return gl.RED;
  45226. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  45227. if ( p === RGFormat ) return gl.RG;
  45228. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  45229. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  45230. // S3TC
  45231. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  45232. if ( transfer === SRGBTransfer ) {
  45233. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  45234. if ( extension !== null ) {
  45235. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  45236. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  45237. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  45238. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  45239. } else {
  45240. return null;
  45241. }
  45242. } else {
  45243. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  45244. if ( extension !== null ) {
  45245. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  45246. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45247. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45248. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45249. } else {
  45250. return null;
  45251. }
  45252. }
  45253. }
  45254. // PVRTC
  45255. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  45256. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  45257. if ( extension !== null ) {
  45258. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  45259. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  45260. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  45261. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  45262. } else {
  45263. return null;
  45264. }
  45265. }
  45266. // ETC
  45267. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  45268. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  45269. if ( extension !== null ) {
  45270. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  45271. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  45272. } else {
  45273. return null;
  45274. }
  45275. }
  45276. // ASTC
  45277. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  45278. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  45279. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  45280. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  45281. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  45282. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  45283. if ( extension !== null ) {
  45284. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  45285. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  45286. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  45287. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  45288. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  45289. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  45290. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  45291. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  45292. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  45293. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  45294. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  45295. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  45296. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  45297. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  45298. } else {
  45299. return null;
  45300. }
  45301. }
  45302. // BPTC
  45303. if ( p === RGBA_BPTC_Format ) {
  45304. extension = extensions.get( 'EXT_texture_compression_bptc' );
  45305. if ( extension !== null ) {
  45306. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  45307. } else {
  45308. return null;
  45309. }
  45310. }
  45311. // RGTC
  45312. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  45313. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  45314. if ( extension !== null ) {
  45315. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  45316. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  45317. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  45318. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  45319. } else {
  45320. return null;
  45321. }
  45322. }
  45323. //
  45324. if ( p === UnsignedInt248Type ) {
  45325. return gl.UNSIGNED_INT_24_8;
  45326. }
  45327. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  45328. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  45329. }
  45330. /**
  45331. * This method can be used to synchronize the CPU with the GPU by waiting until
  45332. * ongoing GPU commands have been completed.
  45333. *
  45334. * @private
  45335. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  45336. */
  45337. _clientWaitAsync() {
  45338. const { gl } = this;
  45339. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  45340. gl.flush();
  45341. return new Promise( ( resolve, reject ) => {
  45342. function test() {
  45343. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  45344. if ( res === gl.WAIT_FAILED ) {
  45345. gl.deleteSync( sync );
  45346. reject();
  45347. return;
  45348. }
  45349. if ( res === gl.TIMEOUT_EXPIRED ) {
  45350. requestAnimationFrame( test );
  45351. return;
  45352. }
  45353. gl.deleteSync( sync );
  45354. resolve();
  45355. }
  45356. test();
  45357. } );
  45358. }
  45359. }
  45360. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  45361. /**
  45362. * A WebGL 2 backend utility module for managing textures.
  45363. *
  45364. * @private
  45365. */
  45366. class WebGLTextureUtils {
  45367. /**
  45368. * Constructs a new utility object.
  45369. *
  45370. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45371. */
  45372. constructor( backend ) {
  45373. /**
  45374. * A reference to the WebGL 2 backend.
  45375. *
  45376. * @type {WebGLBackend}
  45377. */
  45378. this.backend = backend;
  45379. /**
  45380. * A reference to the rendering context.
  45381. *
  45382. * @type {WebGL2RenderingContext}
  45383. */
  45384. this.gl = backend.gl;
  45385. /**
  45386. * A reference to a backend module holding extension-related
  45387. * utility functions.
  45388. *
  45389. * @type {WebGLExtensions}
  45390. */
  45391. this.extensions = backend.extensions;
  45392. /**
  45393. * A dictionary for managing default textures. The key
  45394. * is the binding point (target), the value the WEbGL texture object.
  45395. *
  45396. * @type {Object<GLenum,WebGLTexture>}
  45397. */
  45398. this.defaultTextures = {};
  45399. /**
  45400. * A scratch framebuffer used for attaching the source texture in
  45401. * {@link copyTextureToTexture}.
  45402. *
  45403. * @private
  45404. * @type {?WebGLFramebuffer}
  45405. */
  45406. this._srcFramebuffer = null;
  45407. /**
  45408. * A scratch framebuffer used for attaching the destination texture in
  45409. * {@link copyTextureToTexture}.
  45410. *
  45411. * @private
  45412. * @type {?WebGLFramebuffer}
  45413. */
  45414. this._dstFramebuffer = null;
  45415. if ( initialized === false ) {
  45416. this._init();
  45417. initialized = true;
  45418. }
  45419. }
  45420. /**
  45421. * Inits the state of the utility.
  45422. *
  45423. * @private
  45424. */
  45425. _init() {
  45426. const gl = this.gl;
  45427. // Store only WebGL constants here.
  45428. wrappingToGL = {
  45429. [ RepeatWrapping ]: gl.REPEAT,
  45430. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  45431. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  45432. };
  45433. filterToGL = {
  45434. [ NearestFilter ]: gl.NEAREST,
  45435. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  45436. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  45437. [ LinearFilter ]: gl.LINEAR,
  45438. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  45439. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  45440. };
  45441. compareToGL = {
  45442. [ NeverCompare ]: gl.NEVER,
  45443. [ AlwaysCompare ]: gl.ALWAYS,
  45444. [ LessCompare ]: gl.LESS,
  45445. [ LessEqualCompare ]: gl.LEQUAL,
  45446. [ EqualCompare ]: gl.EQUAL,
  45447. [ GreaterEqualCompare ]: gl.GEQUAL,
  45448. [ GreaterCompare ]: gl.GREATER,
  45449. [ NotEqualCompare ]: gl.NOTEQUAL
  45450. };
  45451. }
  45452. /**
  45453. * Returns the native texture type for the given texture.
  45454. *
  45455. * @param {Texture} texture - The texture.
  45456. * @return {GLenum} The native texture type.
  45457. */
  45458. getGLTextureType( texture ) {
  45459. const { gl } = this;
  45460. let glTextureType;
  45461. if ( texture.isCubeTexture === true ) {
  45462. glTextureType = gl.TEXTURE_CUBE_MAP;
  45463. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  45464. glTextureType = gl.TEXTURE_2D_ARRAY;
  45465. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  45466. glTextureType = gl.TEXTURE_3D;
  45467. } else {
  45468. glTextureType = gl.TEXTURE_2D;
  45469. }
  45470. return glTextureType;
  45471. }
  45472. /**
  45473. * Returns the native texture type for the given texture.
  45474. *
  45475. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  45476. * @param {GLenum} glFormat - The WebGL format.
  45477. * @param {GLenum} glType - The WebGL type.
  45478. * @param {string} colorSpace - The texture's color space.
  45479. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  45480. * @return {GLenum} The internal format.
  45481. */
  45482. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  45483. const { gl, extensions } = this;
  45484. if ( internalFormatName !== null ) {
  45485. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  45486. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  45487. }
  45488. let internalFormat = glFormat;
  45489. if ( glFormat === gl.RED ) {
  45490. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  45491. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  45492. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  45493. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  45494. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  45495. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  45496. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  45497. if ( glType === gl.INT ) internalFormat = gl.R32I;
  45498. }
  45499. if ( glFormat === gl.RED_INTEGER ) {
  45500. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  45501. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  45502. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  45503. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  45504. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  45505. if ( glType === gl.INT ) internalFormat = gl.R32I;
  45506. }
  45507. if ( glFormat === gl.RG ) {
  45508. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  45509. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  45510. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  45511. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  45512. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  45513. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  45514. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  45515. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  45516. }
  45517. if ( glFormat === gl.RG_INTEGER ) {
  45518. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  45519. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  45520. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  45521. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  45522. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  45523. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  45524. }
  45525. if ( glFormat === gl.RGB ) {
  45526. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  45527. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  45528. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  45529. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  45530. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  45531. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  45532. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  45533. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  45534. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  45535. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  45536. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  45537. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  45538. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  45539. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  45540. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  45541. }
  45542. if ( glFormat === gl.RGB_INTEGER ) {
  45543. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  45544. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  45545. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  45546. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  45547. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  45548. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  45549. }
  45550. if ( glFormat === gl.RGBA ) {
  45551. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  45552. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  45553. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  45554. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  45555. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  45556. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  45557. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  45558. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  45559. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  45560. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  45561. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  45562. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  45563. }
  45564. if ( glFormat === gl.RGBA_INTEGER ) {
  45565. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  45566. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  45567. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  45568. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  45569. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  45570. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  45571. }
  45572. if ( glFormat === gl.DEPTH_COMPONENT ) {
  45573. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  45574. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  45575. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  45576. }
  45577. if ( glFormat === gl.DEPTH_STENCIL ) {
  45578. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  45579. }
  45580. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  45581. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  45582. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  45583. extensions.get( 'EXT_color_buffer_float' );
  45584. }
  45585. return internalFormat;
  45586. }
  45587. /**
  45588. * Sets the texture parameters for the given texture.
  45589. *
  45590. * @param {GLenum} textureType - The texture type.
  45591. * @param {Texture} texture - The texture.
  45592. */
  45593. setTextureParameters( textureType, texture ) {
  45594. const { gl, extensions, backend } = this;
  45595. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  45596. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  45597. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  45598. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  45599. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  45600. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  45601. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  45602. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  45603. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  45604. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  45605. // WebGL 2 does not support wrapping for depth 2D array textures
  45606. if ( ! texture.isArrayTexture ) {
  45607. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  45608. }
  45609. }
  45610. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  45611. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  45612. // follow WebGPU backend mapping for texture filtering
  45613. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  45614. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  45615. if ( texture.compareFunction ) {
  45616. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  45617. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  45618. }
  45619. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  45620. if ( texture.magFilter === NearestFilter ) return;
  45621. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  45622. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  45623. if ( texture.anisotropy > 1 ) {
  45624. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  45625. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  45626. }
  45627. }
  45628. }
  45629. /**
  45630. * Creates a default texture for the given texture that can be used
  45631. * as a placeholder until the actual texture is ready for usage.
  45632. *
  45633. * @param {Texture} texture - The texture to create a default texture for.
  45634. */
  45635. createDefaultTexture( texture ) {
  45636. const { gl, backend, defaultTextures } = this;
  45637. const glTextureType = this.getGLTextureType( texture );
  45638. let textureGPU = defaultTextures[ glTextureType ];
  45639. if ( textureGPU === undefined ) {
  45640. textureGPU = gl.createTexture();
  45641. backend.state.bindTexture( glTextureType, textureGPU );
  45642. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  45643. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  45644. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  45645. defaultTextures[ glTextureType ] = textureGPU;
  45646. }
  45647. backend.set( texture, {
  45648. textureGPU,
  45649. glTextureType
  45650. } );
  45651. }
  45652. /**
  45653. * Defines a texture on the GPU for the given texture object.
  45654. *
  45655. * @param {Texture} texture - The texture.
  45656. * @param {Object} [options={}] - Optional configuration parameter.
  45657. * @return {undefined}
  45658. */
  45659. createTexture( texture, options ) {
  45660. const { gl, backend } = this;
  45661. const { levels, width, height, depth } = options;
  45662. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  45663. const glType = backend.utils.convert( texture.type );
  45664. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  45665. const textureGPU = gl.createTexture();
  45666. const glTextureType = this.getGLTextureType( texture );
  45667. backend.state.bindTexture( glTextureType, textureGPU );
  45668. this.setTextureParameters( glTextureType, texture );
  45669. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  45670. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  45671. } else if ( texture.isData3DTexture ) {
  45672. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  45673. } else if ( ! texture.isVideoTexture ) {
  45674. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  45675. }
  45676. backend.set( texture, {
  45677. textureGPU,
  45678. glTextureType,
  45679. glFormat,
  45680. glType,
  45681. glInternalFormat
  45682. } );
  45683. }
  45684. /**
  45685. * Uploads texture buffer data to the GPU memory.
  45686. *
  45687. * @param {WebGLBuffer} buffer - The buffer data.
  45688. * @param {Texture} texture - The texture,
  45689. */
  45690. copyBufferToTexture( buffer, texture ) {
  45691. const { gl, backend } = this;
  45692. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  45693. const { width, height } = texture.source.data;
  45694. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  45695. backend.state.bindTexture( glTextureType, textureGPU );
  45696. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  45697. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  45698. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  45699. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  45700. backend.state.unbindTexture();
  45701. // debug
  45702. // const framebuffer = gl.createFramebuffer();
  45703. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  45704. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  45705. // const readout = new Float32Array( width * height * 4 );
  45706. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  45707. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  45708. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  45709. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  45710. // log( readout );
  45711. }
  45712. /**
  45713. * Uploads the updated texture data to the GPU.
  45714. *
  45715. * @param {Texture} texture - The texture.
  45716. * @param {Object} [options={}] - Optional configuration parameter.
  45717. */
  45718. updateTexture( texture, options ) {
  45719. const { gl } = this;
  45720. const { width, height } = options;
  45721. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  45722. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  45723. return;
  45724. this.backend.state.bindTexture( glTextureType, textureGPU );
  45725. this.setTextureParameters( glTextureType, texture );
  45726. if ( texture.isCompressedTexture ) {
  45727. const mipmaps = texture.mipmaps;
  45728. const image = options.image;
  45729. for ( let i = 0; i < mipmaps.length; i ++ ) {
  45730. const mipmap = mipmaps[ i ];
  45731. if ( texture.isCompressedArrayTexture ) {
  45732. if ( texture.format !== gl.RGBA ) {
  45733. if ( glFormat !== null ) {
  45734. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  45735. } else {
  45736. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  45737. }
  45738. } else {
  45739. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  45740. }
  45741. } else {
  45742. if ( glFormat !== null ) {
  45743. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  45744. } else {
  45745. warn( 'WebGLBackend: Unsupported compressed texture format' );
  45746. }
  45747. }
  45748. }
  45749. } else if ( texture.isCubeTexture ) {
  45750. const images = options.images;
  45751. const mipmaps = texture.mipmaps;
  45752. for ( let i = 0; i < 6; i ++ ) {
  45753. const image = getImage( images[ i ] );
  45754. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  45755. for ( let j = 0; j < mipmaps.length; j ++ ) {
  45756. const mipmap = mipmaps[ j ];
  45757. const image = getImage( mipmap.images[ i ] );
  45758. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  45759. }
  45760. }
  45761. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  45762. const image = options.image;
  45763. if ( texture.layerUpdates.size > 0 ) {
  45764. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  45765. for ( const layerIndex of texture.layerUpdates ) {
  45766. const layerData = image.data.subarray(
  45767. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  45768. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  45769. );
  45770. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  45771. }
  45772. texture.clearLayerUpdates();
  45773. } else {
  45774. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  45775. }
  45776. } else if ( texture.isData3DTexture ) {
  45777. const image = options.image;
  45778. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  45779. } else if ( texture.isVideoTexture ) {
  45780. texture.update();
  45781. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  45782. } else {
  45783. const mipmaps = texture.mipmaps;
  45784. if ( mipmaps.length > 0 ) {
  45785. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  45786. const mipmap = mipmaps[ i ];
  45787. const image = getImage( mipmap );
  45788. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  45789. }
  45790. } else {
  45791. const image = getImage( options.image );
  45792. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  45793. }
  45794. }
  45795. }
  45796. /**
  45797. * Generates mipmaps for the given texture.
  45798. *
  45799. * @param {Texture} texture - The texture.
  45800. */
  45801. generateMipmaps( texture ) {
  45802. const { gl, backend } = this;
  45803. const { textureGPU, glTextureType } = backend.get( texture );
  45804. backend.state.bindTexture( glTextureType, textureGPU );
  45805. gl.generateMipmap( glTextureType );
  45806. }
  45807. /**
  45808. * Deallocates the render buffers of the given render target.
  45809. *
  45810. * @param {RenderTarget} renderTarget - The render target.
  45811. */
  45812. deallocateRenderBuffers( renderTarget ) {
  45813. const { gl, backend } = this;
  45814. // remove framebuffer reference
  45815. if ( renderTarget ) {
  45816. const renderContextData = backend.get( renderTarget );
  45817. renderContextData.renderBufferStorageSetup = undefined;
  45818. if ( renderContextData.framebuffers ) {
  45819. for ( const cacheKey in renderContextData.framebuffers ) {
  45820. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  45821. }
  45822. delete renderContextData.framebuffers;
  45823. }
  45824. if ( renderContextData.depthRenderbuffer ) {
  45825. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  45826. delete renderContextData.depthRenderbuffer;
  45827. }
  45828. if ( renderContextData.stencilRenderbuffer ) {
  45829. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  45830. delete renderContextData.stencilRenderbuffer;
  45831. }
  45832. if ( renderContextData.msaaFrameBuffer ) {
  45833. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  45834. delete renderContextData.msaaFrameBuffer;
  45835. }
  45836. if ( renderContextData.msaaRenderbuffers ) {
  45837. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  45838. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  45839. }
  45840. delete renderContextData.msaaRenderbuffers;
  45841. }
  45842. }
  45843. }
  45844. /**
  45845. * Destroys the GPU data for the given texture object.
  45846. *
  45847. * @param {Texture} texture - The texture.
  45848. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  45849. */
  45850. destroyTexture( texture, isDefaultTexture = false ) {
  45851. const { gl, backend } = this;
  45852. const { textureGPU, renderTarget } = backend.get( texture );
  45853. this.deallocateRenderBuffers( renderTarget );
  45854. if ( isDefaultTexture === false ) {
  45855. gl.deleteTexture( textureGPU );
  45856. }
  45857. backend.delete( texture );
  45858. }
  45859. /**
  45860. * Copies data of the given source texture to the given destination texture.
  45861. *
  45862. * @param {Texture} srcTexture - The source texture.
  45863. * @param {Texture} dstTexture - The destination texture.
  45864. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  45865. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  45866. * @param {number} [srcLevel=0] - The source mip level to copy from.
  45867. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  45868. */
  45869. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  45870. const { gl, backend } = this;
  45871. const { state } = this.backend;
  45872. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  45873. state.bindTexture( glTextureType, dstTextureGPU );
  45874. // gather the necessary dimensions to copy
  45875. let width, height, depth, minX, minY, minZ;
  45876. let dstX, dstY, dstZ;
  45877. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  45878. if ( srcRegion !== null ) {
  45879. width = srcRegion.max.x - srcRegion.min.x;
  45880. height = srcRegion.max.y - srcRegion.min.y;
  45881. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  45882. minX = srcRegion.min.x;
  45883. minY = srcRegion.min.y;
  45884. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  45885. } else {
  45886. const levelScale = Math.pow( 2, - srcLevel );
  45887. width = Math.floor( image.width * levelScale );
  45888. height = Math.floor( image.height * levelScale );
  45889. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  45890. depth = image.depth;
  45891. } else if ( srcTexture.isData3DTexture ) {
  45892. depth = Math.floor( image.depth * levelScale );
  45893. } else {
  45894. depth = 1;
  45895. }
  45896. minX = 0;
  45897. minY = 0;
  45898. minZ = 0;
  45899. }
  45900. if ( dstPosition !== null ) {
  45901. dstX = dstPosition.x;
  45902. dstY = dstPosition.y;
  45903. dstZ = dstPosition.z;
  45904. } else {
  45905. dstX = 0;
  45906. dstY = 0;
  45907. dstZ = 0;
  45908. }
  45909. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  45910. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  45911. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  45912. // used for copying data from cpu
  45913. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  45914. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  45915. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  45916. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  45917. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  45918. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  45919. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  45920. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  45921. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  45922. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  45923. // set up the src texture
  45924. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  45925. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  45926. if ( srcTexture.isDepthTexture ) {
  45927. const srcTextureData = backend.get( srcTexture );
  45928. const dstTextureData = backend.get( dstTexture );
  45929. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  45930. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  45931. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  45932. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  45933. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  45934. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  45935. for ( let i = 0; i < depth; i ++ ) {
  45936. // if the source or destination are a 3d target then a layer needs to be bound
  45937. if ( isSrc3D ) {
  45938. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  45939. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  45940. }
  45941. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  45942. }
  45943. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  45944. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  45945. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  45946. // get the appropriate frame buffers
  45947. const srcTextureData = backend.get( srcTexture );
  45948. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  45949. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  45950. // bind the frame buffer targets
  45951. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  45952. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  45953. for ( let i = 0; i < depth; i ++ ) {
  45954. // assign the correct layers and mip maps to the frame buffers
  45955. if ( isSrc3D ) {
  45956. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  45957. } else {
  45958. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  45959. }
  45960. if ( isDst3D ) {
  45961. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  45962. } else {
  45963. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  45964. }
  45965. // copy the data using the fastest function that can achieve the copy
  45966. if ( srcLevel !== 0 ) {
  45967. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  45968. } else if ( isDst3D ) {
  45969. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  45970. } else {
  45971. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  45972. }
  45973. }
  45974. // unbind read, draw buffers
  45975. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  45976. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  45977. } else {
  45978. if ( isDst3D ) {
  45979. // copy data into the 3d texture
  45980. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  45981. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  45982. } else if ( dstTexture.isCompressedArrayTexture ) {
  45983. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  45984. } else {
  45985. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  45986. }
  45987. } else {
  45988. // copy data into the 2d texture
  45989. if ( srcTexture.isDataTexture ) {
  45990. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  45991. } else if ( srcTexture.isCompressedTexture ) {
  45992. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  45993. } else {
  45994. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  45995. }
  45996. }
  45997. }
  45998. // reset values
  45999. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  46000. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  46001. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  46002. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  46003. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  46004. // Generate mipmaps only when copying level 0
  46005. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  46006. gl.generateMipmap( glTextureType );
  46007. }
  46008. state.unbindTexture();
  46009. }
  46010. /**
  46011. * Copies the current bound framebuffer to the given texture.
  46012. *
  46013. * @param {Texture} texture - The destination texture.
  46014. * @param {RenderContext} renderContext - The render context.
  46015. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  46016. */
  46017. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  46018. const { gl } = this;
  46019. const { state } = this.backend;
  46020. const { textureGPU } = this.backend.get( texture );
  46021. const { x, y, z: width, w: height } = rectangle;
  46022. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  46023. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  46024. if ( requireDrawFrameBuffer ) {
  46025. const partial = ( x !== 0 || y !== 0 );
  46026. let mask;
  46027. let attachment;
  46028. if ( texture.isDepthTexture === true ) {
  46029. mask = gl.DEPTH_BUFFER_BIT;
  46030. attachment = gl.DEPTH_ATTACHMENT;
  46031. if ( renderContext.stencil ) {
  46032. mask |= gl.STENCIL_BUFFER_BIT;
  46033. }
  46034. } else {
  46035. mask = gl.COLOR_BUFFER_BIT;
  46036. attachment = gl.COLOR_ATTACHMENT0;
  46037. }
  46038. if ( partial ) {
  46039. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  46040. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  46041. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  46042. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  46043. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  46044. const flippedY = srcHeight - y - height;
  46045. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  46046. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  46047. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  46048. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  46049. state.unbindTexture();
  46050. } else {
  46051. const fb = gl.createFramebuffer();
  46052. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  46053. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  46054. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  46055. gl.deleteFramebuffer( fb );
  46056. }
  46057. } else {
  46058. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  46059. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  46060. state.unbindTexture();
  46061. }
  46062. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  46063. this.backend._setFramebuffer( renderContext );
  46064. }
  46065. /**
  46066. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  46067. *
  46068. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  46069. * @param {RenderContext} renderContext - The render context.
  46070. * @param {number} samples - The MSAA sample count.
  46071. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  46072. */
  46073. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  46074. const { gl } = this;
  46075. const renderTarget = renderContext.renderTarget;
  46076. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  46077. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  46078. if ( depthBuffer && ! stencilBuffer ) {
  46079. let glInternalFormat = gl.DEPTH_COMPONENT24;
  46080. if ( useMultisampledRTT === true ) {
  46081. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  46082. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  46083. } else if ( samples > 0 ) {
  46084. if ( depthTexture && depthTexture.isDepthTexture ) {
  46085. if ( depthTexture.type === gl.FLOAT ) {
  46086. glInternalFormat = gl.DEPTH_COMPONENT32F;
  46087. }
  46088. }
  46089. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  46090. } else {
  46091. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  46092. }
  46093. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  46094. } else if ( depthBuffer && stencilBuffer ) {
  46095. if ( samples > 0 ) {
  46096. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  46097. } else {
  46098. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  46099. }
  46100. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  46101. }
  46102. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  46103. }
  46104. /**
  46105. * Returns texture data as a typed array.
  46106. *
  46107. * @async
  46108. * @param {Texture} texture - The texture to copy.
  46109. * @param {number} x - The x coordinate of the copy origin.
  46110. * @param {number} y - The y coordinate of the copy origin.
  46111. * @param {number} width - The width of the copy.
  46112. * @param {number} height - The height of the copy.
  46113. * @param {number} faceIndex - The face index.
  46114. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46115. */
  46116. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  46117. const { backend, gl } = this;
  46118. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  46119. const fb = gl.createFramebuffer();
  46120. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  46121. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  46122. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  46123. const typedArrayType = this._getTypedArrayType( glType );
  46124. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  46125. const elementCount = width * height;
  46126. const byteLength = elementCount * bytesPerTexel;
  46127. const buffer = gl.createBuffer();
  46128. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  46129. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  46130. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  46131. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  46132. await backend.utils._clientWaitAsync();
  46133. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  46134. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  46135. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  46136. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  46137. gl.deleteFramebuffer( fb );
  46138. return dstBuffer;
  46139. }
  46140. /**
  46141. * Returns the corresponding typed array type for the given WebGL data type.
  46142. *
  46143. * @private
  46144. * @param {GLenum} glType - The WebGL data type.
  46145. * @return {TypedArray.constructor} The typed array type.
  46146. */
  46147. _getTypedArrayType( glType ) {
  46148. const { gl } = this;
  46149. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  46150. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  46151. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  46152. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  46153. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  46154. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  46155. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  46156. if ( glType === gl.FLOAT ) return Float32Array;
  46157. throw new Error( `Unsupported WebGL type: ${glType}` );
  46158. }
  46159. /**
  46160. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  46161. *
  46162. * @private
  46163. * @param {GLenum} glType - The WebGL data type.
  46164. * @param {GLenum} glFormat - The WebGL texture format.
  46165. * @return {number} The bytes-per-texel.
  46166. */
  46167. _getBytesPerTexel( glType, glFormat ) {
  46168. const { gl } = this;
  46169. let bytesPerComponent = 0;
  46170. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  46171. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  46172. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  46173. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  46174. glType === gl.UNSIGNED_SHORT ||
  46175. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  46176. if ( glType === gl.UNSIGNED_INT ||
  46177. glType === gl.FLOAT ) bytesPerComponent = 4;
  46178. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  46179. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  46180. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  46181. }
  46182. /**
  46183. * Frees the internal resources.
  46184. */
  46185. dispose() {
  46186. const { gl } = this;
  46187. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  46188. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  46189. }
  46190. }
  46191. function getImage( source ) {
  46192. if ( source.isDataTexture ) {
  46193. return source.image.data;
  46194. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  46195. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  46196. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  46197. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  46198. return source;
  46199. }
  46200. return source.data;
  46201. }
  46202. /**
  46203. * A WebGL 2 backend utility module for managing extensions.
  46204. *
  46205. * @private
  46206. */
  46207. class WebGLExtensions {
  46208. /**
  46209. * Constructs a new utility object.
  46210. *
  46211. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46212. */
  46213. constructor( backend ) {
  46214. /**
  46215. * A reference to the WebGL 2 backend.
  46216. *
  46217. * @type {WebGLBackend}
  46218. */
  46219. this.backend = backend;
  46220. /**
  46221. * A reference to the rendering context.
  46222. *
  46223. * @type {WebGL2RenderingContext}
  46224. */
  46225. this.gl = this.backend.gl;
  46226. /**
  46227. * A list with all the supported WebGL extensions.
  46228. *
  46229. * @type {Array<string>}
  46230. */
  46231. this.availableExtensions = this.gl.getSupportedExtensions();
  46232. /**
  46233. * A dictionary with requested WebGL extensions.
  46234. * The key is the name of the extension, the value
  46235. * the requested extension object.
  46236. *
  46237. * @type {Object<string,Object>}
  46238. */
  46239. this.extensions = {};
  46240. }
  46241. /**
  46242. * Returns the extension object for the given extension name.
  46243. *
  46244. * @param {string} name - The extension name.
  46245. * @return {Object} The extension object.
  46246. */
  46247. get( name ) {
  46248. let extension = this.extensions[ name ];
  46249. if ( extension === undefined ) {
  46250. extension = this.gl.getExtension( name );
  46251. this.extensions[ name ] = extension;
  46252. }
  46253. return extension;
  46254. }
  46255. /**
  46256. * Returns `true` if the requested extension is available.
  46257. *
  46258. * @param {string} name - The extension name.
  46259. * @return {boolean} Whether the given extension is available or not.
  46260. */
  46261. has( name ) {
  46262. return this.availableExtensions.includes( name );
  46263. }
  46264. }
  46265. /**
  46266. * A WebGL 2 backend utility module for managing the device's capabilities.
  46267. *
  46268. * @private
  46269. */
  46270. class WebGLCapabilities {
  46271. /**
  46272. * Constructs a new utility object.
  46273. *
  46274. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46275. */
  46276. constructor( backend ) {
  46277. /**
  46278. * A reference to the WebGL 2 backend.
  46279. *
  46280. * @type {WebGLBackend}
  46281. */
  46282. this.backend = backend;
  46283. /**
  46284. * This value holds the cached max anisotropy value.
  46285. *
  46286. * @type {?number}
  46287. * @default null
  46288. */
  46289. this.maxAnisotropy = null;
  46290. }
  46291. /**
  46292. * Returns the maximum anisotropy texture filtering value. This value
  46293. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  46294. * WebGL extension.
  46295. *
  46296. * @return {number} The maximum anisotropy texture filtering value.
  46297. */
  46298. getMaxAnisotropy() {
  46299. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  46300. const gl = this.backend.gl;
  46301. const extensions = this.backend.extensions;
  46302. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  46303. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  46304. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  46305. } else {
  46306. this.maxAnisotropy = 0;
  46307. }
  46308. return this.maxAnisotropy;
  46309. }
  46310. }
  46311. const GLFeatureName = {
  46312. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  46313. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  46314. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  46315. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  46316. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  46317. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  46318. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  46319. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  46320. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  46321. 'OVR_multiview2': 'OVR_multiview2'
  46322. };
  46323. class WebGLBufferRenderer {
  46324. constructor( backend ) {
  46325. this.gl = backend.gl;
  46326. this.extensions = backend.extensions;
  46327. this.info = backend.renderer.info;
  46328. this.mode = null;
  46329. this.index = 0;
  46330. this.type = null;
  46331. this.object = null;
  46332. }
  46333. render( start, count ) {
  46334. const { gl, mode, object, type, info, index } = this;
  46335. if ( index !== 0 ) {
  46336. gl.drawElements( mode, count, type, start );
  46337. } else {
  46338. gl.drawArrays( mode, start, count );
  46339. }
  46340. info.update( object, count, 1 );
  46341. }
  46342. renderInstances( start, count, primcount ) {
  46343. const { gl, mode, type, index, object, info } = this;
  46344. if ( primcount === 0 ) return;
  46345. if ( index !== 0 ) {
  46346. gl.drawElementsInstanced( mode, count, type, start, primcount );
  46347. } else {
  46348. gl.drawArraysInstanced( mode, start, count, primcount );
  46349. }
  46350. info.update( object, count, primcount );
  46351. }
  46352. renderMultiDraw( starts, counts, drawCount ) {
  46353. const { extensions, mode, object, info } = this;
  46354. if ( drawCount === 0 ) return;
  46355. const extension = extensions.get( 'WEBGL_multi_draw' );
  46356. if ( extension === null ) {
  46357. for ( let i = 0; i < drawCount; i ++ ) {
  46358. this.render( starts[ i ], counts[ i ] );
  46359. }
  46360. } else {
  46361. if ( this.index !== 0 ) {
  46362. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  46363. } else {
  46364. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  46365. }
  46366. let elementCount = 0;
  46367. for ( let i = 0; i < drawCount; i ++ ) {
  46368. elementCount += counts[ i ];
  46369. }
  46370. info.update( object, elementCount, 1 );
  46371. }
  46372. }
  46373. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  46374. const { extensions, mode, object, info } = this;
  46375. if ( drawCount === 0 ) return;
  46376. const extension = extensions.get( 'WEBGL_multi_draw' );
  46377. if ( extension === null ) {
  46378. for ( let i = 0; i < drawCount; i ++ ) {
  46379. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  46380. }
  46381. } else {
  46382. if ( this.index !== 0 ) {
  46383. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  46384. } else {
  46385. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  46386. }
  46387. let elementCount = 0;
  46388. for ( let i = 0; i < drawCount; i ++ ) {
  46389. elementCount += counts[ i ] * primcount[ i ];
  46390. }
  46391. info.update( object, elementCount, 1 );
  46392. }
  46393. }
  46394. //
  46395. }
  46396. /**
  46397. * Abstract base class of a timestamp query pool.
  46398. *
  46399. * @abstract
  46400. */
  46401. class TimestampQueryPool {
  46402. /**
  46403. * Creates a new timestamp query pool.
  46404. *
  46405. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  46406. */
  46407. constructor( maxQueries = 256 ) {
  46408. /**
  46409. * Whether to track timestamps or not.
  46410. *
  46411. * @type {boolean}
  46412. * @default true
  46413. */
  46414. this.trackTimestamp = true;
  46415. /**
  46416. * Maximum number of queries this pool can hold.
  46417. *
  46418. * @type {number}
  46419. * @default 256
  46420. */
  46421. this.maxQueries = maxQueries;
  46422. /**
  46423. * How many queries allocated so far.
  46424. *
  46425. * @type {number}
  46426. * @default 0
  46427. */
  46428. this.currentQueryIndex = 0;
  46429. /**
  46430. * Tracks offsets for different contexts.
  46431. *
  46432. * @type {Map<string, number>}
  46433. */
  46434. this.queryOffsets = new Map();
  46435. /**
  46436. * Whether the pool has been disposed or not.
  46437. *
  46438. * @type {boolean}
  46439. * @default false
  46440. */
  46441. this.isDisposed = false;
  46442. /**
  46443. * TODO
  46444. *
  46445. * @type {number}
  46446. * @default 0
  46447. */
  46448. this.lastValue = 0;
  46449. /**
  46450. * Stores all timestamp frames.
  46451. *
  46452. * @type {Array<number>}
  46453. */
  46454. this.frames = [];
  46455. /**
  46456. * TODO
  46457. *
  46458. * @type {boolean}
  46459. * @default false
  46460. */
  46461. this.pendingResolve = false;
  46462. /**
  46463. * Stores the latest timestamp for each render context.
  46464. *
  46465. * @type {Map<string, number>}
  46466. */
  46467. this.timestamps = new Map();
  46468. }
  46469. /**
  46470. * Returns all timestamp frames.
  46471. *
  46472. * @return {Array<number>} The timestamp frames.
  46473. */
  46474. getTimestampFrames() {
  46475. return this.frames;
  46476. }
  46477. /**
  46478. * Returns the timestamp for a given render context.
  46479. *
  46480. * @param {string} uid - A unique identifier for the render context.
  46481. * @return {?number} The timestamp, or undefined if not available.
  46482. */
  46483. getTimestamp( uid ) {
  46484. let timestamp = this.timestamps.get( uid );
  46485. if ( timestamp === undefined ) {
  46486. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  46487. timestamp = 0;
  46488. }
  46489. return timestamp;
  46490. }
  46491. /**
  46492. * Returns whether a timestamp is available for a given render context.
  46493. *
  46494. * @param {string} uid - A unique identifier for the render context.
  46495. * @return {boolean} True if a timestamp is available, false otherwise.
  46496. */
  46497. hasTimestamp( uid ) {
  46498. return this.timestamps.has( uid );
  46499. }
  46500. /**
  46501. * Allocate queries for a specific uid.
  46502. *
  46503. * @abstract
  46504. * @param {string} uid - A unique identifier for the render context.
  46505. * @param {number} frameId - The current frame identifier.
  46506. * @returns {?number}
  46507. */
  46508. allocateQueriesForContext( /* uid, frameId */ ) {}
  46509. /**
  46510. * Resolve all timestamps and return data (or process them).
  46511. *
  46512. * @abstract
  46513. * @async
  46514. * @returns {Promise<number>|number} The resolved timestamp value.
  46515. */
  46516. async resolveQueriesAsync() {}
  46517. /**
  46518. * Dispose of the query pool.
  46519. *
  46520. * @abstract
  46521. */
  46522. dispose() {}
  46523. }
  46524. /**
  46525. * Manages a pool of WebGL timestamp queries for performance measurement.
  46526. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  46527. *
  46528. * @augments TimestampQueryPool
  46529. */
  46530. class WebGLTimestampQueryPool extends TimestampQueryPool {
  46531. /**
  46532. * Creates a new WebGL timestamp query pool.
  46533. *
  46534. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  46535. * @param {string} type - The type identifier for this query pool.
  46536. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  46537. */
  46538. constructor( gl, type, maxQueries = 2048 ) {
  46539. super( maxQueries );
  46540. this.gl = gl;
  46541. this.type = type;
  46542. // Check for timer query extensions
  46543. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  46544. gl.getExtension( 'EXT_disjoint_timer_query' );
  46545. if ( ! this.ext ) {
  46546. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  46547. this.trackTimestamp = false;
  46548. return;
  46549. }
  46550. // Create query objects
  46551. this.queries = [];
  46552. for ( let i = 0; i < this.maxQueries; i ++ ) {
  46553. this.queries.push( gl.createQuery() );
  46554. }
  46555. this.activeQuery = null;
  46556. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  46557. }
  46558. /**
  46559. * Allocates a pair of queries for a given render context.
  46560. *
  46561. * @param {string} uid - A unique identifier for the render context.
  46562. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  46563. */
  46564. allocateQueriesForContext( uid ) {
  46565. if ( ! this.trackTimestamp ) return null;
  46566. // Check if we have enough space for a new query pair
  46567. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  46568. 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() } ).` );
  46569. return null;
  46570. }
  46571. const baseOffset = this.currentQueryIndex;
  46572. this.currentQueryIndex += 2;
  46573. // Initialize query states
  46574. this.queryStates.set( baseOffset, 'inactive' );
  46575. this.queryOffsets.set( uid, baseOffset );
  46576. return baseOffset;
  46577. }
  46578. /**
  46579. * Begins a timestamp query for the specified render context.
  46580. *
  46581. * @param {string} uid - A unique identifier for the render context.
  46582. */
  46583. beginQuery( uid ) {
  46584. if ( ! this.trackTimestamp || this.isDisposed ) {
  46585. return;
  46586. }
  46587. const baseOffset = this.queryOffsets.get( uid );
  46588. if ( baseOffset == null ) {
  46589. return;
  46590. }
  46591. // Don't start a new query if there's an active one
  46592. if ( this.activeQuery !== null ) {
  46593. return;
  46594. }
  46595. const query = this.queries[ baseOffset ];
  46596. if ( ! query ) {
  46597. return;
  46598. }
  46599. try {
  46600. // Only begin if query is inactive
  46601. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  46602. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  46603. this.activeQuery = baseOffset;
  46604. this.queryStates.set( baseOffset, 'started' );
  46605. }
  46606. } catch ( error ) {
  46607. error( 'Error in beginQuery:', error );
  46608. this.activeQuery = null;
  46609. this.queryStates.set( baseOffset, 'inactive' );
  46610. }
  46611. }
  46612. /**
  46613. * Ends the active timestamp query for the specified render context.
  46614. *
  46615. * @param {string} uid - A unique identifier for the render context.
  46616. */
  46617. endQuery( uid ) {
  46618. if ( ! this.trackTimestamp || this.isDisposed ) {
  46619. return;
  46620. }
  46621. const baseOffset = this.queryOffsets.get( uid );
  46622. if ( baseOffset == null ) {
  46623. return;
  46624. }
  46625. // Only end if this is the active query
  46626. if ( this.activeQuery !== baseOffset ) {
  46627. return;
  46628. }
  46629. try {
  46630. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  46631. this.queryStates.set( baseOffset, 'ended' );
  46632. this.activeQuery = null;
  46633. } catch ( error ) {
  46634. error( 'Error in endQuery:', error );
  46635. // Reset state on error
  46636. this.queryStates.set( baseOffset, 'inactive' );
  46637. this.activeQuery = null;
  46638. }
  46639. }
  46640. /**
  46641. * Asynchronously resolves all completed queries and returns the total duration.
  46642. *
  46643. * @async
  46644. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  46645. */
  46646. async resolveQueriesAsync() {
  46647. if ( ! this.trackTimestamp || this.pendingResolve ) {
  46648. return this.lastValue;
  46649. }
  46650. this.pendingResolve = true;
  46651. try {
  46652. // Wait for all ended queries to complete
  46653. const resolvePromises = new Map();
  46654. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  46655. const state = this.queryStates.get( baseOffset );
  46656. if ( state === 'ended' ) {
  46657. const query = this.queries[ baseOffset ];
  46658. resolvePromises.set( uid, this.resolveQuery( query ) );
  46659. }
  46660. }
  46661. if ( resolvePromises.size === 0 ) {
  46662. return this.lastValue;
  46663. }
  46664. //
  46665. const framesDuration = {};
  46666. const frames = [];
  46667. for ( const [ uid, promise ] of resolvePromises ) {
  46668. const match = uid.match( /^(.*):f(\d+)$/ );
  46669. const frame = parseInt( match[ 2 ] );
  46670. if ( frames.includes( frame ) === false ) {
  46671. frames.push( frame );
  46672. }
  46673. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  46674. const duration = await promise;
  46675. this.timestamps.set( uid, duration );
  46676. framesDuration[ frame ] += duration;
  46677. }
  46678. // Return the total duration of the last frame
  46679. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  46680. // Store the last valid result
  46681. this.lastValue = totalDuration;
  46682. this.frames = frames;
  46683. // Reset states
  46684. this.currentQueryIndex = 0;
  46685. this.queryOffsets.clear();
  46686. this.queryStates.clear();
  46687. this.activeQuery = null;
  46688. return totalDuration;
  46689. } catch ( error ) {
  46690. error( 'Error resolving queries:', error );
  46691. return this.lastValue;
  46692. } finally {
  46693. this.pendingResolve = false;
  46694. }
  46695. }
  46696. /**
  46697. * Resolves a single query, checking for completion and disjoint operation.
  46698. *
  46699. * @async
  46700. * @param {WebGLQuery} query - The query object to resolve.
  46701. * @returns {Promise<number>} The elapsed time in milliseconds.
  46702. */
  46703. async resolveQuery( query ) {
  46704. return new Promise( ( resolve ) => {
  46705. if ( this.isDisposed ) {
  46706. resolve( this.lastValue );
  46707. return;
  46708. }
  46709. let timeoutId;
  46710. let isResolved = false;
  46711. const cleanup = () => {
  46712. if ( timeoutId ) {
  46713. clearTimeout( timeoutId );
  46714. timeoutId = null;
  46715. }
  46716. };
  46717. const finalizeResolution = ( value ) => {
  46718. if ( ! isResolved ) {
  46719. isResolved = true;
  46720. cleanup();
  46721. resolve( value );
  46722. }
  46723. };
  46724. const checkQuery = () => {
  46725. if ( this.isDisposed ) {
  46726. finalizeResolution( this.lastValue );
  46727. return;
  46728. }
  46729. try {
  46730. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  46731. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  46732. if ( disjoint ) {
  46733. finalizeResolution( this.lastValue );
  46734. return;
  46735. }
  46736. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  46737. if ( ! available ) {
  46738. timeoutId = setTimeout( checkQuery, 1 );
  46739. return;
  46740. }
  46741. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  46742. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  46743. } catch ( error ) {
  46744. error( 'Error checking query:', error );
  46745. resolve( this.lastValue );
  46746. }
  46747. };
  46748. checkQuery();
  46749. } );
  46750. }
  46751. /**
  46752. * Releases all resources held by this query pool.
  46753. * This includes deleting all query objects and clearing internal state.
  46754. */
  46755. dispose() {
  46756. if ( this.isDisposed ) {
  46757. return;
  46758. }
  46759. this.isDisposed = true;
  46760. if ( ! this.trackTimestamp ) return;
  46761. for ( const query of this.queries ) {
  46762. this.gl.deleteQuery( query );
  46763. }
  46764. this.queries = [];
  46765. this.queryStates.clear();
  46766. this.queryOffsets.clear();
  46767. this.lastValue = 0;
  46768. this.activeQuery = null;
  46769. }
  46770. }
  46771. /**
  46772. * A backend implementation targeting WebGL 2.
  46773. *
  46774. * @private
  46775. * @augments Backend
  46776. */
  46777. class WebGLBackend extends Backend {
  46778. /**
  46779. * WebGLBackend options.
  46780. *
  46781. * @typedef {Object} WebGLBackend~Options
  46782. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  46783. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  46784. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  46785. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  46786. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  46787. * @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.
  46788. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  46789. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  46790. */
  46791. /**
  46792. * Constructs a new WebGPU backend.
  46793. *
  46794. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  46795. */
  46796. constructor( parameters = {} ) {
  46797. super( parameters );
  46798. /**
  46799. * This flag can be used for type testing.
  46800. *
  46801. * @type {boolean}
  46802. * @readonly
  46803. * @default true
  46804. */
  46805. this.isWebGLBackend = true;
  46806. /**
  46807. * A reference to a backend module holding shader attribute-related
  46808. * utility functions.
  46809. *
  46810. * @type {?WebGLAttributeUtils}
  46811. * @default null
  46812. */
  46813. this.attributeUtils = null;
  46814. /**
  46815. * A reference to a backend module holding extension-related
  46816. * utility functions.
  46817. *
  46818. * @type {?WebGLExtensions}
  46819. * @default null
  46820. */
  46821. this.extensions = null;
  46822. /**
  46823. * A reference to a backend module holding capability-related
  46824. * utility functions.
  46825. *
  46826. * @type {?WebGLCapabilities}
  46827. * @default null
  46828. */
  46829. this.capabilities = null;
  46830. /**
  46831. * A reference to a backend module holding texture-related
  46832. * utility functions.
  46833. *
  46834. * @type {?WebGLTextureUtils}
  46835. * @default null
  46836. */
  46837. this.textureUtils = null;
  46838. /**
  46839. * A reference to a backend module holding renderer-related
  46840. * utility functions.
  46841. *
  46842. * @type {?WebGLBufferRenderer}
  46843. * @default null
  46844. */
  46845. this.bufferRenderer = null;
  46846. /**
  46847. * A reference to the rendering context.
  46848. *
  46849. * @type {?WebGL2RenderingContext}
  46850. * @default null
  46851. */
  46852. this.gl = null;
  46853. /**
  46854. * A reference to a backend module holding state-related
  46855. * utility functions.
  46856. *
  46857. * @type {?WebGLState}
  46858. * @default null
  46859. */
  46860. this.state = null;
  46861. /**
  46862. * A reference to a backend module holding common
  46863. * utility functions.
  46864. *
  46865. * @type {?WebGLUtils}
  46866. * @default null
  46867. */
  46868. this.utils = null;
  46869. /**
  46870. * Dictionary for caching VAOs.
  46871. *
  46872. * @type {Object<string,WebGLVertexArrayObject>}
  46873. */
  46874. this.vaoCache = {};
  46875. /**
  46876. * Dictionary for caching transform feedback objects.
  46877. *
  46878. * @type {Object<string,WebGLTransformFeedback>}
  46879. */
  46880. this.transformFeedbackCache = {};
  46881. /**
  46882. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  46883. * Only relevant when using compute shaders.
  46884. *
  46885. * @type {boolean}
  46886. * @default false
  46887. */
  46888. this.discard = false;
  46889. /**
  46890. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  46891. * device does not support the extension.
  46892. *
  46893. * @type {?EXTDisjointTimerQueryWebGL2}
  46894. * @default null
  46895. */
  46896. this.disjoint = null;
  46897. /**
  46898. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  46899. * device does not support the extension.
  46900. *
  46901. * @type {?KHRParallelShaderCompile}
  46902. * @default null
  46903. */
  46904. this.parallel = null;
  46905. /**
  46906. * A reference to the current render context.
  46907. *
  46908. * @private
  46909. * @type {RenderContext}
  46910. * @default null
  46911. */
  46912. this._currentContext = null;
  46913. /**
  46914. * A unique collection of bindings.
  46915. *
  46916. * @private
  46917. * @type {WeakSet<Array<BindGroup>>}
  46918. */
  46919. this._knownBindings = new WeakSet();
  46920. /**
  46921. * Whether the device supports framebuffers invalidation or not.
  46922. *
  46923. * @private
  46924. * @type {boolean}
  46925. */
  46926. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  46927. /**
  46928. * The target framebuffer when rendering with
  46929. * the WebXR device API.
  46930. *
  46931. * @private
  46932. * @type {?WebGLFramebuffer}
  46933. * @default null
  46934. */
  46935. this._xrFramebuffer = null;
  46936. }
  46937. /**
  46938. * Initializes the backend so it is ready for usage.
  46939. *
  46940. * @param {Renderer} renderer - The renderer.
  46941. */
  46942. init( renderer ) {
  46943. super.init( renderer );
  46944. //
  46945. const parameters = this.parameters;
  46946. const contextAttributes = {
  46947. antialias: renderer.currentSamples > 0,
  46948. alpha: true, // always true for performance reasons
  46949. depth: renderer.depth,
  46950. stencil: renderer.stencil
  46951. };
  46952. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  46953. function onContextLost( event ) {
  46954. event.preventDefault();
  46955. const contextLossInfo = {
  46956. api: 'WebGL',
  46957. message: event.statusMessage || 'Unknown reason',
  46958. reason: null,
  46959. originalEvent: event
  46960. };
  46961. renderer.onDeviceLost( contextLossInfo );
  46962. }
  46963. this._onContextLost = onContextLost;
  46964. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  46965. this.gl = glContext;
  46966. this.extensions = new WebGLExtensions( this );
  46967. this.capabilities = new WebGLCapabilities( this );
  46968. this.attributeUtils = new WebGLAttributeUtils( this );
  46969. this.textureUtils = new WebGLTextureUtils( this );
  46970. this.bufferRenderer = new WebGLBufferRenderer( this );
  46971. this.state = new WebGLState( this );
  46972. this.utils = new WebGLUtils( this );
  46973. this.extensions.get( 'EXT_color_buffer_float' );
  46974. this.extensions.get( 'WEBGL_clip_cull_distance' );
  46975. this.extensions.get( 'OES_texture_float_linear' );
  46976. this.extensions.get( 'EXT_color_buffer_half_float' );
  46977. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  46978. this.extensions.get( 'WEBGL_render_shared_exponent' );
  46979. this.extensions.get( 'WEBGL_multi_draw' );
  46980. this.extensions.get( 'OVR_multiview2' );
  46981. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  46982. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  46983. }
  46984. /**
  46985. * The coordinate system of the backend.
  46986. *
  46987. * @type {number}
  46988. * @readonly
  46989. */
  46990. get coordinateSystem() {
  46991. return WebGLCoordinateSystem;
  46992. }
  46993. /**
  46994. * This method performs a readback operation by moving buffer data from
  46995. * a storage buffer attribute from the GPU to the CPU.
  46996. *
  46997. * @async
  46998. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46999. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  47000. */
  47001. async getArrayBufferAsync( attribute ) {
  47002. return await this.attributeUtils.getArrayBufferAsync( attribute );
  47003. }
  47004. /**
  47005. * Ensures the backend is XR compatible.
  47006. *
  47007. * @async
  47008. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  47009. */
  47010. async makeXRCompatible() {
  47011. const attributes = this.gl.getContextAttributes();
  47012. if ( attributes.xrCompatible !== true ) {
  47013. await this.gl.makeXRCompatible();
  47014. }
  47015. }
  47016. /**
  47017. * Sets the XR rendering destination.
  47018. *
  47019. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  47020. */
  47021. setXRTarget( xrFramebuffer ) {
  47022. this._xrFramebuffer = xrFramebuffer;
  47023. }
  47024. /**
  47025. * Configures the given XR render target with external textures.
  47026. *
  47027. * This method is only relevant when using the WebXR Layers API.
  47028. *
  47029. * @param {XRRenderTarget} renderTarget - The XR render target.
  47030. * @param {WebGLTexture} colorTexture - A native color texture.
  47031. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  47032. */
  47033. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  47034. const gl = this.gl;
  47035. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  47036. if ( depthTexture !== null ) {
  47037. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  47038. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  47039. // The multisample_render_to_texture extension doesn't work properly if there
  47040. // are midframe flushes and an external depth texture.
  47041. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  47042. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  47043. }
  47044. renderTarget._autoAllocateDepthBuffer = false;
  47045. }
  47046. }
  47047. /**
  47048. * Inits a time stamp query for the given render context.
  47049. *
  47050. * @param {string} type - The type of the timestamp query.
  47051. * @param {string} uid - A unique identifier for the timestamp query.
  47052. */
  47053. initTimestampQuery( type, uid ) {
  47054. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  47055. if ( ! this.timestampQueryPool[ type ] ) {
  47056. // TODO: Variable maxQueries?
  47057. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  47058. }
  47059. const timestampQueryPool = this.timestampQueryPool[ type ];
  47060. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  47061. if ( baseOffset !== null ) {
  47062. timestampQueryPool.beginQuery( uid );
  47063. }
  47064. }
  47065. // timestamp utils
  47066. /**
  47067. * Prepares the timestamp buffer.
  47068. *
  47069. * @param {string} type - The type of the timestamp query.
  47070. * @param {string} uid - A unique identifier for the timestamp query.
  47071. */
  47072. prepareTimestampBuffer( type, uid ) {
  47073. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  47074. const timestampQueryPool = this.timestampQueryPool[ type ];
  47075. timestampQueryPool.endQuery( uid );
  47076. }
  47077. /**
  47078. * Returns the backend's rendering context.
  47079. *
  47080. * @return {WebGL2RenderingContext} The rendering context.
  47081. */
  47082. getContext() {
  47083. return this.gl;
  47084. }
  47085. /**
  47086. * This method is executed at the beginning of a render call and prepares
  47087. * the WebGL state for upcoming render calls
  47088. *
  47089. * @param {RenderContext} renderContext - The render context.
  47090. */
  47091. beginRender( renderContext ) {
  47092. const { state } = this;
  47093. const renderContextData = this.get( renderContext );
  47094. //
  47095. if ( renderContext.viewport ) {
  47096. this.updateViewport( renderContext );
  47097. } else {
  47098. const { width, height } = this.getDrawingBufferSize();
  47099. state.viewport( 0, 0, width, height );
  47100. }
  47101. if ( renderContext.scissor ) {
  47102. const { x, y, width, height } = renderContext.scissorValue;
  47103. state.scissor( x, renderContext.height - height - y, width, height );
  47104. }
  47105. //
  47106. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  47107. renderContextData.previousContext = this._currentContext;
  47108. this._currentContext = renderContext;
  47109. this._setFramebuffer( renderContext );
  47110. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  47111. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47112. if ( occlusionQueryCount > 0 ) {
  47113. // Get a reference to the array of objects with queries. The renderContextData property
  47114. // can be changed by another render pass before the async reading of all previous queries complete
  47115. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  47116. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  47117. renderContextData.lastOcclusionObject = null;
  47118. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  47119. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  47120. renderContextData.occlusionQueryIndex = 0;
  47121. }
  47122. }
  47123. /**
  47124. * This method is executed at the end of a render call and finalizes work
  47125. * after draw calls.
  47126. *
  47127. * @param {RenderContext} renderContext - The render context.
  47128. */
  47129. finishRender( renderContext ) {
  47130. const { gl, state } = this;
  47131. const renderContextData = this.get( renderContext );
  47132. const previousContext = renderContextData.previousContext;
  47133. state.resetVertexState();
  47134. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47135. if ( occlusionQueryCount > 0 ) {
  47136. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  47137. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  47138. }
  47139. this.resolveOccludedAsync( renderContext );
  47140. }
  47141. const textures = renderContext.textures;
  47142. if ( textures !== null ) {
  47143. for ( let i = 0; i < textures.length; i ++ ) {
  47144. const texture = textures[ i ];
  47145. if ( texture.generateMipmaps ) {
  47146. this.generateMipmaps( texture );
  47147. }
  47148. }
  47149. }
  47150. this._currentContext = previousContext;
  47151. this._resolveRenderTarget( renderContext );
  47152. if ( previousContext !== null ) {
  47153. this._setFramebuffer( previousContext );
  47154. if ( previousContext.viewport ) {
  47155. this.updateViewport( previousContext );
  47156. } else {
  47157. const { width, height } = this.getDrawingBufferSize();
  47158. state.viewport( 0, 0, width, height );
  47159. }
  47160. }
  47161. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  47162. }
  47163. /**
  47164. * This method processes the result of occlusion queries and writes it
  47165. * into render context data.
  47166. *
  47167. * @async
  47168. * @param {RenderContext} renderContext - The render context.
  47169. */
  47170. resolveOccludedAsync( renderContext ) {
  47171. const renderContextData = this.get( renderContext );
  47172. // handle occlusion query results
  47173. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  47174. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  47175. const occluded = new WeakSet();
  47176. const { gl } = this;
  47177. renderContextData.currentOcclusionQueryObjects = null;
  47178. renderContextData.currentOcclusionQueries = null;
  47179. const check = () => {
  47180. let completed = 0;
  47181. // check all queries and requeue as appropriate
  47182. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  47183. const query = currentOcclusionQueries[ i ];
  47184. if ( query === null ) continue;
  47185. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  47186. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  47187. currentOcclusionQueries[ i ] = null;
  47188. gl.deleteQuery( query );
  47189. completed ++;
  47190. }
  47191. }
  47192. if ( completed < currentOcclusionQueries.length ) {
  47193. requestAnimationFrame( check );
  47194. } else {
  47195. renderContextData.occluded = occluded;
  47196. }
  47197. };
  47198. check();
  47199. }
  47200. }
  47201. /**
  47202. * Returns `true` if the given 3D object is fully occluded by other
  47203. * 3D objects in the scene.
  47204. *
  47205. * @param {RenderContext} renderContext - The render context.
  47206. * @param {Object3D} object - The 3D object to test.
  47207. * @return {boolean} Whether the 3D object is fully occluded or not.
  47208. */
  47209. isOccluded( renderContext, object ) {
  47210. const renderContextData = this.get( renderContext );
  47211. return renderContextData.occluded && renderContextData.occluded.has( object );
  47212. }
  47213. /**
  47214. * Updates the viewport with the values from the given render context.
  47215. *
  47216. * @param {RenderContext} renderContext - The render context.
  47217. */
  47218. updateViewport( renderContext ) {
  47219. const { state } = this;
  47220. const { x, y, width, height } = renderContext.viewportValue;
  47221. state.viewport( x, renderContext.height - height - y, width, height );
  47222. }
  47223. /**
  47224. * Defines the scissor test.
  47225. *
  47226. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  47227. */
  47228. setScissorTest( boolean ) {
  47229. const state = this.state;
  47230. state.setScissorTest( boolean );
  47231. }
  47232. /**
  47233. * Returns the clear color and alpha into a single
  47234. * color object.
  47235. *
  47236. * @return {Color4} The clear color.
  47237. */
  47238. getClearColor() {
  47239. const clearColor = super.getClearColor();
  47240. // Since the canvas is always created with alpha: true,
  47241. // WebGL must always premultiply the clear color.
  47242. clearColor.r *= clearColor.a;
  47243. clearColor.g *= clearColor.a;
  47244. clearColor.b *= clearColor.a;
  47245. return clearColor;
  47246. }
  47247. /**
  47248. * Performs a clear operation.
  47249. *
  47250. * @param {boolean} color - Whether the color buffer should be cleared or not.
  47251. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  47252. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  47253. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  47254. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  47255. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  47256. * or not. Only relevant for explicit clears.
  47257. */
  47258. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  47259. const { gl, renderer } = this;
  47260. if ( descriptor === null ) {
  47261. const clearColor = this.getClearColor();
  47262. descriptor = {
  47263. textures: null,
  47264. clearColorValue: clearColor
  47265. };
  47266. }
  47267. //
  47268. let clear = 0;
  47269. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  47270. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  47271. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  47272. if ( clear !== 0 ) {
  47273. let clearColor;
  47274. if ( descriptor.clearColorValue ) {
  47275. clearColor = descriptor.clearColorValue;
  47276. } else {
  47277. clearColor = this.getClearColor();
  47278. }
  47279. const clearDepth = renderer.getClearDepth();
  47280. const clearStencil = renderer.getClearStencil();
  47281. if ( depth ) this.state.setDepthMask( true );
  47282. if ( descriptor.textures === null ) {
  47283. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  47284. gl.clear( clear );
  47285. } else {
  47286. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  47287. if ( color ) {
  47288. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  47289. if ( i === 0 ) {
  47290. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  47291. } else {
  47292. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  47293. }
  47294. }
  47295. }
  47296. if ( depth && stencil ) {
  47297. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  47298. } else if ( depth ) {
  47299. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  47300. } else if ( stencil ) {
  47301. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  47302. }
  47303. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  47304. }
  47305. }
  47306. }
  47307. /**
  47308. * This method is executed at the beginning of a compute call and
  47309. * prepares the state for upcoming compute tasks.
  47310. *
  47311. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47312. */
  47313. beginCompute( computeGroup ) {
  47314. const { state, gl } = this;
  47315. //
  47316. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  47317. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  47318. }
  47319. /**
  47320. * Executes a compute command for the given compute node.
  47321. *
  47322. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  47323. * @param {Node} computeNode - The compute node.
  47324. * @param {Array<BindGroup>} bindings - The bindings.
  47325. * @param {ComputePipeline} pipeline - The compute pipeline.
  47326. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  47327. */
  47328. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  47329. const { state, gl } = this;
  47330. if ( this.discard === false ) {
  47331. // required here to handle async behaviour of render.compute()
  47332. gl.enable( gl.RASTERIZER_DISCARD );
  47333. this.discard = true;
  47334. }
  47335. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  47336. const vaoKey = this._getVaoKey( attributes );
  47337. const vaoGPU = this.vaoCache[ vaoKey ];
  47338. if ( vaoGPU === undefined ) {
  47339. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  47340. } else {
  47341. state.setVertexState( vaoGPU );
  47342. }
  47343. state.useProgram( programGPU );
  47344. this._bindUniforms( bindings );
  47345. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  47346. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  47347. gl.beginTransformFeedback( gl.POINTS );
  47348. count = ( count !== null ) ? count : computeNode.count;
  47349. if ( Array.isArray( count ) ) {
  47350. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  47351. count = count[ 0 ];
  47352. }
  47353. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  47354. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  47355. } else {
  47356. gl.drawArrays( gl.POINTS, 0, count );
  47357. }
  47358. gl.endTransformFeedback();
  47359. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  47360. // switch active buffers
  47361. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  47362. const dualAttributeData = transformBuffers[ i ];
  47363. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  47364. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  47365. }
  47366. dualAttributeData.switchBuffers();
  47367. }
  47368. }
  47369. /**
  47370. * This method is executed at the end of a compute call and
  47371. * finalizes work after compute tasks.
  47372. *
  47373. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47374. */
  47375. finishCompute( computeGroup ) {
  47376. const gl = this.gl;
  47377. this.discard = false;
  47378. gl.disable( gl.RASTERIZER_DISCARD );
  47379. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  47380. if ( this._currentContext ) {
  47381. this._setFramebuffer( this._currentContext );
  47382. }
  47383. }
  47384. /**
  47385. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  47386. *
  47387. * @param {RenderContext} renderContext - The render context.
  47388. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  47389. *
  47390. * @private
  47391. */
  47392. _isRenderCameraDepthArray( renderContext ) {
  47393. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  47394. }
  47395. /**
  47396. * Executes a draw command for the given render object.
  47397. *
  47398. * @param {RenderObject} renderObject - The render object to draw.
  47399. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  47400. */
  47401. draw( renderObject/*, info*/ ) {
  47402. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  47403. const { programGPU } = this.get( pipeline );
  47404. const { gl, state } = this;
  47405. const contextData = this.get( context );
  47406. const drawParams = renderObject.getDrawParameters();
  47407. if ( drawParams === null ) return;
  47408. //
  47409. this._bindUniforms( renderObject.getBindings() );
  47410. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  47411. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  47412. state.useProgram( programGPU );
  47413. // vertex state
  47414. const attributes = renderObject.getAttributes();
  47415. const attributesData = this.get( attributes );
  47416. let vaoGPU = attributesData.vaoGPU;
  47417. if ( vaoGPU === undefined ) {
  47418. const vaoKey = this._getVaoKey( attributes );
  47419. vaoGPU = this.vaoCache[ vaoKey ];
  47420. if ( vaoGPU === undefined ) {
  47421. vaoGPU = this._createVao( attributes );
  47422. this.vaoCache[ vaoKey ] = vaoGPU;
  47423. attributesData.vaoGPU = vaoGPU;
  47424. }
  47425. }
  47426. const index = renderObject.getIndex();
  47427. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  47428. state.setVertexState( vaoGPU, indexGPU );
  47429. //
  47430. const lastObject = contextData.lastOcclusionObject;
  47431. if ( lastObject !== object && lastObject !== undefined ) {
  47432. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  47433. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  47434. contextData.occlusionQueryIndex ++;
  47435. }
  47436. if ( object.occlusionTest === true ) {
  47437. const query = gl.createQuery();
  47438. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  47439. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  47440. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  47441. }
  47442. contextData.lastOcclusionObject = object;
  47443. }
  47444. //
  47445. const renderer = this.bufferRenderer;
  47446. if ( object.isPoints ) renderer.mode = gl.POINTS;
  47447. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  47448. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  47449. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  47450. else {
  47451. if ( material.wireframe === true ) {
  47452. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  47453. renderer.mode = gl.LINES;
  47454. } else {
  47455. renderer.mode = gl.TRIANGLES;
  47456. }
  47457. }
  47458. //
  47459. const { vertexCount, instanceCount } = drawParams;
  47460. let { firstVertex } = drawParams;
  47461. renderer.object = object;
  47462. if ( index !== null ) {
  47463. firstVertex *= index.array.BYTES_PER_ELEMENT;
  47464. const indexData = this.get( index );
  47465. renderer.index = index.count;
  47466. renderer.type = indexData.type;
  47467. } else {
  47468. renderer.index = 0;
  47469. }
  47470. const draw = () => {
  47471. if ( object.isBatchedMesh ) {
  47472. if ( object._multiDrawInstances !== null ) {
  47473. // @deprecated, r174
  47474. warnOnce( 'WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  47475. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  47476. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  47477. warnOnce( 'WebGLBackend: WEBGL_multi_draw not supported.' );
  47478. } else {
  47479. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  47480. }
  47481. } else if ( instanceCount > 1 ) {
  47482. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  47483. } else {
  47484. renderer.render( firstVertex, vertexCount );
  47485. }
  47486. };
  47487. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  47488. const cameraData = this.get( renderObject.camera );
  47489. const cameras = renderObject.camera.cameras;
  47490. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  47491. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  47492. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  47493. const indexesGPU = [];
  47494. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47495. const bufferGPU = gl.createBuffer();
  47496. data[ 0 ] = i;
  47497. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47498. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  47499. indexesGPU.push( bufferGPU );
  47500. }
  47501. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  47502. }
  47503. const cameraIndexData = this.get( cameraIndex );
  47504. const pixelRatio = this.renderer.getPixelRatio();
  47505. const renderTarget = this._currentContext.renderTarget;
  47506. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  47507. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  47508. if ( isRenderCameraDepthArray ) {
  47509. // Clear the depth texture
  47510. const textureData = this.get( renderTarget.depthTexture );
  47511. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  47512. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  47513. const { stencilBuffer } = renderTarget;
  47514. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47515. this.renderer._activeCubeFace = i;
  47516. this._currentContext.activeCubeFace = i;
  47517. this._setFramebuffer( this._currentContext );
  47518. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  47519. }
  47520. this.renderer._activeCubeFace = prevActiveCubeFace;
  47521. this._currentContext.activeCubeFace = prevActiveCubeFace;
  47522. }
  47523. }
  47524. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47525. const subCamera = cameras[ i ];
  47526. if ( object.layers.test( subCamera.layers ) ) {
  47527. if ( isRenderCameraDepthArray ) {
  47528. // Update the active layer
  47529. this.renderer._activeCubeFace = i;
  47530. this._currentContext.activeCubeFace = i;
  47531. this._setFramebuffer( this._currentContext );
  47532. }
  47533. const vp = subCamera.viewport;
  47534. if ( vp !== undefined ) {
  47535. const x = vp.x * pixelRatio;
  47536. const y = vp.y * pixelRatio;
  47537. const width = vp.width * pixelRatio;
  47538. const height = vp.height * pixelRatio;
  47539. state.viewport(
  47540. Math.floor( x ),
  47541. Math.floor( renderObject.context.height - height - y ),
  47542. Math.floor( width ),
  47543. Math.floor( height )
  47544. );
  47545. }
  47546. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  47547. draw();
  47548. }
  47549. this._currentContext.activeCubeFace = prevActiveCubeFace;
  47550. this.renderer._activeCubeFace = prevActiveCubeFace;
  47551. }
  47552. } else {
  47553. draw();
  47554. }
  47555. }
  47556. /**
  47557. * Explain why always null is returned.
  47558. *
  47559. * @param {RenderObject} renderObject - The render object.
  47560. * @return {boolean} Whether the render pipeline requires an update or not.
  47561. */
  47562. needsRenderUpdate( /*renderObject*/ ) {
  47563. return false;
  47564. }
  47565. /**
  47566. * Explain why no cache key is computed.
  47567. *
  47568. * @param {RenderObject} renderObject - The render object.
  47569. * @return {string} The cache key.
  47570. */
  47571. getRenderCacheKey( /*renderObject*/ ) {
  47572. return '';
  47573. }
  47574. // textures
  47575. /**
  47576. * Creates a default texture for the given texture that can be used
  47577. * as a placeholder until the actual texture is ready for usage.
  47578. *
  47579. * @param {Texture} texture - The texture to create a default texture for.
  47580. */
  47581. createDefaultTexture( texture ) {
  47582. this.textureUtils.createDefaultTexture( texture );
  47583. }
  47584. /**
  47585. * Defines a texture on the GPU for the given texture object.
  47586. *
  47587. * @param {Texture} texture - The texture.
  47588. * @param {Object} [options={}] - Optional configuration parameter.
  47589. */
  47590. createTexture( texture, options ) {
  47591. this.textureUtils.createTexture( texture, options );
  47592. }
  47593. /**
  47594. * Uploads the updated texture data to the GPU.
  47595. *
  47596. * @param {Texture} texture - The texture.
  47597. * @param {Object} [options={}] - Optional configuration parameter.
  47598. */
  47599. updateTexture( texture, options ) {
  47600. this.textureUtils.updateTexture( texture, options );
  47601. }
  47602. /**
  47603. * Generates mipmaps for the given texture.
  47604. *
  47605. * @param {Texture} texture - The texture.
  47606. */
  47607. generateMipmaps( texture ) {
  47608. this.textureUtils.generateMipmaps( texture );
  47609. }
  47610. /**
  47611. * Destroys the GPU data for the given texture object.
  47612. *
  47613. * @param {Texture} texture - The texture.
  47614. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  47615. */
  47616. destroyTexture( texture, isDefaultTexture = false ) {
  47617. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  47618. }
  47619. /**
  47620. * Returns texture data as a typed array.
  47621. *
  47622. * @async
  47623. * @param {Texture} texture - The texture to copy.
  47624. * @param {number} x - The x coordinate of the copy origin.
  47625. * @param {number} y - The y coordinate of the copy origin.
  47626. * @param {number} width - The width of the copy.
  47627. * @param {number} height - The height of the copy.
  47628. * @param {number} faceIndex - The face index.
  47629. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47630. */
  47631. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47632. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  47633. }
  47634. /**
  47635. * This method does nothing since WebGL 2 has no concept of samplers.
  47636. *
  47637. * @param {Texture} texture - The texture to update the sampler for.
  47638. * @return {string} The current sampler key.
  47639. */
  47640. updateSampler( /*texture*/ ) {
  47641. return '';
  47642. }
  47643. // node builder
  47644. /**
  47645. * Returns a node builder for the given render object.
  47646. *
  47647. * @param {RenderObject} object - The render object.
  47648. * @param {Renderer} renderer - The renderer.
  47649. * @return {GLSLNodeBuilder} The node builder.
  47650. */
  47651. createNodeBuilder( object, renderer ) {
  47652. return new GLSLNodeBuilder( object, renderer );
  47653. }
  47654. // program
  47655. /**
  47656. * Creates a shader program from the given programmable stage.
  47657. *
  47658. * @param {ProgrammableStage} program - The programmable stage.
  47659. */
  47660. createProgram( program ) {
  47661. const gl = this.gl;
  47662. const { stage, code } = program;
  47663. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  47664. gl.shaderSource( shader, code );
  47665. gl.compileShader( shader );
  47666. this.set( program, {
  47667. shaderGPU: shader
  47668. } );
  47669. }
  47670. /**
  47671. * Destroys the shader program of the given programmable stage.
  47672. *
  47673. * @param {ProgrammableStage} program - The programmable stage.
  47674. */
  47675. destroyProgram( program ) {
  47676. this.delete( program );
  47677. }
  47678. /**
  47679. * Creates a render pipeline for the given render object.
  47680. *
  47681. * @param {RenderObject} renderObject - The render object.
  47682. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47683. */
  47684. createRenderPipeline( renderObject, promises ) {
  47685. const gl = this.gl;
  47686. const pipeline = renderObject.pipeline;
  47687. // Program
  47688. const { fragmentProgram, vertexProgram } = pipeline;
  47689. const programGPU = gl.createProgram();
  47690. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  47691. const vertexShader = this.get( vertexProgram ).shaderGPU;
  47692. gl.attachShader( programGPU, fragmentShader );
  47693. gl.attachShader( programGPU, vertexShader );
  47694. gl.linkProgram( programGPU );
  47695. this.set( pipeline, {
  47696. programGPU,
  47697. fragmentShader,
  47698. vertexShader
  47699. } );
  47700. if ( promises !== null && this.parallel ) {
  47701. const p = new Promise( ( resolve /*, reject*/ ) => {
  47702. const parallel = this.parallel;
  47703. const checkStatus = () => {
  47704. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  47705. this._completeCompile( renderObject, pipeline );
  47706. resolve();
  47707. } else {
  47708. requestAnimationFrame( checkStatus );
  47709. }
  47710. };
  47711. checkStatus();
  47712. } );
  47713. promises.push( p );
  47714. return;
  47715. }
  47716. this._completeCompile( renderObject, pipeline );
  47717. }
  47718. /**
  47719. * Formats the source code of error messages.
  47720. *
  47721. * @private
  47722. * @param {string} string - The code.
  47723. * @param {number} errorLine - The error line.
  47724. * @return {string} The formatted code.
  47725. */
  47726. _handleSource( string, errorLine ) {
  47727. const lines = string.split( '\n' );
  47728. const lines2 = [];
  47729. const from = Math.max( errorLine - 6, 0 );
  47730. const to = Math.min( errorLine + 6, lines.length );
  47731. for ( let i = from; i < to; i ++ ) {
  47732. const line = i + 1;
  47733. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  47734. }
  47735. return lines2.join( '\n' );
  47736. }
  47737. /**
  47738. * Gets the shader compilation errors from the info log.
  47739. *
  47740. * @private
  47741. * @param {WebGL2RenderingContext} gl - The rendering context.
  47742. * @param {WebGLShader} shader - The WebGL shader object.
  47743. * @param {string} type - The shader type.
  47744. * @return {string} The shader errors.
  47745. */
  47746. _getShaderErrors( gl, shader, type ) {
  47747. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  47748. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  47749. const errors = shaderInfoLog.trim();
  47750. if ( status && errors === '' ) return '';
  47751. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  47752. if ( errorMatches ) {
  47753. const errorLine = parseInt( errorMatches[ 1 ] );
  47754. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  47755. } else {
  47756. return errors;
  47757. }
  47758. }
  47759. /**
  47760. * Logs shader compilation errors.
  47761. *
  47762. * @private
  47763. * @param {WebGLProgram} programGPU - The WebGL program.
  47764. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  47765. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  47766. */
  47767. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  47768. if ( this.renderer.debug.checkShaderErrors ) {
  47769. const gl = this.gl;
  47770. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  47771. const programLog = programInfoLog.trim();
  47772. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  47773. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  47774. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  47775. } else {
  47776. // default error reporting
  47777. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  47778. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  47779. error(
  47780. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  47781. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  47782. 'Program Info Log: ' + programLog + '\n' +
  47783. vertexErrors + '\n' +
  47784. fragmentErrors
  47785. );
  47786. }
  47787. } else if ( programLog !== '' ) {
  47788. warn( 'WebGLProgram: Program Info Log:', programLog );
  47789. }
  47790. }
  47791. }
  47792. /**
  47793. * Completes the shader program setup for the given render object.
  47794. *
  47795. * @private
  47796. * @param {RenderObject} renderObject - The render object.
  47797. * @param {RenderPipeline} pipeline - The render pipeline.
  47798. */
  47799. _completeCompile( renderObject, pipeline ) {
  47800. const { state, gl } = this;
  47801. const pipelineData = this.get( pipeline );
  47802. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  47803. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  47804. this._logProgramError( programGPU, fragmentShader, vertexShader );
  47805. }
  47806. state.useProgram( programGPU );
  47807. // Bindings
  47808. const bindings = renderObject.getBindings();
  47809. this._setupBindings( bindings, programGPU );
  47810. //
  47811. this.set( pipeline, {
  47812. programGPU
  47813. } );
  47814. }
  47815. /**
  47816. * Creates a compute pipeline for the given compute node.
  47817. *
  47818. * @param {ComputePipeline} computePipeline - The compute pipeline.
  47819. * @param {Array<BindGroup>} bindings - The bindings.
  47820. */
  47821. createComputePipeline( computePipeline, bindings ) {
  47822. const { state, gl } = this;
  47823. // Program
  47824. const fragmentProgram = {
  47825. stage: 'fragment',
  47826. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  47827. };
  47828. this.createProgram( fragmentProgram );
  47829. const { computeProgram } = computePipeline;
  47830. const programGPU = gl.createProgram();
  47831. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  47832. const vertexShader = this.get( computeProgram ).shaderGPU;
  47833. const transforms = computeProgram.transforms;
  47834. const transformVaryingNames = [];
  47835. const transformAttributeNodes = [];
  47836. for ( let i = 0; i < transforms.length; i ++ ) {
  47837. const transform = transforms[ i ];
  47838. transformVaryingNames.push( transform.varyingName );
  47839. transformAttributeNodes.push( transform.attributeNode );
  47840. }
  47841. gl.attachShader( programGPU, fragmentShader );
  47842. gl.attachShader( programGPU, vertexShader );
  47843. gl.transformFeedbackVaryings(
  47844. programGPU,
  47845. transformVaryingNames,
  47846. gl.SEPARATE_ATTRIBS
  47847. );
  47848. gl.linkProgram( programGPU );
  47849. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  47850. this._logProgramError( programGPU, fragmentShader, vertexShader );
  47851. }
  47852. state.useProgram( programGPU );
  47853. // Bindings
  47854. this._setupBindings( bindings, programGPU );
  47855. const attributeNodes = computeProgram.attributes;
  47856. const attributes = [];
  47857. const transformBuffers = [];
  47858. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  47859. const attribute = attributeNodes[ i ].node.attribute;
  47860. attributes.push( attribute );
  47861. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  47862. }
  47863. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  47864. const attribute = transformAttributeNodes[ i ].attribute;
  47865. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  47866. const attributeData = this.get( attribute );
  47867. transformBuffers.push( attributeData );
  47868. }
  47869. //
  47870. this.set( computePipeline, {
  47871. programGPU,
  47872. transformBuffers,
  47873. attributes
  47874. } );
  47875. }
  47876. /**
  47877. * Creates bindings from the given bind group definition.
  47878. *
  47879. * @param {BindGroup} bindGroup - The bind group.
  47880. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47881. * @param {number} cacheIndex - The cache index.
  47882. * @param {number} version - The version.
  47883. */
  47884. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  47885. if ( this._knownBindings.has( bindings ) === false ) {
  47886. this._knownBindings.add( bindings );
  47887. let uniformBuffers = 0;
  47888. let textures = 0;
  47889. for ( const bindGroup of bindings ) {
  47890. this.set( bindGroup, {
  47891. textures: textures,
  47892. uniformBuffers: uniformBuffers
  47893. } );
  47894. for ( const binding of bindGroup.bindings ) {
  47895. if ( binding.isUniformBuffer ) uniformBuffers ++;
  47896. if ( binding.isSampledTexture ) textures ++;
  47897. }
  47898. }
  47899. }
  47900. this.updateBindings( bindGroup, bindings );
  47901. }
  47902. /**
  47903. * Updates the given bind group definition.
  47904. *
  47905. * @param {BindGroup} bindGroup - The bind group.
  47906. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47907. * @param {number} cacheIndex - The cache index.
  47908. * @param {number} version - The version.
  47909. */
  47910. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  47911. const { gl } = this;
  47912. const bindGroupData = this.get( bindGroup );
  47913. let i = bindGroupData.uniformBuffers;
  47914. let t = bindGroupData.textures;
  47915. for ( const binding of bindGroup.bindings ) {
  47916. const map = this.get( binding );
  47917. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  47918. const data = binding.buffer;
  47919. let { bufferGPU } = this.get( data );
  47920. if ( bufferGPU === undefined ) {
  47921. // create
  47922. bufferGPU = gl.createBuffer();
  47923. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47924. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  47925. this.set( data, { bufferGPU } );
  47926. } else {
  47927. // update
  47928. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47929. gl.bufferSubData( gl.UNIFORM_BUFFER, 0, data );
  47930. }
  47931. map.index = i ++;
  47932. map.bufferGPU = bufferGPU;
  47933. this.set( binding, map );
  47934. } else if ( binding.isSampledTexture ) {
  47935. const { textureGPU, glTextureType } = this.get( binding.texture );
  47936. map.index = t ++;
  47937. map.textureGPU = textureGPU;
  47938. map.glTextureType = glTextureType;
  47939. this.set( binding, map );
  47940. }
  47941. }
  47942. }
  47943. /**
  47944. * Updates a buffer binding.
  47945. *
  47946. * @param {Buffer} binding - The buffer binding to update.
  47947. */
  47948. updateBinding( binding ) {
  47949. const gl = this.gl;
  47950. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  47951. const bindingData = this.get( binding );
  47952. const bufferGPU = bindingData.bufferGPU;
  47953. const data = binding.buffer;
  47954. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47955. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  47956. }
  47957. }
  47958. // attributes
  47959. /**
  47960. * Creates the GPU buffer of an indexed shader attribute.
  47961. *
  47962. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  47963. */
  47964. createIndexAttribute( attribute ) {
  47965. const gl = this.gl;
  47966. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  47967. }
  47968. /**
  47969. * Creates the GPU buffer of a shader attribute.
  47970. *
  47971. * @param {BufferAttribute} attribute - The buffer attribute.
  47972. */
  47973. createAttribute( attribute ) {
  47974. if ( this.has( attribute ) ) return;
  47975. const gl = this.gl;
  47976. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  47977. }
  47978. /**
  47979. * Creates the GPU buffer of a storage attribute.
  47980. *
  47981. * @param {BufferAttribute} attribute - The buffer attribute.
  47982. */
  47983. createStorageAttribute( attribute ) {
  47984. if ( this.has( attribute ) ) return;
  47985. const gl = this.gl;
  47986. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  47987. }
  47988. /**
  47989. * Updates the GPU buffer of a shader attribute.
  47990. *
  47991. * @param {BufferAttribute} attribute - The buffer attribute to update.
  47992. */
  47993. updateAttribute( attribute ) {
  47994. this.attributeUtils.updateAttribute( attribute );
  47995. }
  47996. /**
  47997. * Destroys the GPU buffer of a shader attribute.
  47998. *
  47999. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  48000. */
  48001. destroyAttribute( attribute ) {
  48002. this.attributeUtils.destroyAttribute( attribute );
  48003. }
  48004. /**
  48005. * Checks if the given feature is supported by the backend.
  48006. *
  48007. * @param {string} name - The feature's name.
  48008. * @return {boolean} Whether the feature is supported or not.
  48009. */
  48010. hasFeature( name ) {
  48011. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  48012. const extensions = this.extensions;
  48013. for ( let i = 0; i < keysMatching.length; i ++ ) {
  48014. if ( extensions.has( keysMatching[ i ] ) ) return true;
  48015. }
  48016. return false;
  48017. }
  48018. /**
  48019. * Returns the maximum anisotropy texture filtering value.
  48020. *
  48021. * @return {number} The maximum anisotropy texture filtering value.
  48022. */
  48023. getMaxAnisotropy() {
  48024. return this.capabilities.getMaxAnisotropy();
  48025. }
  48026. /**
  48027. * Copies data of the given source texture to the given destination texture.
  48028. *
  48029. * @param {Texture} srcTexture - The source texture.
  48030. * @param {Texture} dstTexture - The destination texture.
  48031. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  48032. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  48033. * @param {number} [srcLevel=0] - The source mip level to copy from.
  48034. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  48035. */
  48036. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  48037. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  48038. }
  48039. /**
  48040. * Copies the current bound framebuffer to the given texture.
  48041. *
  48042. * @param {Texture} texture - The destination texture.
  48043. * @param {RenderContext} renderContext - The render context.
  48044. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  48045. */
  48046. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  48047. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  48048. }
  48049. /**
  48050. * Configures the active framebuffer from the given render context.
  48051. *
  48052. * @private
  48053. * @param {RenderContext} descriptor - The render context.
  48054. */
  48055. _setFramebuffer( descriptor ) {
  48056. const { gl, state } = this;
  48057. let currentFrameBuffer = null;
  48058. if ( descriptor.textures !== null ) {
  48059. const renderTarget = descriptor.renderTarget;
  48060. const renderTargetContextData = this.get( renderTarget );
  48061. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  48062. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  48063. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  48064. const isRenderTargetArray = renderTarget.depth > 1;
  48065. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  48066. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  48067. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  48068. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  48069. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  48070. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  48071. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  48072. const cacheKey = getCacheKey( descriptor );
  48073. let fb;
  48074. if ( isCube ) {
  48075. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  48076. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  48077. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  48078. fb = this._xrFramebuffer;
  48079. } else {
  48080. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  48081. fb = renderTargetContextData.framebuffers[ cacheKey ];
  48082. }
  48083. if ( fb === undefined ) {
  48084. fb = gl.createFramebuffer();
  48085. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48086. const textures = descriptor.textures;
  48087. const depthInvalidationArray = [];
  48088. if ( isCube ) {
  48089. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  48090. const { textureGPU } = this.get( textures[ 0 ] );
  48091. const cubeFace = this.renderer._activeCubeFace;
  48092. const mipLevel = this.renderer._activeMipmapLevel;
  48093. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  48094. } else {
  48095. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  48096. for ( let i = 0; i < textures.length; i ++ ) {
  48097. const texture = textures[ i ];
  48098. const textureData = this.get( texture );
  48099. textureData.renderTarget = descriptor.renderTarget;
  48100. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  48101. const attachment = gl.COLOR_ATTACHMENT0 + i;
  48102. if ( renderTarget.multiview ) {
  48103. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  48104. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  48105. const layer = this.renderer._activeCubeFace;
  48106. const mipLevel = this.renderer._activeMipmapLevel;
  48107. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  48108. } else {
  48109. if ( useMultisampledRTT ) {
  48110. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48111. } else {
  48112. const mipLevel = this.renderer._activeMipmapLevel;
  48113. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  48114. }
  48115. }
  48116. }
  48117. }
  48118. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48119. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  48120. const renderbuffer = gl.createRenderbuffer();
  48121. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  48122. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  48123. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  48124. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  48125. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  48126. } else {
  48127. if ( descriptor.depthTexture !== null ) {
  48128. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  48129. const textureData = this.get( descriptor.depthTexture );
  48130. textureData.renderTarget = descriptor.renderTarget;
  48131. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  48132. if ( renderTarget.multiview ) {
  48133. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  48134. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  48135. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48136. } else {
  48137. if ( descriptor.depthTexture.isArrayTexture ) {
  48138. const layer = this.renderer._activeCubeFace;
  48139. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  48140. } else {
  48141. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48142. }
  48143. }
  48144. }
  48145. }
  48146. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  48147. } else {
  48148. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  48149. if ( isRenderCameraDepthArray ) {
  48150. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48151. const layer = this.renderer._activeCubeFace;
  48152. const depthData = this.get( descriptor.depthTexture );
  48153. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48154. gl.framebufferTextureLayer(
  48155. gl.FRAMEBUFFER,
  48156. depthStyle,
  48157. depthData.textureGPU,
  48158. 0,
  48159. layer
  48160. );
  48161. }
  48162. // rebind external XR textures
  48163. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  48164. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48165. // rebind color
  48166. const textureData = this.get( descriptor.textures[ 0 ] );
  48167. if ( renderTarget.multiview ) {
  48168. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  48169. } else if ( useMultisampledRTT ) {
  48170. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48171. } else {
  48172. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48173. }
  48174. // rebind depth
  48175. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48176. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  48177. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  48178. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  48179. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  48180. } else {
  48181. const textureData = this.get( descriptor.depthTexture );
  48182. if ( renderTarget.multiview ) {
  48183. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  48184. } else if ( useMultisampledRTT ) {
  48185. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48186. } else {
  48187. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48188. }
  48189. }
  48190. }
  48191. }
  48192. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  48193. if ( msaaFb === undefined ) {
  48194. const invalidationArray = [];
  48195. msaaFb = gl.createFramebuffer();
  48196. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  48197. const msaaRenderbuffers = [];
  48198. const textures = descriptor.textures;
  48199. for ( let i = 0; i < textures.length; i ++ ) {
  48200. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  48201. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48202. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  48203. const texture = descriptor.textures[ i ];
  48204. const textureData = this.get( texture );
  48205. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  48206. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48207. }
  48208. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  48209. renderTargetContextData.msaaFrameBuffer = msaaFb;
  48210. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  48211. if ( depthBuffer && depthRenderbuffer === undefined ) {
  48212. depthRenderbuffer = gl.createRenderbuffer();
  48213. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  48214. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  48215. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48216. invalidationArray.push( depthStyle );
  48217. }
  48218. renderTargetContextData.invalidationArray = invalidationArray;
  48219. }
  48220. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  48221. } else {
  48222. currentFrameBuffer = fb;
  48223. }
  48224. state.drawBuffers( descriptor, fb );
  48225. }
  48226. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  48227. }
  48228. /**
  48229. * Computes the VAO key for the given index and attributes.
  48230. *
  48231. * @private
  48232. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  48233. * @return {string} The VAO key.
  48234. */
  48235. _getVaoKey( attributes ) {
  48236. let key = '';
  48237. for ( let i = 0; i < attributes.length; i ++ ) {
  48238. const attributeData = this.get( attributes[ i ] );
  48239. key += ':' + attributeData.id;
  48240. }
  48241. return key;
  48242. }
  48243. /**
  48244. * Creates a VAO from the index and attributes.
  48245. *
  48246. * @private
  48247. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  48248. * @return {Object} The VAO data.
  48249. */
  48250. _createVao( attributes ) {
  48251. const { gl } = this;
  48252. const vaoGPU = gl.createVertexArray();
  48253. gl.bindVertexArray( vaoGPU );
  48254. for ( let i = 0; i < attributes.length; i ++ ) {
  48255. const attribute = attributes[ i ];
  48256. const attributeData = this.get( attribute );
  48257. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  48258. gl.enableVertexAttribArray( i );
  48259. let stride, offset;
  48260. if ( attribute.isInterleavedBufferAttribute === true ) {
  48261. stride = attribute.data.stride * attributeData.bytesPerElement;
  48262. offset = attribute.offset * attributeData.bytesPerElement;
  48263. } else {
  48264. stride = 0;
  48265. offset = 0;
  48266. }
  48267. if ( attributeData.isInteger ) {
  48268. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  48269. } else {
  48270. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  48271. }
  48272. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  48273. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  48274. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  48275. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  48276. }
  48277. }
  48278. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  48279. return vaoGPU;
  48280. }
  48281. /**
  48282. * Creates a transform feedback from the given transform buffers.
  48283. *
  48284. * @private
  48285. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  48286. * @return {WebGLTransformFeedback} The transform feedback.
  48287. */
  48288. _getTransformFeedback( transformBuffers ) {
  48289. let key = '';
  48290. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48291. key += ':' + transformBuffers[ i ].id;
  48292. }
  48293. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  48294. if ( transformFeedbackGPU !== undefined ) {
  48295. return transformFeedbackGPU;
  48296. }
  48297. const { gl } = this;
  48298. transformFeedbackGPU = gl.createTransformFeedback();
  48299. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  48300. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48301. const attributeData = transformBuffers[ i ];
  48302. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  48303. }
  48304. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  48305. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  48306. return transformFeedbackGPU;
  48307. }
  48308. /**
  48309. * Setups the given bindings.
  48310. *
  48311. * @private
  48312. * @param {Array<BindGroup>} bindings - The bindings.
  48313. * @param {WebGLProgram} programGPU - The WebGL program.
  48314. */
  48315. _setupBindings( bindings, programGPU ) {
  48316. const gl = this.gl;
  48317. for ( const bindGroup of bindings ) {
  48318. for ( const binding of bindGroup.bindings ) {
  48319. const bindingData = this.get( binding );
  48320. const index = bindingData.index;
  48321. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48322. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  48323. gl.uniformBlockBinding( programGPU, location, index );
  48324. } else if ( binding.isSampledTexture ) {
  48325. const location = gl.getUniformLocation( programGPU, binding.name );
  48326. gl.uniform1i( location, index );
  48327. }
  48328. }
  48329. }
  48330. }
  48331. /**
  48332. * Binds the given uniforms.
  48333. *
  48334. * @private
  48335. * @param {Array<BindGroup>} bindings - The bindings.
  48336. */
  48337. _bindUniforms( bindings ) {
  48338. const { gl, state } = this;
  48339. for ( const bindGroup of bindings ) {
  48340. for ( const binding of bindGroup.bindings ) {
  48341. const bindingData = this.get( binding );
  48342. const index = bindingData.index;
  48343. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48344. // TODO USE bindBufferRange to group multiple uniform buffers
  48345. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  48346. } else if ( binding.isSampledTexture ) {
  48347. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  48348. }
  48349. }
  48350. }
  48351. }
  48352. /**
  48353. * The method ensures multisampled render targets are resolved.
  48354. *
  48355. * @private
  48356. * @param {RenderContext} renderContext - The render context.
  48357. */
  48358. _resolveRenderTarget( renderContext ) {
  48359. const { gl, state } = this;
  48360. const renderTarget = renderContext.renderTarget;
  48361. if ( renderContext.textures !== null && renderTarget ) {
  48362. const renderTargetContextData = this.get( renderTarget );
  48363. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  48364. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  48365. let mask = gl.COLOR_BUFFER_BIT;
  48366. if ( renderTarget.resolveDepthBuffer ) {
  48367. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  48368. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  48369. }
  48370. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  48371. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  48372. const textures = renderContext.textures;
  48373. const isMRT = textures.length > 1;
  48374. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  48375. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  48376. if ( isMRT ) {
  48377. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  48378. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  48379. for ( let i = 0; i < textures.length; i ++ ) {
  48380. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  48381. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  48382. }
  48383. }
  48384. for ( let i = 0; i < textures.length; i ++ ) {
  48385. if ( isMRT ) {
  48386. // configure attachment for resolve
  48387. const { textureGPU } = this.get( textures[ i ] );
  48388. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48389. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  48390. }
  48391. if ( renderContext.scissor ) {
  48392. const { x, y, width, height } = renderContext.scissorValue;
  48393. const viewY = renderContext.height - height - y;
  48394. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  48395. } else {
  48396. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  48397. }
  48398. }
  48399. if ( isMRT ) {
  48400. // restore attachments
  48401. for ( let i = 0; i < textures.length; i ++ ) {
  48402. const { textureGPU } = this.get( textures[ i ] );
  48403. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48404. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  48405. }
  48406. }
  48407. if ( this._supportsInvalidateFramebuffer === true ) {
  48408. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  48409. }
  48410. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  48411. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  48412. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  48413. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  48414. }
  48415. }
  48416. }
  48417. /**
  48418. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  48419. * should be used when MSAA is enabled.
  48420. *
  48421. * @private
  48422. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  48423. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  48424. */
  48425. _useMultisampledExtension( renderTarget ) {
  48426. if ( renderTarget.multiview === true ) {
  48427. return true;
  48428. }
  48429. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  48430. }
  48431. /**
  48432. * Frees internal resources.
  48433. */
  48434. dispose() {
  48435. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  48436. const extension = this.extensions.get( 'WEBGL_lose_context' );
  48437. if ( extension ) extension.loseContext();
  48438. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  48439. }
  48440. }
  48441. const GPUPrimitiveTopology = {
  48442. PointList: 'point-list',
  48443. LineList: 'line-list',
  48444. LineStrip: 'line-strip',
  48445. TriangleList: 'triangle-list',
  48446. TriangleStrip: 'triangle-strip',
  48447. };
  48448. const GPUCompareFunction = {
  48449. Never: 'never',
  48450. Less: 'less',
  48451. Equal: 'equal',
  48452. LessEqual: 'less-equal',
  48453. Greater: 'greater',
  48454. NotEqual: 'not-equal',
  48455. GreaterEqual: 'greater-equal',
  48456. Always: 'always'
  48457. };
  48458. const GPUStoreOp = {
  48459. Store: 'store'};
  48460. const GPULoadOp = {
  48461. Load: 'load',
  48462. Clear: 'clear'
  48463. };
  48464. const GPUFrontFace = {
  48465. CCW: 'ccw',
  48466. CW: 'cw'
  48467. };
  48468. const GPUCullMode = {
  48469. None: 'none',
  48470. Back: 'back'
  48471. };
  48472. const GPUIndexFormat = {
  48473. Uint16: 'uint16',
  48474. Uint32: 'uint32'
  48475. };
  48476. const GPUTextureFormat = {
  48477. // 8-bit formats
  48478. R8Unorm: 'r8unorm',
  48479. R8Snorm: 'r8snorm',
  48480. R8Uint: 'r8uint',
  48481. R8Sint: 'r8sint',
  48482. // 16-bit formats
  48483. R16Uint: 'r16uint',
  48484. R16Sint: 'r16sint',
  48485. R16Float: 'r16float',
  48486. RG8Unorm: 'rg8unorm',
  48487. RG8Snorm: 'rg8snorm',
  48488. RG8Uint: 'rg8uint',
  48489. RG8Sint: 'rg8sint',
  48490. // 32-bit formats
  48491. R32Uint: 'r32uint',
  48492. R32Sint: 'r32sint',
  48493. R32Float: 'r32float',
  48494. RG16Uint: 'rg16uint',
  48495. RG16Sint: 'rg16sint',
  48496. RG16Float: 'rg16float',
  48497. RGBA8Unorm: 'rgba8unorm',
  48498. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  48499. RGBA8Snorm: 'rgba8snorm',
  48500. RGBA8Uint: 'rgba8uint',
  48501. RGBA8Sint: 'rgba8sint',
  48502. BGRA8Unorm: 'bgra8unorm',
  48503. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  48504. // Packed 32-bit formats
  48505. RGB9E5UFloat: 'rgb9e5ufloat',
  48506. RGB10A2Unorm: 'rgb10a2unorm',
  48507. RG11B10UFloat: 'rg11b10ufloat',
  48508. // 64-bit formats
  48509. RG32Uint: 'rg32uint',
  48510. RG32Sint: 'rg32sint',
  48511. RG32Float: 'rg32float',
  48512. RGBA16Uint: 'rgba16uint',
  48513. RGBA16Sint: 'rgba16sint',
  48514. RGBA16Float: 'rgba16float',
  48515. // 128-bit formats
  48516. RGBA32Uint: 'rgba32uint',
  48517. RGBA32Sint: 'rgba32sint',
  48518. RGBA32Float: 'rgba32float',
  48519. Depth16Unorm: 'depth16unorm',
  48520. Depth24Plus: 'depth24plus',
  48521. Depth24PlusStencil8: 'depth24plus-stencil8',
  48522. Depth32Float: 'depth32float',
  48523. // 'depth32float-stencil8' extension
  48524. Depth32FloatStencil8: 'depth32float-stencil8',
  48525. // BC compressed formats usable if 'texture-compression-bc' is both
  48526. // supported by the device/user agent and enabled in requestDevice.
  48527. BC1RGBAUnorm: 'bc1-rgba-unorm',
  48528. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  48529. BC2RGBAUnorm: 'bc2-rgba-unorm',
  48530. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  48531. BC3RGBAUnorm: 'bc3-rgba-unorm',
  48532. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  48533. BC4RUnorm: 'bc4-r-unorm',
  48534. BC4RSnorm: 'bc4-r-snorm',
  48535. BC5RGUnorm: 'bc5-rg-unorm',
  48536. BC5RGSnorm: 'bc5-rg-snorm',
  48537. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  48538. BC6HRGBFloat: 'bc6h-rgb-float',
  48539. BC7RGBAUnorm: 'bc7-rgba-unorm',
  48540. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  48541. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  48542. // supported by the device/user agent and enabled in requestDevice.
  48543. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  48544. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  48545. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  48546. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  48547. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  48548. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  48549. EACR11Unorm: 'eac-r11unorm',
  48550. EACR11Snorm: 'eac-r11snorm',
  48551. EACRG11Unorm: 'eac-rg11unorm',
  48552. EACRG11Snorm: 'eac-rg11snorm',
  48553. // ASTC compressed formats usable if 'texture-compression-astc' is both
  48554. // supported by the device/user agent and enabled in requestDevice.
  48555. ASTC4x4Unorm: 'astc-4x4-unorm',
  48556. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  48557. ASTC5x4Unorm: 'astc-5x4-unorm',
  48558. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  48559. ASTC5x5Unorm: 'astc-5x5-unorm',
  48560. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  48561. ASTC6x5Unorm: 'astc-6x5-unorm',
  48562. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  48563. ASTC6x6Unorm: 'astc-6x6-unorm',
  48564. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  48565. ASTC8x5Unorm: 'astc-8x5-unorm',
  48566. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  48567. ASTC8x6Unorm: 'astc-8x6-unorm',
  48568. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  48569. ASTC8x8Unorm: 'astc-8x8-unorm',
  48570. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  48571. ASTC10x5Unorm: 'astc-10x5-unorm',
  48572. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  48573. ASTC10x6Unorm: 'astc-10x6-unorm',
  48574. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  48575. ASTC10x8Unorm: 'astc-10x8-unorm',
  48576. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  48577. ASTC10x10Unorm: 'astc-10x10-unorm',
  48578. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  48579. ASTC12x10Unorm: 'astc-12x10-unorm',
  48580. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  48581. ASTC12x12Unorm: 'astc-12x12-unorm',
  48582. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  48583. };
  48584. const GPUAddressMode = {
  48585. ClampToEdge: 'clamp-to-edge',
  48586. Repeat: 'repeat',
  48587. MirrorRepeat: 'mirror-repeat'
  48588. };
  48589. const GPUFilterMode = {
  48590. Linear: 'linear',
  48591. Nearest: 'nearest'
  48592. };
  48593. const GPUBlendFactor = {
  48594. Zero: 'zero',
  48595. One: 'one',
  48596. Src: 'src',
  48597. OneMinusSrc: 'one-minus-src',
  48598. SrcAlpha: 'src-alpha',
  48599. OneMinusSrcAlpha: 'one-minus-src-alpha',
  48600. Dst: 'dst',
  48601. OneMinusDst: 'one-minus-dst',
  48602. DstAlpha: 'dst-alpha',
  48603. OneMinusDstAlpha: 'one-minus-dst-alpha',
  48604. SrcAlphaSaturated: 'src-alpha-saturated',
  48605. Constant: 'constant',
  48606. OneMinusConstant: 'one-minus-constant'
  48607. };
  48608. const GPUBlendOperation = {
  48609. Add: 'add',
  48610. Subtract: 'subtract',
  48611. ReverseSubtract: 'reverse-subtract',
  48612. Min: 'min',
  48613. Max: 'max'
  48614. };
  48615. const GPUColorWriteFlags = {
  48616. None: 0,
  48617. All: 0xF
  48618. };
  48619. const GPUStencilOperation = {
  48620. Keep: 'keep',
  48621. Zero: 'zero',
  48622. Replace: 'replace',
  48623. Invert: 'invert',
  48624. IncrementClamp: 'increment-clamp',
  48625. DecrementClamp: 'decrement-clamp',
  48626. IncrementWrap: 'increment-wrap',
  48627. DecrementWrap: 'decrement-wrap'
  48628. };
  48629. const GPUBufferBindingType = {
  48630. Storage: 'storage',
  48631. ReadOnlyStorage: 'read-only-storage'
  48632. };
  48633. const GPUStorageTextureAccess = {
  48634. WriteOnly: 'write-only',
  48635. ReadOnly: 'read-only',
  48636. ReadWrite: 'read-write',
  48637. };
  48638. const GPUSamplerBindingType = {
  48639. NonFiltering: 'non-filtering',
  48640. Comparison: 'comparison'
  48641. };
  48642. const GPUTextureSampleType = {
  48643. Float: 'float',
  48644. UnfilterableFloat: 'unfilterable-float',
  48645. Depth: 'depth',
  48646. SInt: 'sint',
  48647. UInt: 'uint'
  48648. };
  48649. const GPUTextureDimension = {
  48650. TwoD: '2d',
  48651. ThreeD: '3d'
  48652. };
  48653. const GPUTextureViewDimension = {
  48654. TwoD: '2d',
  48655. TwoDArray: '2d-array',
  48656. Cube: 'cube',
  48657. ThreeD: '3d'
  48658. };
  48659. const GPUTextureAspect = {
  48660. All: 'all'};
  48661. const GPUInputStepMode = {
  48662. Vertex: 'vertex',
  48663. Instance: 'instance'
  48664. };
  48665. const GPUFeatureName = {
  48666. CoreFeaturesAndLimits: 'core-features-and-limits',
  48667. DepthClipControl: 'depth-clip-control',
  48668. Depth32FloatStencil8: 'depth32float-stencil8',
  48669. TextureCompressionBC: 'texture-compression-bc',
  48670. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  48671. TextureCompressionETC2: 'texture-compression-etc2',
  48672. TextureCompressionASTC: 'texture-compression-astc',
  48673. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  48674. TimestampQuery: 'timestamp-query',
  48675. IndirectFirstInstance: 'indirect-first-instance',
  48676. ShaderF16: 'shader-f16',
  48677. RG11B10UFloat: 'rg11b10ufloat-renderable',
  48678. BGRA8UNormStorage: 'bgra8unorm-storage',
  48679. Float32Filterable: 'float32-filterable',
  48680. Float32Blendable: 'float32-blendable',
  48681. ClipDistances: 'clip-distances',
  48682. DualSourceBlending: 'dual-source-blending',
  48683. Subgroups: 'subgroups',
  48684. TextureFormatsTier1: 'texture-formats-tier1',
  48685. TextureFormatsTier2: 'texture-formats-tier2'
  48686. };
  48687. const GPUFeatureMap = {
  48688. 'texture-compression-s3tc': 'texture-compression-bc',
  48689. 'texture-compression-etc1': 'texture-compression-etc2'
  48690. };
  48691. /**
  48692. * A special form of sampler binding type.
  48693. * It's texture value is managed by a node object.
  48694. *
  48695. * @private
  48696. * @augments Sampler
  48697. */
  48698. class NodeSampler extends Sampler {
  48699. /**
  48700. * Constructs a new node-based sampler.
  48701. *
  48702. * @param {string} name - The samplers's name.
  48703. * @param {TextureNode} textureNode - The texture node.
  48704. * @param {UniformGroupNode} groupNode - The uniform group node.
  48705. */
  48706. constructor( name, textureNode, groupNode ) {
  48707. super( name, textureNode ? textureNode.value : null );
  48708. /**
  48709. * The texture node.
  48710. *
  48711. * @type {TextureNode}
  48712. */
  48713. this.textureNode = textureNode;
  48714. /**
  48715. * The uniform group node.
  48716. *
  48717. * @type {UniformGroupNode}
  48718. */
  48719. this.groupNode = groupNode;
  48720. }
  48721. /**
  48722. * Updates the texture value of this sampler.
  48723. *
  48724. * @return {boolean} Whether the sampler needs an update or not.
  48725. */
  48726. update() {
  48727. const { textureNode } = this;
  48728. if ( this.texture !== textureNode.value ) {
  48729. this.texture = textureNode.value;
  48730. return true;
  48731. }
  48732. return super.update();
  48733. }
  48734. }
  48735. /**
  48736. * Represents a storage buffer binding type.
  48737. *
  48738. * @private
  48739. * @augments Buffer
  48740. */
  48741. class StorageBuffer extends Buffer {
  48742. /**
  48743. * Constructs a new uniform buffer.
  48744. *
  48745. * @param {string} name - The buffer's name.
  48746. * @param {BufferAttribute} attribute - The buffer attribute.
  48747. */
  48748. constructor( name, attribute ) {
  48749. super( name, attribute ? attribute.array : null );
  48750. /**
  48751. * This flag can be used for type testing.
  48752. *
  48753. * @type {BufferAttribute}
  48754. */
  48755. this.attribute = attribute;
  48756. /**
  48757. * This flag can be used for type testing.
  48758. *
  48759. * @type {boolean}
  48760. * @readonly
  48761. * @default true
  48762. */
  48763. this.isStorageBuffer = true;
  48764. }
  48765. }
  48766. let _id = 0;
  48767. /**
  48768. * A special form of storage buffer binding type.
  48769. * It's buffer value is managed by a node object.
  48770. *
  48771. * @private
  48772. * @augments StorageBuffer
  48773. */
  48774. class NodeStorageBuffer extends StorageBuffer {
  48775. /**
  48776. * Constructs a new node-based storage buffer.
  48777. *
  48778. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  48779. * @param {UniformGroupNode} groupNode - The uniform group node.
  48780. */
  48781. constructor( nodeUniform, groupNode ) {
  48782. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  48783. /**
  48784. * The node uniform.
  48785. *
  48786. * @type {StorageBufferNode}
  48787. */
  48788. this.nodeUniform = nodeUniform;
  48789. /**
  48790. * The access type.
  48791. *
  48792. * @type {string}
  48793. */
  48794. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  48795. /**
  48796. * The uniform group node.
  48797. *
  48798. * @type {UniformGroupNode}
  48799. */
  48800. this.groupNode = groupNode;
  48801. }
  48802. /**
  48803. * The storage buffer.
  48804. *
  48805. * @type {BufferAttribute}
  48806. */
  48807. get buffer() {
  48808. return this.nodeUniform.value;
  48809. }
  48810. }
  48811. /**
  48812. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  48813. *
  48814. * @private
  48815. */
  48816. class WebGPUTexturePassUtils extends DataMap {
  48817. /**
  48818. * Constructs a new utility object.
  48819. *
  48820. * @param {GPUDevice} device - The WebGPU device.
  48821. */
  48822. constructor( device ) {
  48823. super();
  48824. /**
  48825. * The WebGPU device.
  48826. *
  48827. * @type {GPUDevice}
  48828. */
  48829. this.device = device;
  48830. const mipmapVertexSource = `
  48831. struct VarysStruct {
  48832. @builtin( position ) Position: vec4<f32>,
  48833. @location( 0 ) vTex : vec2<f32>
  48834. };
  48835. @vertex
  48836. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  48837. var Varys : VarysStruct;
  48838. var pos = array< vec2<f32>, 4 >(
  48839. vec2<f32>( -1.0, 1.0 ),
  48840. vec2<f32>( 1.0, 1.0 ),
  48841. vec2<f32>( -1.0, -1.0 ),
  48842. vec2<f32>( 1.0, -1.0 )
  48843. );
  48844. var tex = array< vec2<f32>, 4 >(
  48845. vec2<f32>( 0.0, 0.0 ),
  48846. vec2<f32>( 1.0, 0.0 ),
  48847. vec2<f32>( 0.0, 1.0 ),
  48848. vec2<f32>( 1.0, 1.0 )
  48849. );
  48850. Varys.vTex = tex[ vertexIndex ];
  48851. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  48852. return Varys;
  48853. }
  48854. `;
  48855. const mipmapFragmentSource = `
  48856. @group( 0 ) @binding( 0 )
  48857. var imgSampler : sampler;
  48858. @group( 0 ) @binding( 1 )
  48859. var img : texture_2d<f32>;
  48860. @fragment
  48861. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  48862. return textureSample( img, imgSampler, vTex );
  48863. }
  48864. `;
  48865. const flipYFragmentSource = `
  48866. @group( 0 ) @binding( 0 )
  48867. var imgSampler : sampler;
  48868. @group( 0 ) @binding( 1 )
  48869. var img : texture_2d<f32>;
  48870. @fragment
  48871. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  48872. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  48873. }
  48874. `;
  48875. /**
  48876. * The mipmap GPU sampler.
  48877. *
  48878. * @type {GPUSampler}
  48879. */
  48880. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  48881. /**
  48882. * The flipY GPU sampler.
  48883. *
  48884. * @type {GPUSampler}
  48885. */
  48886. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  48887. /**
  48888. * A cache for GPU render pipelines used for copy/transfer passes.
  48889. * Every texture format requires a unique pipeline.
  48890. *
  48891. * @type {Object<string,GPURenderPipeline>}
  48892. */
  48893. this.transferPipelines = {};
  48894. /**
  48895. * A cache for GPU render pipelines used for flipY passes.
  48896. * Every texture format requires a unique pipeline.
  48897. *
  48898. * @type {Object<string,GPURenderPipeline>}
  48899. */
  48900. this.flipYPipelines = {};
  48901. /**
  48902. * The mipmap vertex shader module.
  48903. *
  48904. * @type {GPUShaderModule}
  48905. */
  48906. this.mipmapVertexShaderModule = device.createShaderModule( {
  48907. label: 'mipmapVertex',
  48908. code: mipmapVertexSource
  48909. } );
  48910. /**
  48911. * The mipmap fragment shader module.
  48912. *
  48913. * @type {GPUShaderModule}
  48914. */
  48915. this.mipmapFragmentShaderModule = device.createShaderModule( {
  48916. label: 'mipmapFragment',
  48917. code: mipmapFragmentSource
  48918. } );
  48919. /**
  48920. * The flipY fragment shader module.
  48921. *
  48922. * @type {GPUShaderModule}
  48923. */
  48924. this.flipYFragmentShaderModule = device.createShaderModule( {
  48925. label: 'flipYFragment',
  48926. code: flipYFragmentSource
  48927. } );
  48928. }
  48929. /**
  48930. * Returns a render pipeline for the internal copy render pass. The pass
  48931. * requires a unique render pipeline for each texture format.
  48932. *
  48933. * @param {string} format - The GPU texture format
  48934. * @return {GPURenderPipeline} The GPU render pipeline.
  48935. */
  48936. getTransferPipeline( format ) {
  48937. let pipeline = this.transferPipelines[ format ];
  48938. if ( pipeline === undefined ) {
  48939. pipeline = this.device.createRenderPipeline( {
  48940. label: `mipmap-${ format }`,
  48941. vertex: {
  48942. module: this.mipmapVertexShaderModule,
  48943. entryPoint: 'main'
  48944. },
  48945. fragment: {
  48946. module: this.mipmapFragmentShaderModule,
  48947. entryPoint: 'main',
  48948. targets: [ { format } ]
  48949. },
  48950. primitive: {
  48951. topology: GPUPrimitiveTopology.TriangleStrip,
  48952. stripIndexFormat: GPUIndexFormat.Uint32
  48953. },
  48954. layout: 'auto'
  48955. } );
  48956. this.transferPipelines[ format ] = pipeline;
  48957. }
  48958. return pipeline;
  48959. }
  48960. /**
  48961. * Returns a render pipeline for the flipY render pass. The pass
  48962. * requires a unique render pipeline for each texture format.
  48963. *
  48964. * @param {string} format - The GPU texture format
  48965. * @return {GPURenderPipeline} The GPU render pipeline.
  48966. */
  48967. getFlipYPipeline( format ) {
  48968. let pipeline = this.flipYPipelines[ format ];
  48969. if ( pipeline === undefined ) {
  48970. pipeline = this.device.createRenderPipeline( {
  48971. label: `flipY-${ format }`,
  48972. vertex: {
  48973. module: this.mipmapVertexShaderModule,
  48974. entryPoint: 'main'
  48975. },
  48976. fragment: {
  48977. module: this.flipYFragmentShaderModule,
  48978. entryPoint: 'main',
  48979. targets: [ { format } ]
  48980. },
  48981. primitive: {
  48982. topology: GPUPrimitiveTopology.TriangleStrip,
  48983. stripIndexFormat: GPUIndexFormat.Uint32
  48984. },
  48985. layout: 'auto'
  48986. } );
  48987. this.flipYPipelines[ format ] = pipeline;
  48988. }
  48989. return pipeline;
  48990. }
  48991. /**
  48992. * Flip the contents of the given GPU texture along its vertical axis.
  48993. *
  48994. * @param {GPUTexture} textureGPU - The GPU texture object.
  48995. * @param {Object} textureGPUDescriptor - The texture descriptor.
  48996. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  48997. */
  48998. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  48999. const format = textureGPUDescriptor.format;
  49000. const { width, height } = textureGPUDescriptor.size;
  49001. const transferPipeline = this.getTransferPipeline( format );
  49002. const flipYPipeline = this.getFlipYPipeline( format );
  49003. const tempTexture = this.device.createTexture( {
  49004. size: { width, height, depthOrArrayLayers: 1 },
  49005. format,
  49006. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  49007. } );
  49008. const srcView = textureGPU.createView( {
  49009. baseMipLevel: 0,
  49010. mipLevelCount: 1,
  49011. dimension: GPUTextureViewDimension.TwoD,
  49012. baseArrayLayer
  49013. } );
  49014. const dstView = tempTexture.createView( {
  49015. baseMipLevel: 0,
  49016. mipLevelCount: 1,
  49017. dimension: GPUTextureViewDimension.TwoD,
  49018. baseArrayLayer: 0
  49019. } );
  49020. const commandEncoder = this.device.createCommandEncoder( {} );
  49021. const pass = ( pipeline, sourceView, destinationView ) => {
  49022. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  49023. const bindGroup = this.device.createBindGroup( {
  49024. layout: bindGroupLayout,
  49025. entries: [ {
  49026. binding: 0,
  49027. resource: this.flipYSampler
  49028. }, {
  49029. binding: 1,
  49030. resource: sourceView
  49031. } ]
  49032. } );
  49033. const passEncoder = commandEncoder.beginRenderPass( {
  49034. colorAttachments: [ {
  49035. view: destinationView,
  49036. loadOp: GPULoadOp.Clear,
  49037. storeOp: GPUStoreOp.Store,
  49038. clearValue: [ 0, 0, 0, 0 ]
  49039. } ]
  49040. } );
  49041. passEncoder.setPipeline( pipeline );
  49042. passEncoder.setBindGroup( 0, bindGroup );
  49043. passEncoder.draw( 4, 1, 0, 0 );
  49044. passEncoder.end();
  49045. };
  49046. pass( transferPipeline, srcView, dstView );
  49047. pass( flipYPipeline, dstView, srcView );
  49048. this.device.queue.submit( [ commandEncoder.finish() ] );
  49049. tempTexture.destroy();
  49050. }
  49051. /**
  49052. * Generates mipmaps for the given GPU texture.
  49053. *
  49054. * @param {GPUTexture} textureGPU - The GPU texture object.
  49055. * @param {Object} textureGPUDescriptor - The texture descriptor.
  49056. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  49057. */
  49058. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  49059. const textureData = this.get( textureGPU );
  49060. if ( textureData.useCount === undefined ) {
  49061. textureData.useCount = 0;
  49062. textureData.layers = [];
  49063. }
  49064. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  49065. const commandEncoder = this.device.createCommandEncoder( {} );
  49066. this._mipmapRunBundles( commandEncoder, passes );
  49067. this.device.queue.submit( [ commandEncoder.finish() ] );
  49068. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  49069. textureData.useCount ++;
  49070. }
  49071. /**
  49072. * Since multiple copy render passes are required to generate mipmaps, the passes
  49073. * are managed as render bundles to improve performance.
  49074. *
  49075. * @param {GPUTexture} textureGPU - The GPU texture object.
  49076. * @param {Object} textureGPUDescriptor - The texture descriptor.
  49077. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  49078. * @return {Array<Object>} An array of render bundles.
  49079. */
  49080. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  49081. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  49082. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  49083. let srcView = textureGPU.createView( {
  49084. baseMipLevel: 0,
  49085. mipLevelCount: 1,
  49086. dimension: GPUTextureViewDimension.TwoD,
  49087. baseArrayLayer
  49088. } );
  49089. const passes = [];
  49090. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  49091. const bindGroup = this.device.createBindGroup( {
  49092. layout: bindGroupLayout,
  49093. entries: [ {
  49094. binding: 0,
  49095. resource: this.mipmapSampler
  49096. }, {
  49097. binding: 1,
  49098. resource: srcView
  49099. } ]
  49100. } );
  49101. const dstView = textureGPU.createView( {
  49102. baseMipLevel: i,
  49103. mipLevelCount: 1,
  49104. dimension: GPUTextureViewDimension.TwoD,
  49105. baseArrayLayer
  49106. } );
  49107. const passDescriptor = {
  49108. colorAttachments: [ {
  49109. view: dstView,
  49110. loadOp: GPULoadOp.Clear,
  49111. storeOp: GPUStoreOp.Store,
  49112. clearValue: [ 0, 0, 0, 0 ]
  49113. } ]
  49114. };
  49115. const passEncoder = this.device.createRenderBundleEncoder( {
  49116. colorFormats: [ textureGPUDescriptor.format ]
  49117. } );
  49118. passEncoder.setPipeline( pipeline );
  49119. passEncoder.setBindGroup( 0, bindGroup );
  49120. passEncoder.draw( 4, 1, 0, 0 );
  49121. passes.push( {
  49122. renderBundles: [ passEncoder.finish() ],
  49123. passDescriptor
  49124. } );
  49125. srcView = dstView;
  49126. }
  49127. return passes;
  49128. }
  49129. /**
  49130. * Executes the render bundles.
  49131. *
  49132. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  49133. * @param {Array<Object>} passes - An array of render bundles.
  49134. */
  49135. _mipmapRunBundles( commandEncoder, passes ) {
  49136. const levels = passes.length;
  49137. for ( let i = 0; i < levels; i ++ ) {
  49138. const pass = passes[ i ];
  49139. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  49140. passEncoder.executeBundles( pass.renderBundles );
  49141. passEncoder.end();
  49142. }
  49143. }
  49144. }
  49145. const _compareToWebGPU = {
  49146. [ NeverCompare ]: 'never',
  49147. [ LessCompare ]: 'less',
  49148. [ EqualCompare ]: 'equal',
  49149. [ LessEqualCompare ]: 'less-equal',
  49150. [ GreaterCompare ]: 'greater',
  49151. [ GreaterEqualCompare ]: 'greater-equal',
  49152. [ AlwaysCompare ]: 'always',
  49153. [ NotEqualCompare ]: 'not-equal'
  49154. };
  49155. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  49156. /**
  49157. * A WebGPU backend utility module for managing textures.
  49158. *
  49159. * @private
  49160. */
  49161. class WebGPUTextureUtils {
  49162. /**
  49163. * Constructs a new utility object.
  49164. *
  49165. * @param {WebGPUBackend} backend - The WebGPU backend.
  49166. */
  49167. constructor( backend ) {
  49168. /**
  49169. * A reference to the WebGPU backend.
  49170. *
  49171. * @type {WebGPUBackend}
  49172. */
  49173. this.backend = backend;
  49174. /**
  49175. * A reference to the pass utils.
  49176. *
  49177. * @type {?WebGPUTexturePassUtils}
  49178. * @default null
  49179. */
  49180. this._passUtils = null;
  49181. /**
  49182. * A dictionary for managing default textures. The key
  49183. * is the texture format, the value the texture object.
  49184. *
  49185. * @type {Object<string,Texture>}
  49186. */
  49187. this.defaultTexture = {};
  49188. /**
  49189. * A dictionary for managing default cube textures. The key
  49190. * is the texture format, the value the texture object.
  49191. *
  49192. * @type {Object<string,CubeTexture>}
  49193. */
  49194. this.defaultCubeTexture = {};
  49195. /**
  49196. * A default video frame.
  49197. *
  49198. * @type {?VideoFrame}
  49199. * @default null
  49200. */
  49201. this.defaultVideoFrame = null;
  49202. /**
  49203. * A cache of shared texture samplers.
  49204. *
  49205. * @type {Map<string, Object>}
  49206. */
  49207. this._samplerCache = new Map();
  49208. }
  49209. /**
  49210. * Creates a GPU sampler for the given texture.
  49211. *
  49212. * @param {Texture} texture - The texture to create the sampler for.
  49213. * @return {string} The current sampler key.
  49214. */
  49215. updateSampler( texture ) {
  49216. const backend = this.backend;
  49217. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  49218. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  49219. texture.anisotropy + '-' + ( texture.compareFunction || 0 );
  49220. let samplerData = this._samplerCache.get( samplerKey );
  49221. if ( samplerData === undefined ) {
  49222. const samplerDescriptorGPU = {
  49223. addressModeU: this._convertAddressMode( texture.wrapS ),
  49224. addressModeV: this._convertAddressMode( texture.wrapT ),
  49225. addressModeW: this._convertAddressMode( texture.wrapR ),
  49226. magFilter: this._convertFilterMode( texture.magFilter ),
  49227. minFilter: this._convertFilterMode( texture.minFilter ),
  49228. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  49229. maxAnisotropy: 1
  49230. };
  49231. // anisotropy can only be used when all filter modes are set to linear.
  49232. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  49233. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  49234. }
  49235. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  49236. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  49237. }
  49238. const sampler = backend.device.createSampler( samplerDescriptorGPU );
  49239. samplerData = { sampler, usedTimes: 0 };
  49240. this._samplerCache.set( samplerKey, samplerData );
  49241. }
  49242. const textureData = backend.get( texture );
  49243. if ( textureData.sampler !== samplerData.sampler ) {
  49244. // check if previous sampler is unused so it can be deleted
  49245. if ( textureData.sampler !== undefined ) {
  49246. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  49247. oldSamplerData.usedTimes --;
  49248. if ( oldSamplerData.usedTimes === 0 ) {
  49249. this._samplerCache.delete( textureData.samplerKey );
  49250. }
  49251. }
  49252. // update to new sampler data
  49253. textureData.samplerKey = samplerKey;
  49254. textureData.sampler = samplerData.sampler;
  49255. samplerData.usedTimes ++;
  49256. }
  49257. return samplerKey;
  49258. }
  49259. /**
  49260. * Creates a default texture for the given texture that can be used
  49261. * as a placeholder until the actual texture is ready for usage.
  49262. *
  49263. * @param {Texture} texture - The texture to create a default texture for.
  49264. */
  49265. createDefaultTexture( texture ) {
  49266. let textureGPU;
  49267. const format = getFormat( texture );
  49268. if ( texture.isCubeTexture ) {
  49269. textureGPU = this._getDefaultCubeTextureGPU( format );
  49270. } else {
  49271. textureGPU = this._getDefaultTextureGPU( format );
  49272. }
  49273. this.backend.get( texture ).texture = textureGPU;
  49274. }
  49275. /**
  49276. * Defines a texture on the GPU for the given texture object.
  49277. *
  49278. * @param {Texture} texture - The texture.
  49279. * @param {Object} [options={}] - Optional configuration parameter.
  49280. */
  49281. createTexture( texture, options = {} ) {
  49282. const backend = this.backend;
  49283. const textureData = backend.get( texture );
  49284. if ( textureData.initialized ) {
  49285. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  49286. }
  49287. if ( texture.isExternalTexture ) {
  49288. textureData.texture = texture.sourceTexture;
  49289. textureData.initialized = true;
  49290. return;
  49291. }
  49292. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  49293. if ( options.levels === undefined ) options.levels = 1;
  49294. if ( options.depth === undefined ) options.depth = 1;
  49295. const { width, height, depth, levels } = options;
  49296. if ( texture.isFramebufferTexture ) {
  49297. if ( options.renderTarget ) {
  49298. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  49299. } else {
  49300. options.format = this.backend.utils.getPreferredCanvasFormat();
  49301. }
  49302. }
  49303. const dimension = this._getDimension( texture );
  49304. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  49305. textureData.format = format;
  49306. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  49307. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  49308. if ( texture.isStorageTexture === true ) {
  49309. usage |= GPUTextureUsage.STORAGE_BINDING;
  49310. }
  49311. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  49312. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  49313. }
  49314. const textureDescriptorGPU = {
  49315. label: texture.name,
  49316. size: {
  49317. width: width,
  49318. height: height,
  49319. depthOrArrayLayers: depth,
  49320. },
  49321. mipLevelCount: levels,
  49322. sampleCount: primarySamples,
  49323. dimension: dimension,
  49324. format: format,
  49325. usage: usage
  49326. };
  49327. // texture creation
  49328. if ( format === undefined ) {
  49329. warn( 'WebGPURenderer: Texture format not supported.' );
  49330. this.createDefaultTexture( texture );
  49331. return;
  49332. }
  49333. if ( texture.isCubeTexture ) {
  49334. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  49335. }
  49336. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  49337. if ( isMSAA ) {
  49338. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  49339. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  49340. msaaTextureDescriptorGPU.sampleCount = samples;
  49341. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  49342. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  49343. }
  49344. textureData.initialized = true;
  49345. textureData.textureDescriptorGPU = textureDescriptorGPU;
  49346. }
  49347. /**
  49348. * Destroys the GPU data for the given texture object.
  49349. *
  49350. * @param {Texture} texture - The texture.
  49351. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  49352. */
  49353. destroyTexture( texture, isDefaultTexture = false ) {
  49354. const backend = this.backend;
  49355. const textureData = backend.get( texture );
  49356. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  49357. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  49358. backend.delete( texture );
  49359. }
  49360. /**
  49361. * Generates mipmaps for the given texture.
  49362. *
  49363. * @param {Texture} texture - The texture.
  49364. */
  49365. generateMipmaps( texture ) {
  49366. const textureData = this.backend.get( texture );
  49367. if ( texture.isCubeTexture ) {
  49368. for ( let i = 0; i < 6; i ++ ) {
  49369. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  49370. }
  49371. } else {
  49372. const depth = texture.image.depth || 1;
  49373. for ( let i = 0; i < depth; i ++ ) {
  49374. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  49375. }
  49376. }
  49377. }
  49378. /**
  49379. * Returns the color buffer representing the color
  49380. * attachment of the default framebuffer.
  49381. *
  49382. * @return {GPUTexture} The color buffer.
  49383. */
  49384. getColorBuffer() {
  49385. const backend = this.backend;
  49386. const canvasTarget = backend.renderer.getCanvasTarget();
  49387. const { width, height } = backend.getDrawingBufferSize();
  49388. const samples = backend.renderer.currentSamples;
  49389. const colorTexture = canvasTarget.colorTexture;
  49390. const colorTextureData = backend.get( colorTexture );
  49391. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  49392. return colorTextureData.texture;
  49393. }
  49394. // recreate
  49395. let colorBuffer = colorTextureData.texture;
  49396. if ( colorBuffer ) colorBuffer.destroy();
  49397. colorBuffer = backend.device.createTexture( {
  49398. label: 'colorBuffer',
  49399. size: {
  49400. width: width,
  49401. height: height,
  49402. depthOrArrayLayers: 1
  49403. },
  49404. sampleCount: backend.utils.getSampleCount( backend.renderer.currentSamples ),
  49405. format: backend.utils.getPreferredCanvasFormat(),
  49406. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  49407. } );
  49408. //
  49409. colorTexture.source.width = width;
  49410. colorTexture.source.height = height;
  49411. colorTexture.samples = samples;
  49412. colorTextureData.texture = colorBuffer;
  49413. return colorBuffer;
  49414. }
  49415. /**
  49416. * Returns the depth buffer representing the depth
  49417. * attachment of the default framebuffer.
  49418. *
  49419. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  49420. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  49421. * @return {GPUTexture} The depth buffer.
  49422. */
  49423. getDepthBuffer( depth = true, stencil = false ) {
  49424. const backend = this.backend;
  49425. const canvasTarget = backend.renderer.getCanvasTarget();
  49426. const { width, height } = backend.getDrawingBufferSize();
  49427. const samples = backend.renderer.currentSamples;
  49428. const depthTexture = canvasTarget.depthTexture;
  49429. if ( depthTexture.width === width &&
  49430. depthTexture.height === height &&
  49431. depthTexture.samples === samples &&
  49432. depthTexture.depth === depth &&
  49433. depthTexture.stencil === stencil ) {
  49434. return backend.get( depthTexture ).texture;
  49435. }
  49436. //
  49437. const depthTextureGPU = backend.get( depthTexture ).texture;
  49438. let format, type;
  49439. if ( stencil ) {
  49440. format = DepthStencilFormat;
  49441. type = UnsignedInt248Type;
  49442. } else if ( depth ) {
  49443. format = DepthFormat;
  49444. type = UnsignedIntType;
  49445. }
  49446. if ( depthTextureGPU !== undefined ) {
  49447. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  49448. return depthTextureGPU;
  49449. }
  49450. this.destroyTexture( depthTexture );
  49451. }
  49452. // recreate
  49453. depthTexture.name = 'depthBuffer';
  49454. depthTexture.format = format;
  49455. depthTexture.type = type;
  49456. depthTexture.image.width = width;
  49457. depthTexture.image.height = height;
  49458. depthTexture.samples = samples;
  49459. this.createTexture( depthTexture, { width, height } );
  49460. return backend.get( depthTexture ).texture;
  49461. }
  49462. /**
  49463. * Uploads the updated texture data to the GPU.
  49464. *
  49465. * @param {Texture} texture - The texture.
  49466. * @param {Object} [options={}] - Optional configuration parameter.
  49467. */
  49468. updateTexture( texture, options ) {
  49469. const textureData = this.backend.get( texture );
  49470. const mipmaps = texture.mipmaps;
  49471. const { textureDescriptorGPU } = textureData;
  49472. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  49473. return;
  49474. // transfer texture data
  49475. if ( texture.isDataTexture ) {
  49476. if ( mipmaps.length > 0 ) {
  49477. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49478. const mipmap = mipmaps[ i ];
  49479. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  49480. }
  49481. } else {
  49482. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  49483. }
  49484. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  49485. for ( let i = 0; i < options.image.depth; i ++ ) {
  49486. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  49487. }
  49488. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  49489. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  49490. } else if ( texture.isCubeTexture ) {
  49491. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  49492. } else {
  49493. if ( mipmaps.length > 0 ) {
  49494. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49495. const mipmap = mipmaps[ i ];
  49496. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  49497. }
  49498. } else {
  49499. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  49500. }
  49501. }
  49502. //
  49503. textureData.version = texture.version;
  49504. }
  49505. /**
  49506. * Returns texture data as a typed array.
  49507. *
  49508. * @async
  49509. * @param {Texture} texture - The texture to copy.
  49510. * @param {number} x - The x coordinate of the copy origin.
  49511. * @param {number} y - The y coordinate of the copy origin.
  49512. * @param {number} width - The width of the copy.
  49513. * @param {number} height - The height of the copy.
  49514. * @param {number} faceIndex - The face index.
  49515. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49516. */
  49517. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49518. const device = this.backend.device;
  49519. const textureData = this.backend.get( texture );
  49520. const textureGPU = textureData.texture;
  49521. const format = textureData.textureDescriptorGPU.format;
  49522. const bytesPerTexel = this._getBytesPerTexel( format );
  49523. let bytesPerRow = width * bytesPerTexel;
  49524. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  49525. const readBuffer = device.createBuffer(
  49526. {
  49527. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  49528. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  49529. }
  49530. );
  49531. const encoder = device.createCommandEncoder();
  49532. encoder.copyTextureToBuffer(
  49533. {
  49534. texture: textureGPU,
  49535. origin: { x, y, z: faceIndex },
  49536. },
  49537. {
  49538. buffer: readBuffer,
  49539. bytesPerRow: bytesPerRow
  49540. },
  49541. {
  49542. width: width,
  49543. height: height
  49544. }
  49545. );
  49546. const typedArrayType = this._getTypedArrayType( format );
  49547. device.queue.submit( [ encoder.finish() ] );
  49548. await readBuffer.mapAsync( GPUMapMode.READ );
  49549. const buffer = readBuffer.getMappedRange();
  49550. return new typedArrayType( buffer );
  49551. }
  49552. /**
  49553. * Frees all internal resources.
  49554. */
  49555. dispose() {
  49556. this._samplerCache.clear();
  49557. }
  49558. /**
  49559. * Returns the default GPU texture for the given format.
  49560. *
  49561. * @private
  49562. * @param {string} format - The GPU format.
  49563. * @return {GPUTexture} The GPU texture.
  49564. */
  49565. _getDefaultTextureGPU( format ) {
  49566. let defaultTexture = this.defaultTexture[ format ];
  49567. if ( defaultTexture === undefined ) {
  49568. const texture = new Texture();
  49569. texture.minFilter = NearestFilter;
  49570. texture.magFilter = NearestFilter;
  49571. this.createTexture( texture, { width: 1, height: 1, format } );
  49572. this.defaultTexture[ format ] = defaultTexture = texture;
  49573. }
  49574. return this.backend.get( defaultTexture ).texture;
  49575. }
  49576. /**
  49577. * Returns the default GPU cube texture for the given format.
  49578. *
  49579. * @private
  49580. * @param {string} format - The GPU format.
  49581. * @return {GPUTexture} The GPU texture.
  49582. */
  49583. _getDefaultCubeTextureGPU( format ) {
  49584. let defaultCubeTexture = this.defaultTexture[ format ];
  49585. if ( defaultCubeTexture === undefined ) {
  49586. const texture = new CubeTexture();
  49587. texture.minFilter = NearestFilter;
  49588. texture.magFilter = NearestFilter;
  49589. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  49590. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  49591. }
  49592. return this.backend.get( defaultCubeTexture ).texture;
  49593. }
  49594. /**
  49595. * Uploads cube texture image data to the GPU memory.
  49596. *
  49597. * @private
  49598. * @param {CubeTexture} texture - The cube texture.
  49599. * @param {GPUTexture} textureGPU - The GPU texture.
  49600. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49601. */
  49602. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  49603. const images = texture.images;
  49604. const mipmaps = texture.mipmaps;
  49605. for ( let i = 0; i < 6; i ++ ) {
  49606. const image = images[ i ];
  49607. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  49608. if ( image.isDataTexture ) {
  49609. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  49610. } else {
  49611. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  49612. }
  49613. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49614. const mipmap = mipmaps[ j ];
  49615. const image = mipmap.images[ i ];
  49616. if ( image.isDataTexture ) {
  49617. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  49618. } else {
  49619. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  49620. }
  49621. }
  49622. }
  49623. }
  49624. /**
  49625. * Uploads texture image data to the GPU memory.
  49626. *
  49627. * @private
  49628. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  49629. * @param {GPUTexture} textureGPU - The GPU texture.
  49630. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49631. * @param {number} originDepth - The origin depth.
  49632. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  49633. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  49634. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  49635. */
  49636. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  49637. const device = this.backend.device;
  49638. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  49639. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  49640. device.queue.copyExternalImageToTexture(
  49641. {
  49642. source: image,
  49643. flipY: flipY
  49644. }, {
  49645. texture: textureGPU,
  49646. mipLevel: mipLevel,
  49647. origin: { x: 0, y: 0, z: originDepth },
  49648. premultipliedAlpha: premultiplyAlpha
  49649. }, {
  49650. width: width,
  49651. height: height,
  49652. depthOrArrayLayers: 1
  49653. }
  49654. );
  49655. }
  49656. /**
  49657. * Returns the pass utils singleton.
  49658. *
  49659. * @private
  49660. * @return {WebGPUTexturePassUtils} The utils instance.
  49661. */
  49662. _getPassUtils() {
  49663. let passUtils = this._passUtils;
  49664. if ( passUtils === null ) {
  49665. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  49666. }
  49667. return passUtils;
  49668. }
  49669. /**
  49670. * Generates mipmaps for the given GPU texture.
  49671. *
  49672. * @private
  49673. * @param {GPUTexture} textureGPU - The GPU texture object.
  49674. * @param {Object} textureDescriptorGPU - The texture descriptor.
  49675. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  49676. */
  49677. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  49678. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  49679. }
  49680. /**
  49681. * Flip the contents of the given GPU texture along its vertical axis.
  49682. *
  49683. * @private
  49684. * @param {GPUTexture} textureGPU - The GPU texture object.
  49685. * @param {Object} textureDescriptorGPU - The texture descriptor.
  49686. * @param {number} [originDepth=0] - The origin depth.
  49687. */
  49688. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  49689. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  49690. }
  49691. /**
  49692. * Uploads texture buffer data to the GPU memory.
  49693. *
  49694. * @private
  49695. * @param {Object} image - An object defining the image buffer data.
  49696. * @param {GPUTexture} textureGPU - The GPU texture.
  49697. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49698. * @param {number} originDepth - The origin depth.
  49699. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  49700. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  49701. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  49702. */
  49703. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  49704. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  49705. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  49706. const device = this.backend.device;
  49707. const data = image.data;
  49708. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  49709. const bytesPerRow = image.width * bytesPerTexel;
  49710. device.queue.writeTexture(
  49711. {
  49712. texture: textureGPU,
  49713. mipLevel: mipLevel,
  49714. origin: { x: 0, y: 0, z: originDepth }
  49715. },
  49716. data,
  49717. {
  49718. offset: image.width * image.height * bytesPerTexel * depth,
  49719. bytesPerRow
  49720. },
  49721. {
  49722. width: image.width,
  49723. height: image.height,
  49724. depthOrArrayLayers: 1
  49725. } );
  49726. if ( flipY === true ) {
  49727. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  49728. }
  49729. }
  49730. /**
  49731. * Uploads compressed texture data to the GPU memory.
  49732. *
  49733. * @private
  49734. * @param {Array<Object>} mipmaps - An array with mipmap data.
  49735. * @param {GPUTexture} textureGPU - The GPU texture.
  49736. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49737. */
  49738. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  49739. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  49740. const device = this.backend.device;
  49741. const blockData = this._getBlockData( textureDescriptorGPU.format );
  49742. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  49743. for ( let i = 0; i < mipmaps.length; i ++ ) {
  49744. const mipmap = mipmaps[ i ];
  49745. const width = mipmap.width;
  49746. const height = mipmap.height;
  49747. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  49748. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  49749. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  49750. for ( let j = 0; j < depth; j ++ ) {
  49751. device.queue.writeTexture(
  49752. {
  49753. texture: textureGPU,
  49754. mipLevel: i,
  49755. origin: { x: 0, y: 0, z: j }
  49756. },
  49757. mipmap.data,
  49758. {
  49759. offset: j * bytesPerImage,
  49760. bytesPerRow,
  49761. rowsPerImage: Math.ceil( height / blockData.height )
  49762. },
  49763. {
  49764. width: Math.ceil( width / blockData.width ) * blockData.width,
  49765. height: Math.ceil( height / blockData.height ) * blockData.height,
  49766. depthOrArrayLayers: 1
  49767. }
  49768. );
  49769. }
  49770. }
  49771. }
  49772. /**
  49773. * This method is only relevant for compressed texture formats. It returns a block
  49774. * data descriptor for the given GPU compressed texture format.
  49775. *
  49776. * @private
  49777. * @param {string} format - The GPU compressed texture format.
  49778. * @return {Object} The block data descriptor.
  49779. */
  49780. _getBlockData( format ) {
  49781. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  49782. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  49783. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  49784. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  49785. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  49786. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  49787. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  49788. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  49789. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  49790. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  49791. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  49792. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  49793. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  49794. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  49795. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  49796. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  49797. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  49798. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  49799. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  49800. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  49801. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  49802. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  49803. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  49804. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  49805. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  49806. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  49807. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  49808. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  49809. }
  49810. /**
  49811. * Converts the three.js uv wrapping constants to GPU address mode constants.
  49812. *
  49813. * @private
  49814. * @param {number} value - The three.js constant defining a uv wrapping mode.
  49815. * @return {string} The GPU address mode.
  49816. */
  49817. _convertAddressMode( value ) {
  49818. let addressMode = GPUAddressMode.ClampToEdge;
  49819. if ( value === RepeatWrapping ) {
  49820. addressMode = GPUAddressMode.Repeat;
  49821. } else if ( value === MirroredRepeatWrapping ) {
  49822. addressMode = GPUAddressMode.MirrorRepeat;
  49823. }
  49824. return addressMode;
  49825. }
  49826. /**
  49827. * Converts the three.js filter constants to GPU filter constants.
  49828. *
  49829. * @private
  49830. * @param {number} value - The three.js constant defining a filter mode.
  49831. * @return {string} The GPU filter mode.
  49832. */
  49833. _convertFilterMode( value ) {
  49834. let filterMode = GPUFilterMode.Linear;
  49835. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  49836. filterMode = GPUFilterMode.Nearest;
  49837. }
  49838. return filterMode;
  49839. }
  49840. /**
  49841. * Returns the bytes-per-texel value for the given GPU texture format.
  49842. *
  49843. * @private
  49844. * @param {string} format - The GPU texture format.
  49845. * @return {number} The bytes-per-texel.
  49846. */
  49847. _getBytesPerTexel( format ) {
  49848. // 8-bit formats
  49849. if ( format === GPUTextureFormat.R8Unorm ||
  49850. format === GPUTextureFormat.R8Snorm ||
  49851. format === GPUTextureFormat.R8Uint ||
  49852. format === GPUTextureFormat.R8Sint ) return 1;
  49853. // 16-bit formats
  49854. if ( format === GPUTextureFormat.R16Uint ||
  49855. format === GPUTextureFormat.R16Sint ||
  49856. format === GPUTextureFormat.R16Float ||
  49857. format === GPUTextureFormat.RG8Unorm ||
  49858. format === GPUTextureFormat.RG8Snorm ||
  49859. format === GPUTextureFormat.RG8Uint ||
  49860. format === GPUTextureFormat.RG8Sint ) return 2;
  49861. // 32-bit formats
  49862. if ( format === GPUTextureFormat.R32Uint ||
  49863. format === GPUTextureFormat.R32Sint ||
  49864. format === GPUTextureFormat.R32Float ||
  49865. format === GPUTextureFormat.RG16Uint ||
  49866. format === GPUTextureFormat.RG16Sint ||
  49867. format === GPUTextureFormat.RG16Float ||
  49868. format === GPUTextureFormat.RGBA8Unorm ||
  49869. format === GPUTextureFormat.RGBA8UnormSRGB ||
  49870. format === GPUTextureFormat.RGBA8Snorm ||
  49871. format === GPUTextureFormat.RGBA8Uint ||
  49872. format === GPUTextureFormat.RGBA8Sint ||
  49873. format === GPUTextureFormat.BGRA8Unorm ||
  49874. format === GPUTextureFormat.BGRA8UnormSRGB ||
  49875. // Packed 32-bit formats
  49876. format === GPUTextureFormat.RGB9E5UFloat ||
  49877. format === GPUTextureFormat.RGB10A2Unorm ||
  49878. format === GPUTextureFormat.RG11B10UFloat ||
  49879. format === GPUTextureFormat.Depth32Float ||
  49880. format === GPUTextureFormat.Depth24Plus ||
  49881. format === GPUTextureFormat.Depth24PlusStencil8 ||
  49882. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  49883. // 64-bit formats
  49884. if ( format === GPUTextureFormat.RG32Uint ||
  49885. format === GPUTextureFormat.RG32Sint ||
  49886. format === GPUTextureFormat.RG32Float ||
  49887. format === GPUTextureFormat.RGBA16Uint ||
  49888. format === GPUTextureFormat.RGBA16Sint ||
  49889. format === GPUTextureFormat.RGBA16Float ) return 8;
  49890. // 128-bit formats
  49891. if ( format === GPUTextureFormat.RGBA32Uint ||
  49892. format === GPUTextureFormat.RGBA32Sint ||
  49893. format === GPUTextureFormat.RGBA32Float ) return 16;
  49894. }
  49895. /**
  49896. * Returns the corresponding typed array type for the given GPU texture format.
  49897. *
  49898. * @private
  49899. * @param {string} format - The GPU texture format.
  49900. * @return {TypedArray.constructor} The typed array type.
  49901. */
  49902. _getTypedArrayType( format ) {
  49903. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  49904. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  49905. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  49906. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  49907. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  49908. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  49909. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  49910. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  49911. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  49912. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  49913. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  49914. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  49915. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  49916. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  49917. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  49918. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  49919. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  49920. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  49921. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  49922. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  49923. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  49924. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  49925. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  49926. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  49927. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  49928. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  49929. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  49930. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  49931. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  49932. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  49933. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  49934. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  49935. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  49936. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  49937. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  49938. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  49939. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  49940. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  49941. }
  49942. /**
  49943. * Returns the GPU dimensions for the given texture.
  49944. *
  49945. * @private
  49946. * @param {Texture} texture - The texture.
  49947. * @return {string} The GPU dimension.
  49948. */
  49949. _getDimension( texture ) {
  49950. let dimension;
  49951. if ( texture.is3DTexture || texture.isData3DTexture ) {
  49952. dimension = GPUTextureDimension.ThreeD;
  49953. } else {
  49954. dimension = GPUTextureDimension.TwoD;
  49955. }
  49956. return dimension;
  49957. }
  49958. }
  49959. /**
  49960. * Returns the GPU format for the given texture.
  49961. *
  49962. * @param {Texture} texture - The texture.
  49963. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  49964. * It is not necessary to apply the device for most formats.
  49965. * @return {string} The GPU format.
  49966. */
  49967. function getFormat( texture, device = null ) {
  49968. const format = texture.format;
  49969. const type = texture.type;
  49970. const colorSpace = texture.colorSpace;
  49971. const transfer = ColorManagement.getTransfer( colorSpace );
  49972. let formatGPU;
  49973. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  49974. switch ( format ) {
  49975. case RGB_S3TC_DXT1_Format:
  49976. case RGBA_S3TC_DXT1_Format:
  49977. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  49978. break;
  49979. case RGBA_S3TC_DXT3_Format:
  49980. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  49981. break;
  49982. case RGBA_S3TC_DXT5_Format:
  49983. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  49984. break;
  49985. case RED_RGTC1_Format:
  49986. formatGPU = GPUTextureFormat.BC4RUnorm;
  49987. break;
  49988. case SIGNED_RED_RGTC1_Format:
  49989. formatGPU = GPUTextureFormat.BC4RSnorm;
  49990. break;
  49991. case RED_GREEN_RGTC2_Format:
  49992. formatGPU = GPUTextureFormat.BC5RGUnorm;
  49993. break;
  49994. case SIGNED_RED_GREEN_RGTC2_Format:
  49995. formatGPU = GPUTextureFormat.BC5RGSnorm;
  49996. break;
  49997. case RGBA_BPTC_Format:
  49998. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  49999. break;
  50000. case RGB_ETC2_Format:
  50001. case RGB_ETC1_Format:
  50002. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  50003. break;
  50004. case RGBA_ETC2_EAC_Format:
  50005. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  50006. break;
  50007. case RGBA_ASTC_4x4_Format:
  50008. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  50009. break;
  50010. case RGBA_ASTC_5x4_Format:
  50011. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  50012. break;
  50013. case RGBA_ASTC_5x5_Format:
  50014. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  50015. break;
  50016. case RGBA_ASTC_6x5_Format:
  50017. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  50018. break;
  50019. case RGBA_ASTC_6x6_Format:
  50020. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  50021. break;
  50022. case RGBA_ASTC_8x5_Format:
  50023. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  50024. break;
  50025. case RGBA_ASTC_8x6_Format:
  50026. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  50027. break;
  50028. case RGBA_ASTC_8x8_Format:
  50029. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  50030. break;
  50031. case RGBA_ASTC_10x5_Format:
  50032. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  50033. break;
  50034. case RGBA_ASTC_10x6_Format:
  50035. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  50036. break;
  50037. case RGBA_ASTC_10x8_Format:
  50038. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  50039. break;
  50040. case RGBA_ASTC_10x10_Format:
  50041. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  50042. break;
  50043. case RGBA_ASTC_12x10_Format:
  50044. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  50045. break;
  50046. case RGBA_ASTC_12x12_Format:
  50047. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  50048. break;
  50049. case RGBAFormat:
  50050. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  50051. break;
  50052. default:
  50053. error( 'WebGPURenderer: Unsupported texture format.', format );
  50054. }
  50055. } else {
  50056. switch ( format ) {
  50057. case RGBAFormat:
  50058. switch ( type ) {
  50059. case ByteType:
  50060. formatGPU = GPUTextureFormat.RGBA8Snorm;
  50061. break;
  50062. case ShortType:
  50063. formatGPU = GPUTextureFormat.RGBA16Sint;
  50064. break;
  50065. case UnsignedShortType:
  50066. formatGPU = GPUTextureFormat.RGBA16Uint;
  50067. break;
  50068. case UnsignedIntType:
  50069. formatGPU = GPUTextureFormat.RGBA32Uint;
  50070. break;
  50071. case IntType:
  50072. formatGPU = GPUTextureFormat.RGBA32Sint;
  50073. break;
  50074. case UnsignedByteType:
  50075. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  50076. break;
  50077. case HalfFloatType:
  50078. formatGPU = GPUTextureFormat.RGBA16Float;
  50079. break;
  50080. case FloatType:
  50081. formatGPU = GPUTextureFormat.RGBA32Float;
  50082. break;
  50083. default:
  50084. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  50085. }
  50086. break;
  50087. case RGBFormat:
  50088. switch ( type ) {
  50089. case UnsignedInt5999Type:
  50090. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  50091. break;
  50092. case UnsignedInt101111Type:
  50093. formatGPU = GPUTextureFormat.RG11B10UFloat;
  50094. break;
  50095. default:
  50096. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  50097. }
  50098. break;
  50099. case RedFormat:
  50100. switch ( type ) {
  50101. case ByteType:
  50102. formatGPU = GPUTextureFormat.R8Snorm;
  50103. break;
  50104. case ShortType:
  50105. formatGPU = GPUTextureFormat.R16Sint;
  50106. break;
  50107. case UnsignedShortType:
  50108. formatGPU = GPUTextureFormat.R16Uint;
  50109. break;
  50110. case UnsignedIntType:
  50111. formatGPU = GPUTextureFormat.R32Uint;
  50112. break;
  50113. case IntType:
  50114. formatGPU = GPUTextureFormat.R32Sint;
  50115. break;
  50116. case UnsignedByteType:
  50117. formatGPU = GPUTextureFormat.R8Unorm;
  50118. break;
  50119. case HalfFloatType:
  50120. formatGPU = GPUTextureFormat.R16Float;
  50121. break;
  50122. case FloatType:
  50123. formatGPU = GPUTextureFormat.R32Float;
  50124. break;
  50125. default:
  50126. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  50127. }
  50128. break;
  50129. case RGFormat:
  50130. switch ( type ) {
  50131. case ByteType:
  50132. formatGPU = GPUTextureFormat.RG8Snorm;
  50133. break;
  50134. case ShortType:
  50135. formatGPU = GPUTextureFormat.RG16Sint;
  50136. break;
  50137. case UnsignedShortType:
  50138. formatGPU = GPUTextureFormat.RG16Uint;
  50139. break;
  50140. case UnsignedIntType:
  50141. formatGPU = GPUTextureFormat.RG32Uint;
  50142. break;
  50143. case IntType:
  50144. formatGPU = GPUTextureFormat.RG32Sint;
  50145. break;
  50146. case UnsignedByteType:
  50147. formatGPU = GPUTextureFormat.RG8Unorm;
  50148. break;
  50149. case HalfFloatType:
  50150. formatGPU = GPUTextureFormat.RG16Float;
  50151. break;
  50152. case FloatType:
  50153. formatGPU = GPUTextureFormat.RG32Float;
  50154. break;
  50155. default:
  50156. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  50157. }
  50158. break;
  50159. case DepthFormat:
  50160. switch ( type ) {
  50161. case UnsignedShortType:
  50162. formatGPU = GPUTextureFormat.Depth16Unorm;
  50163. break;
  50164. case UnsignedIntType:
  50165. formatGPU = GPUTextureFormat.Depth24Plus;
  50166. break;
  50167. case FloatType:
  50168. formatGPU = GPUTextureFormat.Depth32Float;
  50169. break;
  50170. default:
  50171. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  50172. }
  50173. break;
  50174. case DepthStencilFormat:
  50175. switch ( type ) {
  50176. case UnsignedInt248Type:
  50177. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  50178. break;
  50179. case FloatType:
  50180. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  50181. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  50182. }
  50183. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  50184. break;
  50185. default:
  50186. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  50187. }
  50188. break;
  50189. case RedIntegerFormat:
  50190. switch ( type ) {
  50191. case IntType:
  50192. formatGPU = GPUTextureFormat.R32Sint;
  50193. break;
  50194. case UnsignedIntType:
  50195. formatGPU = GPUTextureFormat.R32Uint;
  50196. break;
  50197. default:
  50198. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  50199. }
  50200. break;
  50201. case RGIntegerFormat:
  50202. switch ( type ) {
  50203. case IntType:
  50204. formatGPU = GPUTextureFormat.RG32Sint;
  50205. break;
  50206. case UnsignedIntType:
  50207. formatGPU = GPUTextureFormat.RG32Uint;
  50208. break;
  50209. default:
  50210. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  50211. }
  50212. break;
  50213. case RGBAIntegerFormat:
  50214. switch ( type ) {
  50215. case IntType:
  50216. formatGPU = GPUTextureFormat.RGBA32Sint;
  50217. break;
  50218. case UnsignedIntType:
  50219. formatGPU = GPUTextureFormat.RGBA32Uint;
  50220. break;
  50221. default:
  50222. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  50223. }
  50224. break;
  50225. default:
  50226. error( 'WebGPURenderer: Unsupported texture format.', format );
  50227. }
  50228. }
  50229. return formatGPU;
  50230. }
  50231. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  50232. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  50233. const wgslTypeLib$1 = {
  50234. 'f32': 'float',
  50235. 'i32': 'int',
  50236. 'u32': 'uint',
  50237. 'bool': 'bool',
  50238. 'vec2<f32>': 'vec2',
  50239. 'vec2<i32>': 'ivec2',
  50240. 'vec2<u32>': 'uvec2',
  50241. 'vec2<bool>': 'bvec2',
  50242. 'vec2f': 'vec2',
  50243. 'vec2i': 'ivec2',
  50244. 'vec2u': 'uvec2',
  50245. 'vec2b': 'bvec2',
  50246. 'vec3<f32>': 'vec3',
  50247. 'vec3<i32>': 'ivec3',
  50248. 'vec3<u32>': 'uvec3',
  50249. 'vec3<bool>': 'bvec3',
  50250. 'vec3f': 'vec3',
  50251. 'vec3i': 'ivec3',
  50252. 'vec3u': 'uvec3',
  50253. 'vec3b': 'bvec3',
  50254. 'vec4<f32>': 'vec4',
  50255. 'vec4<i32>': 'ivec4',
  50256. 'vec4<u32>': 'uvec4',
  50257. 'vec4<bool>': 'bvec4',
  50258. 'vec4f': 'vec4',
  50259. 'vec4i': 'ivec4',
  50260. 'vec4u': 'uvec4',
  50261. 'vec4b': 'bvec4',
  50262. 'mat2x2<f32>': 'mat2',
  50263. 'mat2x2f': 'mat2',
  50264. 'mat3x3<f32>': 'mat3',
  50265. 'mat3x3f': 'mat3',
  50266. 'mat4x4<f32>': 'mat4',
  50267. 'mat4x4f': 'mat4',
  50268. 'sampler': 'sampler',
  50269. 'texture_1d': 'texture',
  50270. 'texture_2d': 'texture',
  50271. 'texture_2d_array': 'texture',
  50272. 'texture_multisampled_2d': 'cubeTexture',
  50273. 'texture_depth_2d': 'depthTexture',
  50274. 'texture_depth_2d_array': 'depthTexture',
  50275. 'texture_depth_multisampled_2d': 'depthTexture',
  50276. 'texture_depth_cube': 'depthTexture',
  50277. 'texture_depth_cube_array': 'depthTexture',
  50278. 'texture_3d': 'texture3D',
  50279. 'texture_cube': 'cubeTexture',
  50280. 'texture_cube_array': 'cubeTexture',
  50281. 'texture_storage_1d': 'storageTexture',
  50282. 'texture_storage_2d': 'storageTexture',
  50283. 'texture_storage_2d_array': 'storageTexture',
  50284. 'texture_storage_3d': 'storageTexture'
  50285. };
  50286. const parse = ( source ) => {
  50287. source = source.trim();
  50288. const declaration = source.match( declarationRegexp );
  50289. if ( declaration !== null && declaration.length === 4 ) {
  50290. const inputsCode = declaration[ 2 ];
  50291. const propsMatches = [];
  50292. let match = null;
  50293. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  50294. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  50295. }
  50296. // Process matches to correctly pair names and types
  50297. const inputs = [];
  50298. for ( let i = 0; i < propsMatches.length; i ++ ) {
  50299. const { name, type } = propsMatches[ i ];
  50300. let resolvedType = type;
  50301. if ( resolvedType.startsWith( 'ptr' ) ) {
  50302. resolvedType = 'pointer';
  50303. } else {
  50304. if ( resolvedType.startsWith( 'texture' ) ) {
  50305. resolvedType = type.split( '<' )[ 0 ];
  50306. }
  50307. resolvedType = wgslTypeLib$1[ resolvedType ];
  50308. }
  50309. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  50310. }
  50311. const blockCode = source.substring( declaration[ 0 ].length );
  50312. const outputType = declaration[ 3 ] || 'void';
  50313. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  50314. const type = wgslTypeLib$1[ outputType ] || outputType;
  50315. return {
  50316. type,
  50317. inputs,
  50318. name,
  50319. inputsCode,
  50320. blockCode,
  50321. outputType
  50322. };
  50323. } else {
  50324. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  50325. }
  50326. };
  50327. /**
  50328. * This class represents a WSL node function.
  50329. *
  50330. * @augments NodeFunction
  50331. */
  50332. class WGSLNodeFunction extends NodeFunction {
  50333. /**
  50334. * Constructs a new WGSL node function.
  50335. *
  50336. * @param {string} source - The WGSL source.
  50337. */
  50338. constructor( source ) {
  50339. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  50340. super( type, inputs, name );
  50341. this.inputsCode = inputsCode;
  50342. this.blockCode = blockCode;
  50343. this.outputType = outputType;
  50344. }
  50345. /**
  50346. * This method returns the WGSL code of the node function.
  50347. *
  50348. * @param {string} [name=this.name] - The function's name.
  50349. * @return {string} The shader code.
  50350. */
  50351. getCode( name = this.name ) {
  50352. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  50353. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  50354. }
  50355. }
  50356. /**
  50357. * A WGSL node parser.
  50358. *
  50359. * @augments NodeParser
  50360. */
  50361. class WGSLNodeParser extends NodeParser {
  50362. /**
  50363. * The method parses the given WGSL code an returns a node function.
  50364. *
  50365. * @param {string} source - The WGSL code.
  50366. * @return {WGSLNodeFunction} A node function.
  50367. */
  50368. parseFunction( source ) {
  50369. return new WGSLNodeFunction( source );
  50370. }
  50371. }
  50372. // GPUShaderStage is not defined in browsers not supporting WebGPU
  50373. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  50374. const accessNames = {
  50375. [ NodeAccess.READ_ONLY ]: 'read',
  50376. [ NodeAccess.WRITE_ONLY ]: 'write',
  50377. [ NodeAccess.READ_WRITE ]: 'read_write'
  50378. };
  50379. const wrapNames = {
  50380. [ RepeatWrapping ]: 'repeat',
  50381. [ ClampToEdgeWrapping ]: 'clamp',
  50382. [ MirroredRepeatWrapping ]: 'mirror'
  50383. };
  50384. const gpuShaderStageLib = {
  50385. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  50386. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  50387. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  50388. };
  50389. const supports = {
  50390. instance: true,
  50391. swizzleAssign: false,
  50392. storageBuffer: true
  50393. };
  50394. const wgslFnOpLib = {
  50395. '^^': 'tsl_xor'
  50396. };
  50397. const wgslTypeLib = {
  50398. float: 'f32',
  50399. int: 'i32',
  50400. uint: 'u32',
  50401. bool: 'bool',
  50402. color: 'vec3<f32>',
  50403. vec2: 'vec2<f32>',
  50404. ivec2: 'vec2<i32>',
  50405. uvec2: 'vec2<u32>',
  50406. bvec2: 'vec2<bool>',
  50407. vec3: 'vec3<f32>',
  50408. ivec3: 'vec3<i32>',
  50409. uvec3: 'vec3<u32>',
  50410. bvec3: 'vec3<bool>',
  50411. vec4: 'vec4<f32>',
  50412. ivec4: 'vec4<i32>',
  50413. uvec4: 'vec4<u32>',
  50414. bvec4: 'vec4<bool>',
  50415. mat2: 'mat2x2<f32>',
  50416. mat3: 'mat3x3<f32>',
  50417. mat4: 'mat4x4<f32>'
  50418. };
  50419. const wgslCodeCache = {};
  50420. const wgslPolyfill = {
  50421. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  50422. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  50423. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  50424. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  50425. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  50426. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  50427. 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 ); }' ),
  50428. 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 ); }' ),
  50429. 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 ); }' ),
  50430. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  50431. 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 ); }' ),
  50432. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  50433. biquadraticTexture: new CodeNode( /* wgsl */`
  50434. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  50435. let res = vec2f( iRes );
  50436. let uvScaled = coord * res;
  50437. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  50438. // https://www.shadertoy.com/view/WtyXRy
  50439. let uv = uvWrapping - 0.5;
  50440. let iuv = floor( uv );
  50441. let f = fract( uv );
  50442. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  50443. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  50444. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  50445. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  50446. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  50447. }
  50448. ` )
  50449. };
  50450. const wgslMethods = {
  50451. dFdx: 'dpdx',
  50452. dFdy: '- dpdy',
  50453. mod_float: 'tsl_mod_float',
  50454. mod_vec2: 'tsl_mod_vec2',
  50455. mod_vec3: 'tsl_mod_vec3',
  50456. mod_vec4: 'tsl_mod_vec4',
  50457. equals_bool: 'tsl_equals_bool',
  50458. equals_bvec2: 'tsl_equals_bvec2',
  50459. equals_bvec3: 'tsl_equals_bvec3',
  50460. equals_bvec4: 'tsl_equals_bvec4',
  50461. inversesqrt: 'inverseSqrt',
  50462. bitcast: 'bitcast<f32>'
  50463. };
  50464. //
  50465. let diagnostics = '';
  50466. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  50467. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  50468. }
  50469. /**
  50470. * A node builder targeting WGSL.
  50471. *
  50472. * This module generates WGSL shader code from node materials and also
  50473. * generates the respective bindings and vertex buffer definitions. These
  50474. * data are later used by the renderer to create render and compute pipelines
  50475. * for render objects.
  50476. *
  50477. * @augments NodeBuilder
  50478. */
  50479. class WGSLNodeBuilder extends NodeBuilder {
  50480. /**
  50481. * Constructs a new WGSL node builder renderer.
  50482. *
  50483. * @param {Object3D} object - The 3D object.
  50484. * @param {Renderer} renderer - The renderer.
  50485. */
  50486. constructor( object, renderer ) {
  50487. super( object, renderer, new WGSLNodeParser() );
  50488. /**
  50489. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  50490. * another dictionary which manages UBOs per group ('render','frame','object').
  50491. *
  50492. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  50493. */
  50494. this.uniformGroups = {};
  50495. /**
  50496. * A dictionary that holds for each shader stage a Map of builtins.
  50497. *
  50498. * @type {Object<string,Map<string,Object>>}
  50499. */
  50500. this.builtins = {};
  50501. /**
  50502. * A dictionary that holds for each shader stage a Set of directives.
  50503. *
  50504. * @type {Object<string,Set<string>>}
  50505. */
  50506. this.directives = {};
  50507. /**
  50508. * A map for managing scope arrays. Only relevant for when using
  50509. * {@link WorkgroupInfoNode} in context of compute shaders.
  50510. *
  50511. * @type {Map<string,Object>}
  50512. */
  50513. this.scopedArrays = new Map();
  50514. }
  50515. /**
  50516. * Generates the WGSL snippet for sampled textures.
  50517. *
  50518. * @private
  50519. * @param {Texture} texture - The texture.
  50520. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50521. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50522. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50523. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50524. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50525. * @return {string} The WGSL snippet.
  50526. */
  50527. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50528. if ( shaderStage === 'fragment' ) {
  50529. if ( depthSnippet ) {
  50530. if ( offsetSnippet ) {
  50531. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  50532. }
  50533. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  50534. } else {
  50535. if ( offsetSnippet ) {
  50536. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  50537. }
  50538. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  50539. }
  50540. } else {
  50541. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  50542. }
  50543. }
  50544. /**
  50545. * Generates the WGSL snippet when sampling textures with explicit mip level.
  50546. *
  50547. * @private
  50548. * @param {Texture} texture - The texture.
  50549. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50550. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50551. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50552. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50553. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50554. * @return {string} The WGSL snippet.
  50555. */
  50556. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  50557. if ( this.isUnfilterable( texture ) === false ) {
  50558. if ( offsetSnippet ) {
  50559. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  50560. }
  50561. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  50562. } else if ( this.isFilteredTexture( texture ) ) {
  50563. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  50564. } else {
  50565. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  50566. }
  50567. }
  50568. /**
  50569. * Generates a wrap function used in context of textures.
  50570. *
  50571. * @param {Texture} texture - The texture to generate the function for.
  50572. * @return {string} The name of the generated function.
  50573. */
  50574. generateWrapFunction( texture ) {
  50575. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  50576. let nodeCode = wgslCodeCache[ functionName ];
  50577. if ( nodeCode === undefined ) {
  50578. const includes = [];
  50579. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  50580. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  50581. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  50582. const addWrapSnippet = ( wrap, axis ) => {
  50583. if ( wrap === RepeatWrapping ) {
  50584. includes.push( wgslPolyfill.repeatWrapping_float );
  50585. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  50586. } else if ( wrap === ClampToEdgeWrapping ) {
  50587. includes.push( wgslPolyfill.clampWrapping_float );
  50588. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  50589. } else if ( wrap === MirroredRepeatWrapping ) {
  50590. includes.push( wgslPolyfill.mirrorWrapping_float );
  50591. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  50592. } else {
  50593. code += `\t\tcoord.${ axis }`;
  50594. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  50595. }
  50596. };
  50597. addWrapSnippet( texture.wrapS, 'x' );
  50598. code += ',\n';
  50599. addWrapSnippet( texture.wrapT, 'y' );
  50600. if ( texture.isData3DTexture ) {
  50601. code += ',\n';
  50602. addWrapSnippet( texture.wrapR, 'z' );
  50603. }
  50604. code += '\n\t);\n\n}\n';
  50605. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  50606. }
  50607. nodeCode.build( this );
  50608. return functionName;
  50609. }
  50610. /**
  50611. * Generates the array declaration string.
  50612. *
  50613. * @param {string} type - The type.
  50614. * @param {?number} [count] - The count.
  50615. * @return {string} The generated value as a shader string.
  50616. */
  50617. generateArrayDeclaration( type, count ) {
  50618. return `array< ${ this.getType( type ) }, ${ count } >`;
  50619. }
  50620. /**
  50621. * Generates a WGSL variable that holds the texture dimension of the given texture.
  50622. * It also returns information about the number of layers (elements) of an arrayed
  50623. * texture as well as the cube face count of cube textures.
  50624. *
  50625. * @param {Texture} texture - The texture to generate the function for.
  50626. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  50627. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50628. * @return {string} The name of the dimension variable.
  50629. */
  50630. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  50631. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  50632. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  50633. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  50634. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  50635. let textureDimensionsParams;
  50636. let dimensionType;
  50637. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  50638. const isMultisampled = primarySamples > 1;
  50639. if ( texture.isData3DTexture ) {
  50640. dimensionType = 'vec3<u32>';
  50641. } else {
  50642. // Regular 2D textures, depth textures, etc.
  50643. dimensionType = 'vec2<u32>';
  50644. }
  50645. // Build parameters string based on texture type and multisampling
  50646. if ( isMultisampled || texture.isStorageTexture ) {
  50647. textureDimensionsParams = textureProperty;
  50648. } else {
  50649. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  50650. }
  50651. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  50652. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  50653. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  50654. textureData.arrayLayerCount = new VarNode(
  50655. new ExpressionNode(
  50656. `textureNumLayers(${textureProperty})`,
  50657. 'u32'
  50658. )
  50659. );
  50660. }
  50661. // For cube textures, we know it's always 6 faces
  50662. if ( texture.isTextureCube ) {
  50663. textureData.cubeFaceCount = new VarNode(
  50664. new ExpressionNode( '6u', 'u32' )
  50665. );
  50666. }
  50667. }
  50668. return textureDimensionNode.build( this );
  50669. }
  50670. /**
  50671. * Generates the WGSL snippet for a manual filtered texture.
  50672. *
  50673. * @param {Texture} texture - The texture.
  50674. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50675. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50676. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50677. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50678. * @return {string} The WGSL snippet.
  50679. */
  50680. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  50681. this._include( 'biquadraticTexture' );
  50682. const wrapFunction = this.generateWrapFunction( texture );
  50683. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  50684. if ( offsetSnippet ) {
  50685. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  50686. }
  50687. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  50688. }
  50689. /**
  50690. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  50691. * Since it's a lookup, no sampling or filtering is applied.
  50692. *
  50693. * @param {Texture} texture - The texture.
  50694. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50695. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50696. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50697. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50698. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50699. * @return {string} The WGSL snippet.
  50700. */
  50701. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  50702. const wrapFunction = this.generateWrapFunction( texture );
  50703. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  50704. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  50705. if ( offsetSnippet ) {
  50706. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  50707. }
  50708. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  50709. return this.generateTextureLoad( texture, textureProperty, coordSnippet, levelSnippet, depthSnippet, null );
  50710. }
  50711. /**
  50712. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  50713. *
  50714. * @param {Texture} texture - The texture.
  50715. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50716. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50717. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50718. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50719. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50720. * @return {string} The WGSL snippet.
  50721. */
  50722. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  50723. if ( levelSnippet === null ) levelSnippet = '0u';
  50724. if ( offsetSnippet ) {
  50725. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  50726. }
  50727. let snippet;
  50728. if ( depthSnippet ) {
  50729. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  50730. } else {
  50731. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  50732. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  50733. snippet += '.x';
  50734. }
  50735. }
  50736. return snippet;
  50737. }
  50738. /**
  50739. * Generates the WGSL snippet that writes a single texel to a texture.
  50740. *
  50741. * @param {Texture} texture - The texture.
  50742. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50743. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50744. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50745. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  50746. * @return {string} The WGSL snippet.
  50747. */
  50748. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  50749. let snippet;
  50750. if ( depthSnippet ) {
  50751. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  50752. } else {
  50753. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  50754. }
  50755. return snippet;
  50756. }
  50757. /**
  50758. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  50759. *
  50760. * @param {Texture} texture - The texture.
  50761. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  50762. */
  50763. isSampleCompare( texture ) {
  50764. return texture.isDepthTexture === true && texture.compareFunction !== null;
  50765. }
  50766. /**
  50767. * Returns `true` if the given texture is unfilterable.
  50768. *
  50769. * @param {Texture} texture - The texture.
  50770. * @return {boolean} Whether the given texture is unfilterable or not.
  50771. */
  50772. isUnfilterable( texture ) {
  50773. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  50774. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  50775. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  50776. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  50777. }
  50778. /**
  50779. * Generates the WGSL snippet for sampling/loading the given texture.
  50780. *
  50781. * @param {Texture} texture - The texture.
  50782. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50783. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50784. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50785. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50786. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50787. * @return {string} The WGSL snippet.
  50788. */
  50789. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50790. let snippet = null;
  50791. if ( this.isUnfilterable( texture ) ) {
  50792. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  50793. } else {
  50794. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  50795. }
  50796. return snippet;
  50797. }
  50798. /**
  50799. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  50800. *
  50801. * @param {Texture} texture - The texture.
  50802. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50803. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50804. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  50805. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50806. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50807. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50808. * @return {string} The WGSL snippet.
  50809. */
  50810. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50811. if ( shaderStage === 'fragment' ) {
  50812. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  50813. if ( offsetSnippet ) {
  50814. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  50815. }
  50816. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  50817. } else {
  50818. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  50819. }
  50820. }
  50821. /**
  50822. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  50823. * against a reference value.
  50824. *
  50825. * @param {Texture} texture - The texture.
  50826. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50827. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50828. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  50829. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50830. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50831. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50832. * @return {string} The WGSL snippet.
  50833. */
  50834. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50835. if ( shaderStage === 'fragment' ) {
  50836. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  50837. if ( offsetSnippet ) {
  50838. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  50839. }
  50840. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  50841. }
  50842. if ( offsetSnippet ) {
  50843. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  50844. }
  50845. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  50846. } else {
  50847. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  50848. }
  50849. }
  50850. /**
  50851. * Generates the WGSL snippet when sampling textures with explicit mip level.
  50852. *
  50853. * @param {Texture} texture - The texture.
  50854. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50855. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50856. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50857. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50858. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50859. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50860. * @return {string} The WGSL snippet.
  50861. */
  50862. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  50863. if ( this.isUnfilterable( texture ) === false ) {
  50864. if ( offsetSnippet ) {
  50865. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  50866. }
  50867. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  50868. } else if ( this.isFilteredTexture( texture ) ) {
  50869. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  50870. } else {
  50871. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  50872. }
  50873. }
  50874. /**
  50875. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  50876. *
  50877. * @param {Texture} texture - The texture.
  50878. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50879. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50880. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  50881. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50882. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50883. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50884. * @return {string} The WGSL snippet.
  50885. */
  50886. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50887. if ( shaderStage === 'fragment' ) {
  50888. if ( offsetSnippet ) {
  50889. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  50890. }
  50891. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  50892. } else {
  50893. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  50894. }
  50895. }
  50896. /**
  50897. * Returns a WGSL snippet that represents the property name of the given node.
  50898. *
  50899. * @param {Node} node - The node.
  50900. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50901. * @return {string} The property name.
  50902. */
  50903. getPropertyName( node, shaderStage = this.shaderStage ) {
  50904. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  50905. if ( shaderStage === 'vertex' ) {
  50906. return `varyings.${ node.name }`;
  50907. }
  50908. } else if ( node.isNodeUniform === true ) {
  50909. const name = node.name;
  50910. const type = node.type;
  50911. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  50912. return name;
  50913. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  50914. if ( this.isCustomStruct( node ) ) {
  50915. return name;
  50916. }
  50917. return name + '.value';
  50918. } else {
  50919. return node.groupNode.name + '.' + name;
  50920. }
  50921. }
  50922. return super.getPropertyName( node );
  50923. }
  50924. /**
  50925. * Returns the output struct name.
  50926. *
  50927. * @return {string} The name of the output struct.
  50928. */
  50929. getOutputStructName() {
  50930. return 'output';
  50931. }
  50932. /**
  50933. * Returns the native shader operator name for a given generic name.
  50934. *
  50935. * @param {string} op - The operator name to resolve.
  50936. * @return {?string} The resolved operator name.
  50937. */
  50938. getFunctionOperator( op ) {
  50939. const fnOp = wgslFnOpLib[ op ];
  50940. if ( fnOp !== undefined ) {
  50941. this._include( fnOp );
  50942. return fnOp;
  50943. }
  50944. return null;
  50945. }
  50946. /**
  50947. * Returns the node access for the given node and shader stage.
  50948. *
  50949. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  50950. * @param {string} shaderStage - The shader stage.
  50951. * @return {string} The node access.
  50952. */
  50953. getNodeAccess( node, shaderStage ) {
  50954. if ( shaderStage !== 'compute' ) {
  50955. if ( node.isAtomic === true ) {
  50956. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  50957. return NodeAccess.READ_WRITE;
  50958. }
  50959. return NodeAccess.READ_ONLY;
  50960. }
  50961. return node.access;
  50962. }
  50963. /**
  50964. * Returns A WGSL snippet representing the storage access.
  50965. *
  50966. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  50967. * @param {string} shaderStage - The shader stage.
  50968. * @return {string} The WGSL snippet representing the storage access.
  50969. */
  50970. getStorageAccess( node, shaderStage ) {
  50971. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  50972. }
  50973. /**
  50974. * This method is one of the more important ones since it's responsible
  50975. * for generating a matching binding instance for the given uniform node.
  50976. *
  50977. * These bindings are later used in the renderer to create bind groups
  50978. * and layouts.
  50979. *
  50980. * @param {UniformNode} node - The uniform node.
  50981. * @param {string} type - The node data type.
  50982. * @param {string} shaderStage - The shader stage.
  50983. * @param {?string} [name=null] - An optional uniform name.
  50984. * @return {NodeUniform} The node uniform object.
  50985. */
  50986. getUniformFromNode( node, type, shaderStage, name = null ) {
  50987. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  50988. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  50989. if ( nodeData.uniformGPU === undefined ) {
  50990. let uniformGPU;
  50991. const group = node.groupNode;
  50992. const groupName = group.name;
  50993. const bindings = this.getBindGroupArray( groupName, shaderStage );
  50994. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  50995. let texture = null;
  50996. const access = this.getNodeAccess( node, shaderStage );
  50997. if ( type === 'texture' || type === 'storageTexture' ) {
  50998. if ( node.value.is3DTexture === true ) {
  50999. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  51000. } else {
  51001. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  51002. }
  51003. } else if ( type === 'cubeTexture' ) {
  51004. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  51005. } else if ( type === 'texture3D' ) {
  51006. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  51007. }
  51008. texture.store = node.isStorageTextureNode === true;
  51009. texture.mipLevel = texture.store ? node.mipLevel : 0;
  51010. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51011. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  51012. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  51013. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51014. bindings.push( sampler, texture );
  51015. uniformGPU = [ sampler, texture ];
  51016. } else {
  51017. bindings.push( texture );
  51018. uniformGPU = [ texture ];
  51019. }
  51020. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  51021. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  51022. const buffer = new bufferClass( node, group );
  51023. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51024. bindings.push( buffer );
  51025. uniformGPU = buffer;
  51026. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  51027. } else {
  51028. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  51029. let uniformsGroup = uniformsStage[ groupName ];
  51030. if ( uniformsGroup === undefined ) {
  51031. uniformsGroup = new NodeUniformsGroup( groupName, group );
  51032. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51033. uniformsStage[ groupName ] = uniformsGroup;
  51034. bindings.push( uniformsGroup );
  51035. }
  51036. uniformGPU = this.getNodeUniform( uniformNode, type );
  51037. uniformsGroup.addUniform( uniformGPU );
  51038. }
  51039. nodeData.uniformGPU = uniformGPU;
  51040. }
  51041. return uniformNode;
  51042. }
  51043. /**
  51044. * This method should be used whenever builtins are required in nodes.
  51045. * The internal builtins data structure will make sure builtins are
  51046. * defined in the WGSL source.
  51047. *
  51048. * @param {string} name - The builtin name.
  51049. * @param {string} property - The property name.
  51050. * @param {string} type - The node data type.
  51051. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51052. * @return {string} The property name.
  51053. */
  51054. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  51055. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  51056. if ( map.has( name ) === false ) {
  51057. map.set( name, {
  51058. name,
  51059. property,
  51060. type
  51061. } );
  51062. }
  51063. return property;
  51064. }
  51065. /**
  51066. * Returns `true` if the given builtin is defined in the given shader stage.
  51067. *
  51068. * @param {string} name - The builtin name.
  51069. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51070. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  51071. */
  51072. hasBuiltin( name, shaderStage = this.shaderStage ) {
  51073. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  51074. }
  51075. /**
  51076. * Returns the vertex index builtin.
  51077. *
  51078. * @return {string} The vertex index.
  51079. */
  51080. getVertexIndex() {
  51081. if ( this.shaderStage === 'vertex' ) {
  51082. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  51083. }
  51084. return 'vertexIndex';
  51085. }
  51086. /**
  51087. * Builds the given shader node.
  51088. *
  51089. * @param {ShaderNodeInternal} shaderNode - The shader node.
  51090. * @return {string} The WGSL function code.
  51091. */
  51092. buildFunctionCode( shaderNode ) {
  51093. const layout = shaderNode.layout;
  51094. const flowData = this.flowShaderNode( shaderNode );
  51095. const parameters = [];
  51096. for ( const input of layout.inputs ) {
  51097. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  51098. }
  51099. //
  51100. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  51101. ${ flowData.vars }
  51102. ${ flowData.code }
  51103. `;
  51104. if ( flowData.result ) {
  51105. code += `\treturn ${ flowData.result };\n`;
  51106. }
  51107. code += '\n}\n';
  51108. //
  51109. return code;
  51110. }
  51111. /**
  51112. * Contextually returns either the vertex stage instance index builtin
  51113. * or the linearized index of an compute invocation within a grid of workgroups.
  51114. *
  51115. * @return {string} The instance index.
  51116. */
  51117. getInstanceIndex() {
  51118. if ( this.shaderStage === 'vertex' ) {
  51119. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  51120. }
  51121. return 'instanceIndex';
  51122. }
  51123. /**
  51124. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  51125. *
  51126. * @return {string} The invocation local index.
  51127. */
  51128. getInvocationLocalIndex() {
  51129. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  51130. }
  51131. /**
  51132. * Returns a builtin representing the size of a subgroup within the current shader.
  51133. *
  51134. * @return {string} The subgroup size.
  51135. */
  51136. getSubgroupSize() {
  51137. this.enableSubGroups();
  51138. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  51139. }
  51140. /**
  51141. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  51142. *
  51143. * @return {string} The invocation subgroup index.
  51144. */
  51145. getInvocationSubgroupIndex() {
  51146. this.enableSubGroups();
  51147. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  51148. }
  51149. /**
  51150. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  51151. *
  51152. * @return {string} The subgroup index.
  51153. */
  51154. getSubgroupIndex() {
  51155. this.enableSubGroups();
  51156. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  51157. }
  51158. /**
  51159. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  51160. *
  51161. * @return {null} Null.
  51162. */
  51163. getDrawIndex() {
  51164. return null;
  51165. }
  51166. /**
  51167. * Returns the front facing builtin.
  51168. *
  51169. * @return {string} The front facing builtin.
  51170. */
  51171. getFrontFacing() {
  51172. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  51173. }
  51174. /**
  51175. * Returns the frag coord builtin.
  51176. *
  51177. * @return {string} The frag coord builtin.
  51178. */
  51179. getFragCoord() {
  51180. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  51181. }
  51182. /**
  51183. * Returns the frag depth builtin.
  51184. *
  51185. * @return {string} The frag depth builtin.
  51186. */
  51187. getFragDepth() {
  51188. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  51189. }
  51190. /**
  51191. * Returns the clip distances builtin.
  51192. *
  51193. * @return {string} The clip distances builtin.
  51194. */
  51195. getClipDistance() {
  51196. return 'varyings.hw_clip_distances';
  51197. }
  51198. /**
  51199. * Whether to flip texture data along its vertical axis or not.
  51200. *
  51201. * @return {boolean} Returns always `false` in context of WGSL.
  51202. */
  51203. isFlipY() {
  51204. return false;
  51205. }
  51206. /**
  51207. * Enables the given directive for the given shader stage.
  51208. *
  51209. * @param {string} name - The directive name.
  51210. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  51211. */
  51212. enableDirective( name, shaderStage = this.shaderStage ) {
  51213. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  51214. stage.add( name );
  51215. }
  51216. /**
  51217. * Returns the directives of the given shader stage as a WGSL string.
  51218. *
  51219. * @param {string} shaderStage - The shader stage.
  51220. * @return {string} A WGSL snippet that enables the directives of the given stage.
  51221. */
  51222. getDirectives( shaderStage ) {
  51223. const snippets = [];
  51224. const directives = this.directives[ shaderStage ];
  51225. if ( directives !== undefined ) {
  51226. for ( const directive of directives ) {
  51227. snippets.push( `enable ${directive};` );
  51228. }
  51229. }
  51230. return snippets.join( '\n' );
  51231. }
  51232. /**
  51233. * Enables the 'subgroups' directive.
  51234. */
  51235. enableSubGroups() {
  51236. this.enableDirective( 'subgroups' );
  51237. }
  51238. /**
  51239. * Enables the 'subgroups-f16' directive.
  51240. */
  51241. enableSubgroupsF16() {
  51242. this.enableDirective( 'subgroups-f16' );
  51243. }
  51244. /**
  51245. * Enables the 'clip_distances' directive.
  51246. */
  51247. enableClipDistances() {
  51248. this.enableDirective( 'clip_distances' );
  51249. }
  51250. /**
  51251. * Enables the 'f16' directive.
  51252. */
  51253. enableShaderF16() {
  51254. this.enableDirective( 'f16' );
  51255. }
  51256. /**
  51257. * Enables the 'dual_source_blending' directive.
  51258. */
  51259. enableDualSourceBlending() {
  51260. this.enableDirective( 'dual_source_blending' );
  51261. }
  51262. /**
  51263. * Enables hardware clipping.
  51264. *
  51265. * @param {string} planeCount - The clipping plane count.
  51266. */
  51267. enableHardwareClipping( planeCount ) {
  51268. this.enableClipDistances();
  51269. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  51270. }
  51271. /**
  51272. * Returns the builtins of the given shader stage as a WGSL string.
  51273. *
  51274. * @param {string} shaderStage - The shader stage.
  51275. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  51276. */
  51277. getBuiltins( shaderStage ) {
  51278. const snippets = [];
  51279. const builtins = this.builtins[ shaderStage ];
  51280. if ( builtins !== undefined ) {
  51281. for ( const { name, property, type } of builtins.values() ) {
  51282. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  51283. }
  51284. }
  51285. return snippets.join( ',\n\t' );
  51286. }
  51287. /**
  51288. * This method should be used when a new scoped buffer is used in context of
  51289. * compute shaders. It adds the array to the internal data structure which is
  51290. * later used to generate the respective WGSL.
  51291. *
  51292. * @param {string} name - The array name.
  51293. * @param {string} scope - The scope.
  51294. * @param {string} bufferType - The buffer type.
  51295. * @param {string} bufferCount - The buffer count.
  51296. * @return {string} The array name.
  51297. */
  51298. getScopedArray( name, scope, bufferType, bufferCount ) {
  51299. if ( this.scopedArrays.has( name ) === false ) {
  51300. this.scopedArrays.set( name, {
  51301. name,
  51302. scope,
  51303. bufferType,
  51304. bufferCount
  51305. } );
  51306. }
  51307. return name;
  51308. }
  51309. /**
  51310. * Returns the scoped arrays of the given shader stage as a WGSL string.
  51311. *
  51312. * @param {string} shaderStage - The shader stage.
  51313. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  51314. * Returns `undefined` when used in the vertex or fragment stage.
  51315. */
  51316. getScopedArrays( shaderStage ) {
  51317. if ( shaderStage !== 'compute' ) {
  51318. return;
  51319. }
  51320. const snippets = [];
  51321. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  51322. const type = this.getType( bufferType );
  51323. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  51324. }
  51325. return snippets.join( '\n' );
  51326. }
  51327. /**
  51328. * Returns the shader attributes of the given shader stage as a WGSL string.
  51329. *
  51330. * @param {string} shaderStage - The shader stage.
  51331. * @return {string} The WGSL snippet that defines the shader attributes.
  51332. */
  51333. getAttributes( shaderStage ) {
  51334. const snippets = [];
  51335. if ( shaderStage === 'compute' ) {
  51336. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  51337. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  51338. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  51339. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  51340. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  51341. this.enableDirective( 'subgroups', shaderStage );
  51342. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  51343. }
  51344. }
  51345. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  51346. const builtins = this.getBuiltins( 'attribute' );
  51347. if ( builtins ) snippets.push( builtins );
  51348. const attributes = this.getAttributesArray();
  51349. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  51350. const attribute = attributes[ index ];
  51351. const name = attribute.name;
  51352. const type = this.getType( attribute.type );
  51353. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  51354. }
  51355. }
  51356. return snippets.join( ',\n\t' );
  51357. }
  51358. /**
  51359. * Returns the members of the given struct type node as a WGSL string.
  51360. *
  51361. * @param {StructTypeNode} struct - The struct type node.
  51362. * @return {string} The WGSL snippet that defines the struct members.
  51363. */
  51364. getStructMembers( struct ) {
  51365. const snippets = [];
  51366. for ( const member of struct.members ) {
  51367. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  51368. let type = this.getType( member.type );
  51369. if ( member.atomic ) {
  51370. type = 'atomic< ' + type + ' >';
  51371. }
  51372. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  51373. }
  51374. if ( struct.output ) {
  51375. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  51376. }
  51377. return snippets.join( ',\n' );
  51378. }
  51379. /**
  51380. * Returns the structs of the given shader stage as a WGSL string.
  51381. *
  51382. * @param {string} shaderStage - The shader stage.
  51383. * @return {string} The WGSL snippet that defines the structs.
  51384. */
  51385. getStructs( shaderStage ) {
  51386. let result = '';
  51387. const structs = this.structs[ shaderStage ];
  51388. if ( structs.length > 0 ) {
  51389. const snippets = [];
  51390. for ( const struct of structs ) {
  51391. let snippet = `struct ${ struct.name } {\n`;
  51392. snippet += this.getStructMembers( struct );
  51393. snippet += '\n};';
  51394. snippets.push( snippet );
  51395. }
  51396. result = '\n' + snippets.join( '\n\n' ) + '\n';
  51397. }
  51398. return result;
  51399. }
  51400. /**
  51401. * Returns a WGSL string representing a variable.
  51402. *
  51403. * @param {string} type - The variable's type.
  51404. * @param {string} name - The variable's name.
  51405. * @param {?number} [count=null] - The array length.
  51406. * @return {string} The WGSL snippet that defines a variable.
  51407. */
  51408. getVar( type, name, count = null ) {
  51409. let snippet = `var ${ name } : `;
  51410. if ( count !== null ) {
  51411. snippet += this.generateArrayDeclaration( type, count );
  51412. } else {
  51413. snippet += this.getType( type );
  51414. }
  51415. return snippet;
  51416. }
  51417. /**
  51418. * Returns the variables of the given shader stage as a WGSL string.
  51419. *
  51420. * @param {string} shaderStage - The shader stage.
  51421. * @return {string} The WGSL snippet that defines the variables.
  51422. */
  51423. getVars( shaderStage ) {
  51424. const snippets = [];
  51425. const vars = this.vars[ shaderStage ];
  51426. if ( vars !== undefined ) {
  51427. for ( const variable of vars ) {
  51428. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  51429. }
  51430. }
  51431. return `\n${ snippets.join( '\n' ) }\n`;
  51432. }
  51433. /**
  51434. * Returns the varyings of the given shader stage as a WGSL string.
  51435. *
  51436. * @param {string} shaderStage - The shader stage.
  51437. * @return {string} The WGSL snippet that defines the varyings.
  51438. */
  51439. getVaryings( shaderStage ) {
  51440. const snippets = [];
  51441. if ( shaderStage === 'vertex' ) {
  51442. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  51443. }
  51444. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  51445. const varyings = this.varyings;
  51446. const vars = this.vars[ shaderStage ];
  51447. for ( let index = 0; index < varyings.length; index ++ ) {
  51448. const varying = varyings[ index ];
  51449. if ( varying.needsInterpolation ) {
  51450. let attributesSnippet = `@location( ${index} )`;
  51451. if ( varying.interpolationType ) {
  51452. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  51453. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  51454. // Otherwise, optimize interpolation when sensible
  51455. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  51456. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  51457. }
  51458. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  51459. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  51460. vars.push( varying );
  51461. }
  51462. }
  51463. }
  51464. const builtins = this.getBuiltins( shaderStage );
  51465. if ( builtins ) snippets.push( builtins );
  51466. const code = snippets.join( ',\n\t' );
  51467. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  51468. }
  51469. isCustomStruct( nodeUniform ) {
  51470. const attribute = nodeUniform.value;
  51471. const bufferNode = nodeUniform.node;
  51472. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  51473. const isStructArray =
  51474. ( bufferNode.value && bufferNode.value.array ) &&
  51475. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  51476. return isAttributeStructType && ! isStructArray;
  51477. }
  51478. /**
  51479. * Returns the uniforms of the given shader stage as a WGSL string.
  51480. *
  51481. * @param {string} shaderStage - The shader stage.
  51482. * @return {string} The WGSL snippet that defines the uniforms.
  51483. */
  51484. getUniforms( shaderStage ) {
  51485. const uniforms = this.uniforms[ shaderStage ];
  51486. const bindingSnippets = [];
  51487. const bufferSnippets = [];
  51488. const structSnippets = [];
  51489. const uniformGroups = {};
  51490. for ( const uniform of uniforms ) {
  51491. const groupName = uniform.groupNode.name;
  51492. const uniformIndexes = this.bindingsIndexes[ groupName ];
  51493. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  51494. const texture = uniform.node.value;
  51495. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  51496. if ( this.isSampleCompare( texture ) ) {
  51497. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  51498. } else {
  51499. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  51500. }
  51501. }
  51502. let textureType;
  51503. let multisampled = '';
  51504. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  51505. if ( primarySamples > 1 ) {
  51506. multisampled = '_multisampled';
  51507. }
  51508. if ( texture.isCubeTexture === true ) {
  51509. textureType = 'texture_cube<f32>';
  51510. } else if ( texture.isDepthTexture === true ) {
  51511. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  51512. textureType = `texture${ multisampled }_2d<f32>`;
  51513. } else {
  51514. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  51515. }
  51516. } else if ( uniform.node.isStorageTextureNode === true ) {
  51517. const format = getFormat( texture );
  51518. const access = this.getStorageAccess( uniform.node, shaderStage );
  51519. const is3D = uniform.node.value.is3DTexture;
  51520. const isArrayTexture = uniform.node.value.isArrayTexture;
  51521. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  51522. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  51523. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  51524. textureType = 'texture_2d_array<f32>';
  51525. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  51526. textureType = 'texture_3d<f32>';
  51527. } else {
  51528. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  51529. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  51530. }
  51531. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  51532. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  51533. const bufferNode = uniform.node;
  51534. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  51535. const bufferCount = bufferNode.bufferCount;
  51536. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  51537. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  51538. if ( this.isCustomStruct( uniform ) ) {
  51539. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  51540. } else {
  51541. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  51542. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  51543. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  51544. }
  51545. } else {
  51546. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  51547. const groupName = uniform.groupNode.name;
  51548. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  51549. index: uniformIndexes.binding ++,
  51550. id: uniformIndexes.group,
  51551. snippets: []
  51552. } );
  51553. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  51554. }
  51555. }
  51556. for ( const name in uniformGroups ) {
  51557. const group = uniformGroups[ name ];
  51558. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  51559. }
  51560. let code = bindingSnippets.join( '\n' );
  51561. code += bufferSnippets.join( '\n' );
  51562. code += structSnippets.join( '\n' );
  51563. return code;
  51564. }
  51565. /**
  51566. * Controls the code build of the shader stages.
  51567. */
  51568. buildCode() {
  51569. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  51570. this.sortBindingGroups();
  51571. for ( const shaderStage in shadersData ) {
  51572. this.shaderStage = shaderStage;
  51573. const stageData = shadersData[ shaderStage ];
  51574. stageData.uniforms = this.getUniforms( shaderStage );
  51575. stageData.attributes = this.getAttributes( shaderStage );
  51576. stageData.varyings = this.getVaryings( shaderStage );
  51577. stageData.structs = this.getStructs( shaderStage );
  51578. stageData.vars = this.getVars( shaderStage );
  51579. stageData.codes = this.getCodes( shaderStage );
  51580. stageData.directives = this.getDirectives( shaderStage );
  51581. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  51582. //
  51583. let flow = '// code\n\n';
  51584. flow += this.flowCode[ shaderStage ];
  51585. const flowNodes = this.flowNodes[ shaderStage ];
  51586. const mainNode = flowNodes[ flowNodes.length - 1 ];
  51587. const outputNode = mainNode.outputNode;
  51588. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  51589. for ( const node of flowNodes ) {
  51590. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  51591. const slotName = node.name;
  51592. if ( slotName ) {
  51593. if ( flow.length > 0 ) flow += '\n';
  51594. flow += `\t// flow -> ${ slotName }\n`;
  51595. }
  51596. flow += `${ flowSlotData.code }\n\t`;
  51597. if ( node === mainNode && shaderStage !== 'compute' ) {
  51598. flow += '// result\n\n\t';
  51599. if ( shaderStage === 'vertex' ) {
  51600. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  51601. } else if ( shaderStage === 'fragment' ) {
  51602. if ( isOutputStruct ) {
  51603. stageData.returnType = outputNode.getNodeType( this );
  51604. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  51605. flow += `return ${ flowSlotData.result };`;
  51606. } else {
  51607. let structSnippet = '\t@location(0) color: vec4<f32>';
  51608. const builtins = this.getBuiltins( 'output' );
  51609. if ( builtins ) structSnippet += ',\n\t' + builtins;
  51610. stageData.returnType = 'OutputStruct';
  51611. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  51612. stageData.structs += '\nvar<private> output : OutputStruct;';
  51613. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  51614. }
  51615. }
  51616. }
  51617. }
  51618. stageData.flow = flow;
  51619. }
  51620. this.shaderStage = null;
  51621. if ( this.material !== null ) {
  51622. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  51623. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  51624. } else {
  51625. // Early strictly validated in computeNode
  51626. const workgroupSize = this.object.workgroupSize;
  51627. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  51628. }
  51629. }
  51630. /**
  51631. * Returns the native shader method name for a given generic name.
  51632. *
  51633. * @param {string} method - The method name to resolve.
  51634. * @param {?string} [output=null] - An optional output.
  51635. * @return {string} The resolved WGSL method name.
  51636. */
  51637. getMethod( method, output = null ) {
  51638. let wgslMethod;
  51639. if ( output !== null ) {
  51640. wgslMethod = this._getWGSLMethod( method + '_' + output );
  51641. }
  51642. if ( wgslMethod === undefined ) {
  51643. wgslMethod = this._getWGSLMethod( method );
  51644. }
  51645. return wgslMethod || method;
  51646. }
  51647. /**
  51648. * Returns the bitcast method name for a given input and outputType.
  51649. *
  51650. * @param {string} type - The output type to bitcast to.
  51651. * @return {string} The resolved WGSL bitcast invocation.
  51652. */
  51653. getBitcastMethod( type ) {
  51654. const dataType = this.getType( type );
  51655. return `bitcast<${ dataType }>`;
  51656. }
  51657. /**
  51658. * Returns the native snippet for a ternary operation.
  51659. *
  51660. * @param {string} condSnippet - The condition determining which expression gets resolved.
  51661. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  51662. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  51663. * @return {string} The resolved method name.
  51664. */
  51665. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  51666. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  51667. }
  51668. /**
  51669. * Returns the WGSL type of the given node data type.
  51670. *
  51671. * @param {string} type - The node data type.
  51672. * @return {string} The WGSL type.
  51673. */
  51674. getType( type ) {
  51675. return wgslTypeLib[ type ] || type;
  51676. }
  51677. /**
  51678. * Whether the requested feature is available or not.
  51679. *
  51680. * @param {string} name - The requested feature.
  51681. * @return {boolean} Whether the requested feature is supported or not.
  51682. */
  51683. isAvailable( name ) {
  51684. let result = supports[ name ];
  51685. if ( result === undefined ) {
  51686. if ( name === 'float32Filterable' ) {
  51687. result = this.renderer.hasFeature( 'float32-filterable' );
  51688. } else if ( name === 'clipDistance' ) {
  51689. result = this.renderer.hasFeature( 'clip-distances' );
  51690. }
  51691. supports[ name ] = result;
  51692. }
  51693. return result;
  51694. }
  51695. /**
  51696. * Returns the native shader method name for a given generic name.
  51697. *
  51698. * @private
  51699. * @param {string} method - The method name to resolve.
  51700. * @return {string} The resolved WGSL method name.
  51701. */
  51702. _getWGSLMethod( method ) {
  51703. if ( wgslPolyfill[ method ] !== undefined ) {
  51704. this._include( method );
  51705. }
  51706. return wgslMethods[ method ];
  51707. }
  51708. /**
  51709. * Includes the given method name into the current
  51710. * function node.
  51711. *
  51712. * @private
  51713. * @param {string} name - The method name to include.
  51714. * @return {CodeNode} The respective code node.
  51715. */
  51716. _include( name ) {
  51717. const codeNode = wgslPolyfill[ name ];
  51718. codeNode.build( this );
  51719. this.addInclude( codeNode );
  51720. return codeNode;
  51721. }
  51722. /**
  51723. * Returns a WGSL vertex shader based on the given shader data.
  51724. *
  51725. * @private
  51726. * @param {Object} shaderData - The shader data.
  51727. * @return {string} The vertex shader.
  51728. */
  51729. _getWGSLVertexCode( shaderData ) {
  51730. return `${ this.getSignature() }
  51731. // directives
  51732. ${shaderData.directives}
  51733. // structs
  51734. ${shaderData.structs}
  51735. // uniforms
  51736. ${shaderData.uniforms}
  51737. // varyings
  51738. ${shaderData.varyings}
  51739. var<private> varyings : VaryingsStruct;
  51740. // codes
  51741. ${shaderData.codes}
  51742. @vertex
  51743. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  51744. // vars
  51745. ${shaderData.vars}
  51746. // flow
  51747. ${shaderData.flow}
  51748. return varyings;
  51749. }
  51750. `;
  51751. }
  51752. /**
  51753. * Returns a WGSL fragment shader based on the given shader data.
  51754. *
  51755. * @private
  51756. * @param {Object} shaderData - The shader data.
  51757. * @return {string} The vertex shader.
  51758. */
  51759. _getWGSLFragmentCode( shaderData ) {
  51760. return `${ this.getSignature() }
  51761. // global
  51762. ${ diagnostics }
  51763. // structs
  51764. ${shaderData.structs}
  51765. // uniforms
  51766. ${shaderData.uniforms}
  51767. // codes
  51768. ${shaderData.codes}
  51769. @fragment
  51770. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  51771. // vars
  51772. ${shaderData.vars}
  51773. // flow
  51774. ${shaderData.flow}
  51775. }
  51776. `;
  51777. }
  51778. /**
  51779. * Returns a WGSL compute shader based on the given shader data.
  51780. *
  51781. * @private
  51782. * @param {Object} shaderData - The shader data.
  51783. * @param {string} workgroupSize - The workgroup size.
  51784. * @return {string} The vertex shader.
  51785. */
  51786. _getWGSLComputeCode( shaderData, workgroupSize ) {
  51787. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  51788. return `${ this.getSignature() }
  51789. // directives
  51790. ${ shaderData.directives }
  51791. // system
  51792. var<private> instanceIndex : u32;
  51793. // locals
  51794. ${ shaderData.scopedArrays }
  51795. // structs
  51796. ${ shaderData.structs }
  51797. // uniforms
  51798. ${ shaderData.uniforms }
  51799. // codes
  51800. ${ shaderData.codes }
  51801. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  51802. fn main( ${ shaderData.attributes } ) {
  51803. // system
  51804. instanceIndex = globalId.x
  51805. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  51806. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  51807. // vars
  51808. ${ shaderData.vars }
  51809. // flow
  51810. ${ shaderData.flow }
  51811. }
  51812. `;
  51813. }
  51814. /**
  51815. * Returns a WGSL struct based on the given name and variables.
  51816. *
  51817. * @private
  51818. * @param {string} name - The struct name.
  51819. * @param {string} vars - The struct variables.
  51820. * @return {string} The WGSL snippet representing a struct.
  51821. */
  51822. _getWGSLStruct( name, vars ) {
  51823. return `
  51824. struct ${name} {
  51825. ${vars}
  51826. };`;
  51827. }
  51828. /**
  51829. * Returns a WGSL struct binding.
  51830. *
  51831. * @private
  51832. * @param {string} name - The struct name.
  51833. * @param {string} vars - The struct variables.
  51834. * @param {string} access - The access.
  51835. * @param {number} [binding=0] - The binding index.
  51836. * @param {number} [group=0] - The group index.
  51837. * @return {string} The WGSL snippet representing a struct binding.
  51838. */
  51839. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  51840. const structName = name + 'Struct';
  51841. const structSnippet = this._getWGSLStruct( structName, vars );
  51842. return `${structSnippet}
  51843. @binding( ${ binding } ) @group( ${ group } )
  51844. var<${access}> ${ name } : ${ structName };`;
  51845. }
  51846. }
  51847. /**
  51848. * A WebGPU backend utility module with common helpers.
  51849. *
  51850. * @private
  51851. */
  51852. class WebGPUUtils {
  51853. /**
  51854. * Constructs a new utility object.
  51855. *
  51856. * @param {WebGPUBackend} backend - The WebGPU backend.
  51857. */
  51858. constructor( backend ) {
  51859. /**
  51860. * A reference to the WebGPU backend.
  51861. *
  51862. * @type {WebGPUBackend}
  51863. */
  51864. this.backend = backend;
  51865. }
  51866. /**
  51867. * Returns the depth/stencil GPU format for the given render context.
  51868. *
  51869. * @param {RenderContext} renderContext - The render context.
  51870. * @return {string} The depth/stencil GPU texture format.
  51871. */
  51872. getCurrentDepthStencilFormat( renderContext ) {
  51873. let format;
  51874. if ( renderContext.depthTexture !== null ) {
  51875. format = this.getTextureFormatGPU( renderContext.depthTexture );
  51876. } else if ( renderContext.depth && renderContext.stencil ) {
  51877. format = GPUTextureFormat.Depth24PlusStencil8;
  51878. } else if ( renderContext.depth ) {
  51879. format = GPUTextureFormat.Depth24Plus;
  51880. }
  51881. return format;
  51882. }
  51883. /**
  51884. * Returns the GPU format for the given texture.
  51885. *
  51886. * @param {Texture} texture - The texture.
  51887. * @return {string} The GPU texture format.
  51888. */
  51889. getTextureFormatGPU( texture ) {
  51890. return this.backend.get( texture ).format;
  51891. }
  51892. /**
  51893. * Returns an object that defines the multi-sampling state of the given texture.
  51894. *
  51895. * @param {Texture} texture - The texture.
  51896. * @return {Object} The multi-sampling state.
  51897. */
  51898. getTextureSampleData( texture ) {
  51899. let samples;
  51900. if ( texture.isFramebufferTexture ) {
  51901. samples = 1;
  51902. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  51903. const renderer = this.backend.renderer;
  51904. const renderTarget = renderer.getRenderTarget();
  51905. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  51906. } else if ( texture.renderTarget ) {
  51907. samples = texture.renderTarget.samples;
  51908. }
  51909. samples = samples || 1;
  51910. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  51911. const primarySamples = isMSAA ? 1 : samples;
  51912. return { samples, primarySamples, isMSAA };
  51913. }
  51914. /**
  51915. * Returns the default color attachment's GPU format of the current render context.
  51916. *
  51917. * @param {RenderContext} renderContext - The render context.
  51918. * @return {string} The GPU texture format of the default color attachment.
  51919. */
  51920. getCurrentColorFormat( renderContext ) {
  51921. let format;
  51922. if ( renderContext.textures !== null ) {
  51923. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  51924. } else {
  51925. format = this.getPreferredCanvasFormat(); // default context format
  51926. }
  51927. return format;
  51928. }
  51929. /**
  51930. * Returns the GPU formats of all color attachments of the current render context.
  51931. *
  51932. * @param {RenderContext} renderContext - The render context.
  51933. * @return {Array<string>} The GPU texture formats of all color attachments.
  51934. */
  51935. getCurrentColorFormats( renderContext ) {
  51936. if ( renderContext.textures !== null ) {
  51937. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  51938. } else {
  51939. return [ this.getPreferredCanvasFormat() ]; // default context format
  51940. }
  51941. }
  51942. /**
  51943. * Returns the output color space of the current render context.
  51944. *
  51945. * @param {RenderContext} renderContext - The render context.
  51946. * @return {string} The output color space.
  51947. */
  51948. getCurrentColorSpace( renderContext ) {
  51949. if ( renderContext.textures !== null ) {
  51950. return renderContext.textures[ 0 ].colorSpace;
  51951. }
  51952. return this.backend.renderer.outputColorSpace;
  51953. }
  51954. /**
  51955. * Returns GPU primitive topology for the given object and material.
  51956. *
  51957. * @param {Object3D} object - The 3D object.
  51958. * @param {Material} material - The material.
  51959. * @return {string} The GPU primitive topology.
  51960. */
  51961. getPrimitiveTopology( object, material ) {
  51962. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  51963. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  51964. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  51965. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  51966. }
  51967. /**
  51968. * Returns a modified sample count from the given sample count value.
  51969. *
  51970. * That is required since WebGPU only supports either 1 or 4.
  51971. *
  51972. * @param {number} sampleCount - The input sample count.
  51973. * @return {number} The (potentially updated) output sample count.
  51974. */
  51975. getSampleCount( sampleCount ) {
  51976. return sampleCount >= 4 ? 4 : 1;
  51977. }
  51978. /**
  51979. * Returns the sample count of the given render context.
  51980. *
  51981. * @param {RenderContext} renderContext - The render context.
  51982. * @return {number} The sample count.
  51983. */
  51984. getSampleCountRenderContext( renderContext ) {
  51985. if ( renderContext.textures !== null ) {
  51986. return this.getSampleCount( renderContext.sampleCount );
  51987. }
  51988. return this.getSampleCount( this.backend.renderer.currentSamples );
  51989. }
  51990. /**
  51991. * Returns the preferred canvas format.
  51992. *
  51993. * There is a separate method for this so it's possible to
  51994. * honor edge cases for specific devices.
  51995. *
  51996. * @return {string} The GPU texture format of the canvas.
  51997. */
  51998. getPreferredCanvasFormat() {
  51999. const outputType = this.backend.parameters.outputType;
  52000. if ( outputType === undefined ) {
  52001. return navigator.gpu.getPreferredCanvasFormat();
  52002. } else if ( outputType === UnsignedByteType ) {
  52003. return GPUTextureFormat.BGRA8Unorm;
  52004. } else if ( outputType === HalfFloatType ) {
  52005. return GPUTextureFormat.RGBA16Float;
  52006. } else {
  52007. throw new Error( 'Unsupported outputType' );
  52008. }
  52009. }
  52010. }
  52011. const typedArraysToVertexFormatPrefix = new Map( [
  52012. [ Int8Array, [ 'sint8', 'snorm8' ]],
  52013. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  52014. [ Int16Array, [ 'sint16', 'snorm16' ]],
  52015. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  52016. [ Int32Array, [ 'sint32', 'snorm32' ]],
  52017. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  52018. [ Float32Array, [ 'float32', ]],
  52019. ] );
  52020. if ( typeof Float16Array !== 'undefined' ) {
  52021. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  52022. }
  52023. const typedAttributeToVertexFormatPrefix = new Map( [
  52024. [ Float16BufferAttribute, [ 'float16', ]],
  52025. ] );
  52026. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  52027. [ Int32Array, 'sint32' ],
  52028. [ Int16Array, 'sint32' ], // patch for INT16
  52029. [ Uint32Array, 'uint32' ],
  52030. [ Uint16Array, 'uint32' ], // patch for UINT16
  52031. [ Float32Array, 'float32' ]
  52032. ] );
  52033. /**
  52034. * A WebGPU backend utility module for managing shader attributes.
  52035. *
  52036. * @private
  52037. */
  52038. class WebGPUAttributeUtils {
  52039. /**
  52040. * Constructs a new utility object.
  52041. *
  52042. * @param {WebGPUBackend} backend - The WebGPU backend.
  52043. */
  52044. constructor( backend ) {
  52045. /**
  52046. * A reference to the WebGPU backend.
  52047. *
  52048. * @type {WebGPUBackend}
  52049. */
  52050. this.backend = backend;
  52051. }
  52052. /**
  52053. * Creates the GPU buffer for the given buffer attribute.
  52054. *
  52055. * @param {BufferAttribute} attribute - The buffer attribute.
  52056. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  52057. */
  52058. createAttribute( attribute, usage ) {
  52059. const bufferAttribute = this._getBufferAttribute( attribute );
  52060. const backend = this.backend;
  52061. const bufferData = backend.get( bufferAttribute );
  52062. let buffer = bufferData.buffer;
  52063. if ( buffer === undefined ) {
  52064. const device = backend.device;
  52065. let array = bufferAttribute.array;
  52066. // patch for INT16 and UINT16
  52067. if ( attribute.normalized === false ) {
  52068. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  52069. array = new Int32Array( array );
  52070. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  52071. array = new Uint32Array( array );
  52072. if ( usage & GPUBufferUsage.INDEX ) {
  52073. for ( let i = 0; i < array.length; i ++ ) {
  52074. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  52075. }
  52076. }
  52077. }
  52078. }
  52079. bufferAttribute.array = array;
  52080. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  52081. array = new array.constructor( bufferAttribute.count * 4 );
  52082. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  52083. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  52084. }
  52085. // Update BufferAttribute
  52086. bufferAttribute.itemSize = 4;
  52087. bufferAttribute.array = array;
  52088. bufferData._force3to4BytesAlignment = true;
  52089. }
  52090. // ensure 4 byte alignment
  52091. const byteLength = array.byteLength;
  52092. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  52093. buffer = device.createBuffer( {
  52094. label: bufferAttribute.name,
  52095. size: size,
  52096. usage: usage,
  52097. mappedAtCreation: true
  52098. } );
  52099. new array.constructor( buffer.getMappedRange() ).set( array );
  52100. buffer.unmap();
  52101. bufferData.buffer = buffer;
  52102. }
  52103. }
  52104. /**
  52105. * Updates the GPU buffer of the given buffer attribute.
  52106. *
  52107. * @param {BufferAttribute} attribute - The buffer attribute.
  52108. */
  52109. updateAttribute( attribute ) {
  52110. const bufferAttribute = this._getBufferAttribute( attribute );
  52111. const backend = this.backend;
  52112. const device = backend.device;
  52113. const bufferData = backend.get( bufferAttribute );
  52114. const buffer = backend.get( bufferAttribute ).buffer;
  52115. let array = bufferAttribute.array;
  52116. // if storage buffer ensure 4 byte alignment
  52117. if ( bufferData._force3to4BytesAlignment === true ) {
  52118. array = new array.constructor( bufferAttribute.count * 4 );
  52119. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  52120. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  52121. }
  52122. bufferAttribute.array = array;
  52123. }
  52124. const isTypedArray = this._isTypedArray( array );
  52125. const updateRanges = bufferAttribute.updateRanges;
  52126. if ( updateRanges.length === 0 ) {
  52127. // Not using update ranges
  52128. device.queue.writeBuffer(
  52129. buffer,
  52130. 0,
  52131. array,
  52132. 0
  52133. );
  52134. } else {
  52135. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  52136. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  52137. const range = updateRanges[ i ];
  52138. let dataOffset, size;
  52139. if ( bufferData._force3to4BytesAlignment === true ) {
  52140. const vertexStart = Math.floor( range.start / 3 );
  52141. const vertexCount = Math.ceil( range.count / 3 );
  52142. dataOffset = vertexStart * 4 * byteOffsetFactor;
  52143. size = vertexCount * 4 * byteOffsetFactor;
  52144. } else {
  52145. dataOffset = range.start * byteOffsetFactor;
  52146. size = range.count * byteOffsetFactor;
  52147. }
  52148. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  52149. device.queue.writeBuffer(
  52150. buffer,
  52151. bufferOffset,
  52152. array,
  52153. dataOffset,
  52154. size
  52155. );
  52156. }
  52157. bufferAttribute.clearUpdateRanges();
  52158. }
  52159. }
  52160. /**
  52161. * This method creates the vertex buffer layout data which are
  52162. * require when creating a render pipeline for the given render object.
  52163. *
  52164. * @param {RenderObject} renderObject - The render object.
  52165. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  52166. */
  52167. createShaderVertexBuffers( renderObject ) {
  52168. const attributes = renderObject.getAttributes();
  52169. const vertexBuffers = new Map();
  52170. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  52171. const geometryAttribute = attributes[ slot ];
  52172. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  52173. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  52174. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  52175. if ( vertexBufferLayout === undefined ) {
  52176. let arrayStride, stepMode;
  52177. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  52178. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  52179. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  52180. } else {
  52181. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  52182. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  52183. }
  52184. // patch for INT16 and UINT16
  52185. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  52186. arrayStride = 4;
  52187. }
  52188. vertexBufferLayout = {
  52189. arrayStride,
  52190. attributes: [],
  52191. stepMode
  52192. };
  52193. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  52194. }
  52195. const format = this._getVertexFormat( geometryAttribute );
  52196. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  52197. vertexBufferLayout.attributes.push( {
  52198. shaderLocation: slot,
  52199. offset,
  52200. format
  52201. } );
  52202. }
  52203. return Array.from( vertexBuffers.values() );
  52204. }
  52205. /**
  52206. * Destroys the GPU buffer of the given buffer attribute.
  52207. *
  52208. * @param {BufferAttribute} attribute - The buffer attribute.
  52209. */
  52210. destroyAttribute( attribute ) {
  52211. const backend = this.backend;
  52212. const data = backend.get( this._getBufferAttribute( attribute ) );
  52213. data.buffer.destroy();
  52214. backend.delete( attribute );
  52215. }
  52216. /**
  52217. * This method performs a readback operation by moving buffer data from
  52218. * a storage buffer attribute from the GPU to the CPU.
  52219. *
  52220. * @async
  52221. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  52222. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  52223. */
  52224. async getArrayBufferAsync( attribute ) {
  52225. const backend = this.backend;
  52226. const device = backend.device;
  52227. const data = backend.get( this._getBufferAttribute( attribute ) );
  52228. const bufferGPU = data.buffer;
  52229. const size = bufferGPU.size;
  52230. const readBufferGPU = device.createBuffer( {
  52231. label: `${ attribute.name }_readback`,
  52232. size,
  52233. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  52234. } );
  52235. const cmdEncoder = device.createCommandEncoder( {
  52236. label: `readback_encoder_${ attribute.name }`
  52237. } );
  52238. cmdEncoder.copyBufferToBuffer(
  52239. bufferGPU,
  52240. 0,
  52241. readBufferGPU,
  52242. 0,
  52243. size
  52244. );
  52245. const gpuCommands = cmdEncoder.finish();
  52246. device.queue.submit( [ gpuCommands ] );
  52247. await readBufferGPU.mapAsync( GPUMapMode.READ );
  52248. const arrayBuffer = readBufferGPU.getMappedRange();
  52249. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  52250. readBufferGPU.unmap();
  52251. return dstBuffer.buffer;
  52252. }
  52253. /**
  52254. * Returns the vertex format of the given buffer attribute.
  52255. *
  52256. * @private
  52257. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  52258. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  52259. */
  52260. _getVertexFormat( geometryAttribute ) {
  52261. const { itemSize, normalized } = geometryAttribute;
  52262. const ArrayType = geometryAttribute.array.constructor;
  52263. const AttributeType = geometryAttribute.constructor;
  52264. let format;
  52265. if ( itemSize === 1 ) {
  52266. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  52267. } else {
  52268. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  52269. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  52270. if ( prefix ) {
  52271. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  52272. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  52273. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  52274. if ( paddedItemSize % 1 ) {
  52275. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  52276. }
  52277. format = `${prefix}x${paddedItemSize}`;
  52278. }
  52279. }
  52280. if ( ! format ) {
  52281. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  52282. }
  52283. return format;
  52284. }
  52285. /**
  52286. * Returns `true` if the given array is a typed array.
  52287. *
  52288. * @private
  52289. * @param {any} array - The array.
  52290. * @return {boolean} Whether the given array is a typed array or not.
  52291. */
  52292. _isTypedArray( array ) {
  52293. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  52294. }
  52295. /**
  52296. * Utility method for handling interleaved buffer attributes correctly.
  52297. * To process them, their `InterleavedBuffer` is returned.
  52298. *
  52299. * @private
  52300. * @param {BufferAttribute} attribute - The attribute.
  52301. * @return {BufferAttribute|InterleavedBuffer}
  52302. */
  52303. _getBufferAttribute( attribute ) {
  52304. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  52305. return attribute;
  52306. }
  52307. }
  52308. /**
  52309. * A WebGPU backend utility module for managing bindings.
  52310. *
  52311. * When reading the documentation it's helpful to keep in mind that
  52312. * all class definitions starting with 'GPU*' are modules from the
  52313. * WebGPU API. So for example `BindGroup` is a class from the engine
  52314. * whereas `GPUBindGroup` is a class from WebGPU.
  52315. *
  52316. * @private
  52317. */
  52318. class WebGPUBindingUtils {
  52319. /**
  52320. * Constructs a new utility object.
  52321. *
  52322. * @param {WebGPUBackend} backend - The WebGPU backend.
  52323. */
  52324. constructor( backend ) {
  52325. /**
  52326. * A reference to the WebGPU backend.
  52327. *
  52328. * @type {WebGPUBackend}
  52329. */
  52330. this.backend = backend;
  52331. /**
  52332. * A cache for managing bind group layouts.
  52333. *
  52334. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  52335. */
  52336. this.bindGroupLayoutCache = new WeakMap();
  52337. }
  52338. /**
  52339. * Creates a GPU bind group layout for the given bind group.
  52340. *
  52341. * @param {BindGroup} bindGroup - The bind group.
  52342. * @return {GPUBindGroupLayout} The GPU bind group layout.
  52343. */
  52344. createBindingsLayout( bindGroup ) {
  52345. const backend = this.backend;
  52346. const device = backend.device;
  52347. const entries = [];
  52348. let index = 0;
  52349. for ( const binding of bindGroup.bindings ) {
  52350. const bindingGPU = {
  52351. binding: index ++,
  52352. visibility: binding.visibility
  52353. };
  52354. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  52355. const buffer = {}; // GPUBufferBindingLayout
  52356. if ( binding.isStorageBuffer ) {
  52357. if ( binding.visibility & 4 ) {
  52358. // compute
  52359. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  52360. buffer.type = GPUBufferBindingType.Storage;
  52361. } else {
  52362. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  52363. }
  52364. } else {
  52365. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  52366. }
  52367. }
  52368. bindingGPU.buffer = buffer;
  52369. } else if ( binding.isSampledTexture && binding.store ) {
  52370. const storageTexture = {}; // GPUStorageTextureBindingLayout
  52371. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  52372. const access = binding.access;
  52373. if ( access === NodeAccess.READ_WRITE ) {
  52374. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  52375. } else if ( access === NodeAccess.WRITE_ONLY ) {
  52376. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  52377. } else {
  52378. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  52379. }
  52380. if ( binding.texture.isArrayTexture ) {
  52381. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  52382. } else if ( binding.texture.is3DTexture ) {
  52383. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  52384. }
  52385. bindingGPU.storageTexture = storageTexture;
  52386. } else if ( binding.isSampledTexture ) {
  52387. const texture = {}; // GPUTextureBindingLayout
  52388. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  52389. if ( primarySamples > 1 ) {
  52390. texture.multisampled = true;
  52391. if ( ! binding.texture.isDepthTexture ) {
  52392. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52393. }
  52394. }
  52395. if ( binding.texture.isDepthTexture ) {
  52396. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  52397. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52398. } else {
  52399. texture.sampleType = GPUTextureSampleType.Depth;
  52400. }
  52401. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  52402. const type = binding.texture.type;
  52403. if ( type === IntType ) {
  52404. texture.sampleType = GPUTextureSampleType.SInt;
  52405. } else if ( type === UnsignedIntType ) {
  52406. texture.sampleType = GPUTextureSampleType.UInt;
  52407. } else if ( type === FloatType ) {
  52408. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  52409. texture.sampleType = GPUTextureSampleType.Float;
  52410. } else {
  52411. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52412. }
  52413. }
  52414. }
  52415. if ( binding.isSampledCubeTexture ) {
  52416. texture.viewDimension = GPUTextureViewDimension.Cube;
  52417. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  52418. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  52419. } else if ( binding.isSampledTexture3D ) {
  52420. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  52421. }
  52422. bindingGPU.texture = texture;
  52423. } else if ( binding.isSampler ) {
  52424. const sampler = {}; // GPUSamplerBindingLayout
  52425. if ( binding.texture.isDepthTexture ) {
  52426. if ( binding.texture.compareFunction !== null ) {
  52427. sampler.type = GPUSamplerBindingType.Comparison;
  52428. } else if ( backend.compatibilityMode ) {
  52429. sampler.type = GPUSamplerBindingType.NonFiltering;
  52430. }
  52431. }
  52432. bindingGPU.sampler = sampler;
  52433. } else {
  52434. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  52435. }
  52436. entries.push( bindingGPU );
  52437. }
  52438. return device.createBindGroupLayout( { entries } );
  52439. }
  52440. /**
  52441. * Creates bindings from the given bind group definition.
  52442. *
  52443. * @param {BindGroup} bindGroup - The bind group.
  52444. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52445. * @param {number} cacheIndex - The cache index.
  52446. * @param {number} version - The version.
  52447. */
  52448. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  52449. const { backend, bindGroupLayoutCache } = this;
  52450. const bindingsData = backend.get( bindGroup );
  52451. // setup (static) binding layout and (dynamic) binding group
  52452. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  52453. if ( bindLayoutGPU === undefined ) {
  52454. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  52455. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  52456. }
  52457. let bindGroupGPU;
  52458. if ( cacheIndex > 0 ) {
  52459. if ( bindingsData.groups === undefined ) {
  52460. bindingsData.groups = [];
  52461. bindingsData.versions = [];
  52462. }
  52463. if ( bindingsData.versions[ cacheIndex ] === version ) {
  52464. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  52465. }
  52466. }
  52467. if ( bindGroupGPU === undefined ) {
  52468. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  52469. if ( cacheIndex > 0 ) {
  52470. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  52471. bindingsData.versions[ cacheIndex ] = version;
  52472. }
  52473. }
  52474. bindingsData.group = bindGroupGPU;
  52475. bindingsData.layout = bindLayoutGPU;
  52476. }
  52477. /**
  52478. * Updates a buffer binding.
  52479. *
  52480. * @param {Buffer} binding - The buffer binding to update.
  52481. */
  52482. updateBinding( binding ) {
  52483. const backend = this.backend;
  52484. const device = backend.device;
  52485. const buffer = binding.buffer;
  52486. const bufferGPU = backend.get( binding ).buffer;
  52487. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  52488. }
  52489. /**
  52490. * Creates a GPU bind group for the camera index.
  52491. *
  52492. * @param {Uint32Array} data - The index data.
  52493. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  52494. * @return {GPUBindGroup} The GPU bind group.
  52495. */
  52496. createBindGroupIndex( data, layout ) {
  52497. const backend = this.backend;
  52498. const device = backend.device;
  52499. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  52500. const index = data[ 0 ];
  52501. const buffer = device.createBuffer( {
  52502. label: 'bindingCameraIndex_' + index,
  52503. size: 16, // uint(4) * 4
  52504. usage: usage
  52505. } );
  52506. device.queue.writeBuffer( buffer, 0, data, 0 );
  52507. const entries = [ { binding: 0, resource: { buffer } } ];
  52508. return device.createBindGroup( {
  52509. label: 'bindGroupCameraIndex_' + index,
  52510. layout,
  52511. entries
  52512. } );
  52513. }
  52514. /**
  52515. * Creates a GPU bind group for the given bind group and GPU layout.
  52516. *
  52517. * @param {BindGroup} bindGroup - The bind group.
  52518. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  52519. * @return {GPUBindGroup} The GPU bind group.
  52520. */
  52521. createBindGroup( bindGroup, layoutGPU ) {
  52522. const backend = this.backend;
  52523. const device = backend.device;
  52524. let bindingPoint = 0;
  52525. const entriesGPU = [];
  52526. for ( const binding of bindGroup.bindings ) {
  52527. if ( binding.isUniformBuffer ) {
  52528. const bindingData = backend.get( binding );
  52529. if ( bindingData.buffer === undefined ) {
  52530. const byteLength = binding.byteLength;
  52531. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  52532. const bufferGPU = device.createBuffer( {
  52533. label: 'bindingBuffer_' + binding.name,
  52534. size: byteLength,
  52535. usage: usage
  52536. } );
  52537. bindingData.buffer = bufferGPU;
  52538. }
  52539. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  52540. } else if ( binding.isStorageBuffer ) {
  52541. const bindingData = backend.get( binding );
  52542. if ( bindingData.buffer === undefined ) {
  52543. const attribute = binding.attribute;
  52544. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  52545. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  52546. bindingData.buffer = backend.get( attribute ).buffer;
  52547. }
  52548. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  52549. } else if ( binding.isSampledTexture ) {
  52550. const textureData = backend.get( binding.texture );
  52551. let resourceGPU;
  52552. if ( textureData.externalTexture !== undefined ) {
  52553. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  52554. } else {
  52555. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  52556. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  52557. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  52558. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  52559. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  52560. }
  52561. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  52562. resourceGPU = textureData[ propertyName ];
  52563. if ( resourceGPU === undefined ) {
  52564. const aspectGPU = GPUTextureAspect.All;
  52565. let dimensionViewGPU;
  52566. if ( binding.isSampledCubeTexture ) {
  52567. dimensionViewGPU = GPUTextureViewDimension.Cube;
  52568. } else if ( binding.isSampledTexture3D ) {
  52569. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  52570. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  52571. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  52572. } else {
  52573. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  52574. }
  52575. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount, baseMipLevel } );
  52576. }
  52577. }
  52578. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  52579. } else if ( binding.isSampler ) {
  52580. const textureGPU = backend.get( binding.texture );
  52581. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  52582. }
  52583. bindingPoint ++;
  52584. }
  52585. return device.createBindGroup( {
  52586. label: 'bindGroup_' + bindGroup.name,
  52587. layout: layoutGPU,
  52588. entries: entriesGPU
  52589. } );
  52590. }
  52591. }
  52592. /**
  52593. * A WebGPU backend utility module for managing pipelines.
  52594. *
  52595. * @private
  52596. */
  52597. class WebGPUPipelineUtils {
  52598. /**
  52599. * Constructs a new utility object.
  52600. *
  52601. * @param {WebGPUBackend} backend - The WebGPU backend.
  52602. */
  52603. constructor( backend ) {
  52604. /**
  52605. * A reference to the WebGPU backend.
  52606. *
  52607. * @type {WebGPUBackend}
  52608. */
  52609. this.backend = backend;
  52610. /**
  52611. * A Weak Map that tracks the active pipeline for render or compute passes.
  52612. *
  52613. * @private
  52614. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  52615. */
  52616. this._activePipelines = new WeakMap();
  52617. }
  52618. /**
  52619. * Sets the given pipeline for the given pass. The method makes sure to only set the
  52620. * pipeline when necessary.
  52621. *
  52622. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  52623. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  52624. */
  52625. setPipeline( pass, pipeline ) {
  52626. const currentPipeline = this._activePipelines.get( pass );
  52627. if ( currentPipeline !== pipeline ) {
  52628. pass.setPipeline( pipeline );
  52629. this._activePipelines.set( pass, pipeline );
  52630. }
  52631. }
  52632. /**
  52633. * Returns the sample count derived from the given render context.
  52634. *
  52635. * @private
  52636. * @param {RenderContext} renderContext - The render context.
  52637. * @return {number} The sample count.
  52638. */
  52639. _getSampleCount( renderContext ) {
  52640. return this.backend.utils.getSampleCountRenderContext( renderContext );
  52641. }
  52642. /**
  52643. * Creates a render pipeline for the given render object.
  52644. *
  52645. * @param {RenderObject} renderObject - The render object.
  52646. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  52647. */
  52648. createRenderPipeline( renderObject, promises ) {
  52649. const { object, material, geometry, pipeline } = renderObject;
  52650. const { vertexProgram, fragmentProgram } = pipeline;
  52651. const backend = this.backend;
  52652. const device = backend.device;
  52653. const utils = backend.utils;
  52654. const pipelineData = backend.get( pipeline );
  52655. // bind group layouts
  52656. const bindGroupLayouts = [];
  52657. for ( const bindGroup of renderObject.getBindings() ) {
  52658. const bindingsData = backend.get( bindGroup );
  52659. bindGroupLayouts.push( bindingsData.layout );
  52660. }
  52661. // vertex buffers
  52662. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  52663. // blending
  52664. let blending;
  52665. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  52666. blending = this._getBlending( material );
  52667. }
  52668. // stencil
  52669. let stencilFront = {};
  52670. if ( material.stencilWrite === true ) {
  52671. stencilFront = {
  52672. compare: this._getStencilCompare( material ),
  52673. failOp: this._getStencilOperation( material.stencilFail ),
  52674. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  52675. passOp: this._getStencilOperation( material.stencilZPass )
  52676. };
  52677. }
  52678. const colorWriteMask = this._getColorWriteMask( material );
  52679. const targets = [];
  52680. if ( renderObject.context.textures !== null ) {
  52681. const textures = renderObject.context.textures;
  52682. for ( let i = 0; i < textures.length; i ++ ) {
  52683. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  52684. targets.push( {
  52685. format: colorFormat,
  52686. blend: blending,
  52687. writeMask: colorWriteMask
  52688. } );
  52689. }
  52690. } else {
  52691. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  52692. targets.push( {
  52693. format: colorFormat,
  52694. blend: blending,
  52695. writeMask: colorWriteMask
  52696. } );
  52697. }
  52698. const vertexModule = backend.get( vertexProgram ).module;
  52699. const fragmentModule = backend.get( fragmentProgram ).module;
  52700. const primitiveState = this._getPrimitiveState( object, geometry, material );
  52701. const depthCompare = this._getDepthCompare( material );
  52702. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  52703. const sampleCount = this._getSampleCount( renderObject.context );
  52704. const pipelineDescriptor = {
  52705. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  52706. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  52707. fragment: Object.assign( {}, fragmentModule, { targets } ),
  52708. primitive: primitiveState,
  52709. multisample: {
  52710. count: sampleCount,
  52711. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  52712. },
  52713. layout: device.createPipelineLayout( {
  52714. bindGroupLayouts
  52715. } )
  52716. };
  52717. const depthStencil = {};
  52718. const renderDepth = renderObject.context.depth;
  52719. const renderStencil = renderObject.context.stencil;
  52720. if ( renderDepth === true || renderStencil === true ) {
  52721. if ( renderDepth === true ) {
  52722. depthStencil.format = depthStencilFormat;
  52723. depthStencil.depthWriteEnabled = material.depthWrite;
  52724. depthStencil.depthCompare = depthCompare;
  52725. }
  52726. if ( renderStencil === true ) {
  52727. depthStencil.stencilFront = stencilFront;
  52728. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  52729. depthStencil.stencilReadMask = material.stencilFuncMask;
  52730. depthStencil.stencilWriteMask = material.stencilWriteMask;
  52731. }
  52732. if ( material.polygonOffset === true ) {
  52733. depthStencil.depthBias = material.polygonOffsetUnits;
  52734. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  52735. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  52736. }
  52737. pipelineDescriptor.depthStencil = depthStencil;
  52738. }
  52739. if ( promises === null ) {
  52740. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  52741. } else {
  52742. const p = new Promise( ( resolve /*, reject*/ ) => {
  52743. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  52744. pipelineData.pipeline = pipeline;
  52745. resolve();
  52746. } );
  52747. } );
  52748. promises.push( p );
  52749. }
  52750. }
  52751. /**
  52752. * Creates GPU render bundle encoder for the given render context.
  52753. *
  52754. * @param {RenderContext} renderContext - The render context.
  52755. * @param {?string} [label='renderBundleEncoder'] - The label.
  52756. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  52757. */
  52758. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  52759. const backend = this.backend;
  52760. const { utils, device } = backend;
  52761. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  52762. const colorFormats = utils.getCurrentColorFormats( renderContext );
  52763. const sampleCount = this._getSampleCount( renderContext );
  52764. const descriptor = {
  52765. label,
  52766. colorFormats,
  52767. depthStencilFormat,
  52768. sampleCount
  52769. };
  52770. return device.createRenderBundleEncoder( descriptor );
  52771. }
  52772. /**
  52773. * Creates a compute pipeline for the given compute node.
  52774. *
  52775. * @param {ComputePipeline} pipeline - The compute pipeline.
  52776. * @param {Array<BindGroup>} bindings - The bindings.
  52777. */
  52778. createComputePipeline( pipeline, bindings ) {
  52779. const backend = this.backend;
  52780. const device = backend.device;
  52781. const computeProgram = backend.get( pipeline.computeProgram ).module;
  52782. const pipelineGPU = backend.get( pipeline );
  52783. // bind group layouts
  52784. const bindGroupLayouts = [];
  52785. for ( const bindingsGroup of bindings ) {
  52786. const bindingsData = backend.get( bindingsGroup );
  52787. bindGroupLayouts.push( bindingsData.layout );
  52788. }
  52789. pipelineGPU.pipeline = device.createComputePipeline( {
  52790. compute: computeProgram,
  52791. layout: device.createPipelineLayout( {
  52792. bindGroupLayouts
  52793. } )
  52794. } );
  52795. }
  52796. /**
  52797. * Returns the blending state as a descriptor object required
  52798. * for the pipeline creation.
  52799. *
  52800. * @private
  52801. * @param {Material} material - The material.
  52802. * @return {Object} The blending state.
  52803. */
  52804. _getBlending( material ) {
  52805. let color, alpha;
  52806. const blending = material.blending;
  52807. const blendSrc = material.blendSrc;
  52808. const blendDst = material.blendDst;
  52809. const blendEquation = material.blendEquation;
  52810. if ( blending === CustomBlending ) {
  52811. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  52812. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  52813. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  52814. color = {
  52815. srcFactor: this._getBlendFactor( blendSrc ),
  52816. dstFactor: this._getBlendFactor( blendDst ),
  52817. operation: this._getBlendOperation( blendEquation )
  52818. };
  52819. alpha = {
  52820. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  52821. dstFactor: this._getBlendFactor( blendDstAlpha ),
  52822. operation: this._getBlendOperation( blendEquationAlpha )
  52823. };
  52824. } else {
  52825. const premultipliedAlpha = material.premultipliedAlpha;
  52826. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  52827. color = {
  52828. srcFactor: srcRGB,
  52829. dstFactor: dstRGB,
  52830. operation: GPUBlendOperation.Add
  52831. };
  52832. alpha = {
  52833. srcFactor: srcAlpha,
  52834. dstFactor: dstAlpha,
  52835. operation: GPUBlendOperation.Add
  52836. };
  52837. };
  52838. if ( premultipliedAlpha ) {
  52839. switch ( blending ) {
  52840. case NormalBlending:
  52841. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  52842. break;
  52843. case AdditiveBlending:
  52844. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  52845. break;
  52846. case SubtractiveBlending:
  52847. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  52848. break;
  52849. case MultiplyBlending:
  52850. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  52851. break;
  52852. }
  52853. } else {
  52854. switch ( blending ) {
  52855. case NormalBlending:
  52856. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  52857. break;
  52858. case AdditiveBlending:
  52859. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  52860. break;
  52861. case SubtractiveBlending:
  52862. error( 'WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  52863. break;
  52864. case MultiplyBlending:
  52865. error( 'WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  52866. break;
  52867. }
  52868. }
  52869. }
  52870. if ( color !== undefined && alpha !== undefined ) {
  52871. return { color, alpha };
  52872. } else {
  52873. error( 'WebGPURenderer: Invalid blending: ', blending );
  52874. }
  52875. }
  52876. /**
  52877. * Returns the GPU blend factor which is required for the pipeline creation.
  52878. *
  52879. * @private
  52880. * @param {number} blend - The blend factor as a three.js constant.
  52881. * @return {string} The GPU blend factor.
  52882. */
  52883. _getBlendFactor( blend ) {
  52884. let blendFactor;
  52885. switch ( blend ) {
  52886. case ZeroFactor:
  52887. blendFactor = GPUBlendFactor.Zero;
  52888. break;
  52889. case OneFactor:
  52890. blendFactor = GPUBlendFactor.One;
  52891. break;
  52892. case SrcColorFactor:
  52893. blendFactor = GPUBlendFactor.Src;
  52894. break;
  52895. case OneMinusSrcColorFactor:
  52896. blendFactor = GPUBlendFactor.OneMinusSrc;
  52897. break;
  52898. case SrcAlphaFactor:
  52899. blendFactor = GPUBlendFactor.SrcAlpha;
  52900. break;
  52901. case OneMinusSrcAlphaFactor:
  52902. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  52903. break;
  52904. case DstColorFactor:
  52905. blendFactor = GPUBlendFactor.Dst;
  52906. break;
  52907. case OneMinusDstColorFactor:
  52908. blendFactor = GPUBlendFactor.OneMinusDst;
  52909. break;
  52910. case DstAlphaFactor:
  52911. blendFactor = GPUBlendFactor.DstAlpha;
  52912. break;
  52913. case OneMinusDstAlphaFactor:
  52914. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  52915. break;
  52916. case SrcAlphaSaturateFactor:
  52917. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  52918. break;
  52919. case BlendColorFactor:
  52920. blendFactor = GPUBlendFactor.Constant;
  52921. break;
  52922. case OneMinusBlendColorFactor:
  52923. blendFactor = GPUBlendFactor.OneMinusConstant;
  52924. break;
  52925. default:
  52926. error( 'WebGPURenderer: Blend factor not supported.', blend );
  52927. }
  52928. return blendFactor;
  52929. }
  52930. /**
  52931. * Returns the GPU stencil compare function which is required for the pipeline creation.
  52932. *
  52933. * @private
  52934. * @param {Material} material - The material.
  52935. * @return {string} The GPU stencil compare function.
  52936. */
  52937. _getStencilCompare( material ) {
  52938. let stencilCompare;
  52939. const stencilFunc = material.stencilFunc;
  52940. switch ( stencilFunc ) {
  52941. case NeverStencilFunc:
  52942. stencilCompare = GPUCompareFunction.Never;
  52943. break;
  52944. case AlwaysStencilFunc:
  52945. stencilCompare = GPUCompareFunction.Always;
  52946. break;
  52947. case LessStencilFunc:
  52948. stencilCompare = GPUCompareFunction.Less;
  52949. break;
  52950. case LessEqualStencilFunc:
  52951. stencilCompare = GPUCompareFunction.LessEqual;
  52952. break;
  52953. case EqualStencilFunc:
  52954. stencilCompare = GPUCompareFunction.Equal;
  52955. break;
  52956. case GreaterEqualStencilFunc:
  52957. stencilCompare = GPUCompareFunction.GreaterEqual;
  52958. break;
  52959. case GreaterStencilFunc:
  52960. stencilCompare = GPUCompareFunction.Greater;
  52961. break;
  52962. case NotEqualStencilFunc:
  52963. stencilCompare = GPUCompareFunction.NotEqual;
  52964. break;
  52965. default:
  52966. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  52967. }
  52968. return stencilCompare;
  52969. }
  52970. /**
  52971. * Returns the GPU stencil operation which is required for the pipeline creation.
  52972. *
  52973. * @private
  52974. * @param {number} op - A three.js constant defining the stencil operation.
  52975. * @return {string} The GPU stencil operation.
  52976. */
  52977. _getStencilOperation( op ) {
  52978. let stencilOperation;
  52979. switch ( op ) {
  52980. case KeepStencilOp:
  52981. stencilOperation = GPUStencilOperation.Keep;
  52982. break;
  52983. case ZeroStencilOp:
  52984. stencilOperation = GPUStencilOperation.Zero;
  52985. break;
  52986. case ReplaceStencilOp:
  52987. stencilOperation = GPUStencilOperation.Replace;
  52988. break;
  52989. case InvertStencilOp:
  52990. stencilOperation = GPUStencilOperation.Invert;
  52991. break;
  52992. case IncrementStencilOp:
  52993. stencilOperation = GPUStencilOperation.IncrementClamp;
  52994. break;
  52995. case DecrementStencilOp:
  52996. stencilOperation = GPUStencilOperation.DecrementClamp;
  52997. break;
  52998. case IncrementWrapStencilOp:
  52999. stencilOperation = GPUStencilOperation.IncrementWrap;
  53000. break;
  53001. case DecrementWrapStencilOp:
  53002. stencilOperation = GPUStencilOperation.DecrementWrap;
  53003. break;
  53004. default:
  53005. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  53006. }
  53007. return stencilOperation;
  53008. }
  53009. /**
  53010. * Returns the GPU blend operation which is required for the pipeline creation.
  53011. *
  53012. * @private
  53013. * @param {number} blendEquation - A three.js constant defining the blend equation.
  53014. * @return {string} The GPU blend operation.
  53015. */
  53016. _getBlendOperation( blendEquation ) {
  53017. let blendOperation;
  53018. switch ( blendEquation ) {
  53019. case AddEquation:
  53020. blendOperation = GPUBlendOperation.Add;
  53021. break;
  53022. case SubtractEquation:
  53023. blendOperation = GPUBlendOperation.Subtract;
  53024. break;
  53025. case ReverseSubtractEquation:
  53026. blendOperation = GPUBlendOperation.ReverseSubtract;
  53027. break;
  53028. case MinEquation:
  53029. blendOperation = GPUBlendOperation.Min;
  53030. break;
  53031. case MaxEquation:
  53032. blendOperation = GPUBlendOperation.Max;
  53033. break;
  53034. default:
  53035. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  53036. }
  53037. return blendOperation;
  53038. }
  53039. /**
  53040. * Returns the primitive state as a descriptor object required
  53041. * for the pipeline creation.
  53042. *
  53043. * @private
  53044. * @param {Object3D} object - The 3D object.
  53045. * @param {BufferGeometry} geometry - The geometry.
  53046. * @param {Material} material - The material.
  53047. * @return {Object} The primitive state.
  53048. */
  53049. _getPrimitiveState( object, geometry, material ) {
  53050. const descriptor = {};
  53051. const utils = this.backend.utils;
  53052. //
  53053. descriptor.topology = utils.getPrimitiveTopology( object, material );
  53054. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  53055. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  53056. }
  53057. //
  53058. let flipSided = ( material.side === BackSide );
  53059. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  53060. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  53061. //
  53062. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  53063. return descriptor;
  53064. }
  53065. /**
  53066. * Returns the GPU color write mask which is required for the pipeline creation.
  53067. *
  53068. * @private
  53069. * @param {Material} material - The material.
  53070. * @return {number} The GPU color write mask.
  53071. */
  53072. _getColorWriteMask( material ) {
  53073. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  53074. }
  53075. /**
  53076. * Returns the GPU depth compare function which is required for the pipeline creation.
  53077. *
  53078. * @private
  53079. * @param {Material} material - The material.
  53080. * @return {string} The GPU depth compare function.
  53081. */
  53082. _getDepthCompare( material ) {
  53083. let depthCompare;
  53084. if ( material.depthTest === false ) {
  53085. depthCompare = GPUCompareFunction.Always;
  53086. } else {
  53087. const depthFunc = material.depthFunc;
  53088. switch ( depthFunc ) {
  53089. case NeverDepth:
  53090. depthCompare = GPUCompareFunction.Never;
  53091. break;
  53092. case AlwaysDepth:
  53093. depthCompare = GPUCompareFunction.Always;
  53094. break;
  53095. case LessDepth:
  53096. depthCompare = GPUCompareFunction.Less;
  53097. break;
  53098. case LessEqualDepth:
  53099. depthCompare = GPUCompareFunction.LessEqual;
  53100. break;
  53101. case EqualDepth:
  53102. depthCompare = GPUCompareFunction.Equal;
  53103. break;
  53104. case GreaterEqualDepth:
  53105. depthCompare = GPUCompareFunction.GreaterEqual;
  53106. break;
  53107. case GreaterDepth:
  53108. depthCompare = GPUCompareFunction.Greater;
  53109. break;
  53110. case NotEqualDepth:
  53111. depthCompare = GPUCompareFunction.NotEqual;
  53112. break;
  53113. default:
  53114. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  53115. }
  53116. }
  53117. return depthCompare;
  53118. }
  53119. }
  53120. /**
  53121. * Manages a pool of WebGPU timestamp queries for performance measurement.
  53122. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  53123. *
  53124. * @augments TimestampQueryPool
  53125. */
  53126. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  53127. /**
  53128. * Creates a new WebGPU timestamp query pool.
  53129. *
  53130. * @param {GPUDevice} device - The WebGPU device to create queries on.
  53131. * @param {string} type - The type identifier for this query pool.
  53132. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  53133. */
  53134. constructor( device, type, maxQueries = 2048 ) {
  53135. super( maxQueries );
  53136. this.device = device;
  53137. this.type = type;
  53138. this.querySet = this.device.createQuerySet( {
  53139. type: 'timestamp',
  53140. count: this.maxQueries,
  53141. label: `queryset_global_timestamp_${type}`
  53142. } );
  53143. const bufferSize = this.maxQueries * 8;
  53144. this.resolveBuffer = this.device.createBuffer( {
  53145. label: `buffer_timestamp_resolve_${type}`,
  53146. size: bufferSize,
  53147. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  53148. } );
  53149. this.resultBuffer = this.device.createBuffer( {
  53150. label: `buffer_timestamp_result_${type}`,
  53151. size: bufferSize,
  53152. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  53153. } );
  53154. }
  53155. /**
  53156. * Allocates a pair of queries for a given render context.
  53157. *
  53158. * @param {string} uid - A unique identifier for the render context.
  53159. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  53160. */
  53161. allocateQueriesForContext( uid ) {
  53162. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  53163. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  53164. 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() } ).` );
  53165. return null;
  53166. }
  53167. const baseOffset = this.currentQueryIndex;
  53168. this.currentQueryIndex += 2;
  53169. this.queryOffsets.set( uid, baseOffset );
  53170. return baseOffset;
  53171. }
  53172. /**
  53173. * Asynchronously resolves all pending queries and returns the total duration.
  53174. * If there's already a pending resolve operation, returns that promise instead.
  53175. *
  53176. * @async
  53177. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  53178. */
  53179. async resolveQueriesAsync() {
  53180. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  53181. return this.lastValue;
  53182. }
  53183. if ( this.pendingResolve ) {
  53184. return this.pendingResolve;
  53185. }
  53186. this.pendingResolve = this._resolveQueries();
  53187. try {
  53188. const result = await this.pendingResolve;
  53189. return result;
  53190. } finally {
  53191. this.pendingResolve = null;
  53192. }
  53193. }
  53194. /**
  53195. * Internal method to resolve queries and calculate total duration.
  53196. *
  53197. * @async
  53198. * @private
  53199. * @returns {Promise<number>} The total duration in milliseconds.
  53200. */
  53201. async _resolveQueries() {
  53202. if ( this.isDisposed ) {
  53203. return this.lastValue;
  53204. }
  53205. try {
  53206. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  53207. return this.lastValue;
  53208. }
  53209. const currentOffsets = new Map( this.queryOffsets );
  53210. const queryCount = this.currentQueryIndex;
  53211. const bytesUsed = queryCount * 8;
  53212. // Reset state before GPU work
  53213. this.currentQueryIndex = 0;
  53214. this.queryOffsets.clear();
  53215. const commandEncoder = this.device.createCommandEncoder();
  53216. commandEncoder.resolveQuerySet(
  53217. this.querySet,
  53218. 0,
  53219. queryCount,
  53220. this.resolveBuffer,
  53221. 0
  53222. );
  53223. commandEncoder.copyBufferToBuffer(
  53224. this.resolveBuffer,
  53225. 0,
  53226. this.resultBuffer,
  53227. 0,
  53228. bytesUsed
  53229. );
  53230. const commandBuffer = commandEncoder.finish();
  53231. this.device.queue.submit( [ commandBuffer ] );
  53232. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  53233. return this.lastValue;
  53234. }
  53235. // Create and track the mapping operation
  53236. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  53237. if ( this.isDisposed ) {
  53238. if ( this.resultBuffer.mapState === 'mapped' ) {
  53239. this.resultBuffer.unmap();
  53240. }
  53241. return this.lastValue;
  53242. }
  53243. //
  53244. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  53245. const framesDuration = {};
  53246. const frames = [];
  53247. for ( const [ uid, baseOffset ] of currentOffsets ) {
  53248. const match = uid.match( /^(.*):f(\d+)$/ );
  53249. const frame = parseInt( match[ 2 ] );
  53250. if ( frames.includes( frame ) === false ) {
  53251. frames.push( frame );
  53252. }
  53253. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  53254. const startTime = times[ baseOffset ];
  53255. const endTime = times[ baseOffset + 1 ];
  53256. const duration = Number( endTime - startTime ) / 1e6;
  53257. this.timestamps.set( uid, duration );
  53258. framesDuration[ frame ] += duration;
  53259. }
  53260. // Return the total duration of the last frame
  53261. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  53262. this.resultBuffer.unmap();
  53263. this.lastValue = totalDuration;
  53264. this.frames = frames;
  53265. return totalDuration;
  53266. } catch ( error ) {
  53267. error( 'Error resolving queries:', error );
  53268. if ( this.resultBuffer.mapState === 'mapped' ) {
  53269. this.resultBuffer.unmap();
  53270. }
  53271. return this.lastValue;
  53272. }
  53273. }
  53274. /**
  53275. * Dispose of the query pool.
  53276. *
  53277. * @async
  53278. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  53279. */
  53280. async dispose() {
  53281. if ( this.isDisposed ) {
  53282. return;
  53283. }
  53284. this.isDisposed = true;
  53285. // Wait for pending resolve operation
  53286. if ( this.pendingResolve ) {
  53287. try {
  53288. await this.pendingResolve;
  53289. } catch ( error ) {
  53290. error( 'Error waiting for pending resolve:', error );
  53291. }
  53292. }
  53293. // Ensure buffer is unmapped before destroying
  53294. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  53295. try {
  53296. this.resultBuffer.unmap();
  53297. } catch ( error ) {
  53298. error( 'Error unmapping buffer:', error );
  53299. }
  53300. }
  53301. // Destroy resources
  53302. if ( this.querySet ) {
  53303. this.querySet.destroy();
  53304. this.querySet = null;
  53305. }
  53306. if ( this.resolveBuffer ) {
  53307. this.resolveBuffer.destroy();
  53308. this.resolveBuffer = null;
  53309. }
  53310. if ( this.resultBuffer ) {
  53311. this.resultBuffer.destroy();
  53312. this.resultBuffer = null;
  53313. }
  53314. this.queryOffsets.clear();
  53315. this.pendingResolve = null;
  53316. }
  53317. }
  53318. /*// debugger tools
  53319. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  53320. //*/
  53321. /**
  53322. * A backend implementation targeting WebGPU.
  53323. *
  53324. * @private
  53325. * @augments Backend
  53326. */
  53327. class WebGPUBackend extends Backend {
  53328. /**
  53329. * WebGPUBackend options.
  53330. *
  53331. * @typedef {Object} WebGPUBackend~Options
  53332. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  53333. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  53334. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  53335. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  53336. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  53337. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  53338. * @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.
  53339. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  53340. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  53341. * @property {string} [powerPreference=undefined] - The power preference.
  53342. * @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.
  53343. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  53344. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  53345. */
  53346. /**
  53347. * Constructs a new WebGPU backend.
  53348. *
  53349. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  53350. */
  53351. constructor( parameters = {} ) {
  53352. super( parameters );
  53353. /**
  53354. * This flag can be used for type testing.
  53355. *
  53356. * @type {boolean}
  53357. * @readonly
  53358. * @default true
  53359. */
  53360. this.isWebGPUBackend = true;
  53361. // some parameters require default values other than "undefined"
  53362. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  53363. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  53364. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  53365. /**
  53366. * Indicates whether the backend is in compatibility mode or not.
  53367. * @type {boolean}
  53368. * @default false
  53369. */
  53370. this.compatibilityMode = this.parameters.compatibilityMode;
  53371. /**
  53372. * A reference to the device.
  53373. *
  53374. * @type {?GPUDevice}
  53375. * @default null
  53376. */
  53377. this.device = null;
  53378. /**
  53379. * A reference to the default render pass descriptor.
  53380. *
  53381. * @type {?Object}
  53382. * @default null
  53383. */
  53384. this.defaultRenderPassdescriptor = null;
  53385. /**
  53386. * A reference to a backend module holding common utility functions.
  53387. *
  53388. * @type {WebGPUUtils}
  53389. */
  53390. this.utils = new WebGPUUtils( this );
  53391. /**
  53392. * A reference to a backend module holding shader attribute-related
  53393. * utility functions.
  53394. *
  53395. * @type {WebGPUAttributeUtils}
  53396. */
  53397. this.attributeUtils = new WebGPUAttributeUtils( this );
  53398. /**
  53399. * A reference to a backend module holding shader binding-related
  53400. * utility functions.
  53401. *
  53402. * @type {WebGPUBindingUtils}
  53403. */
  53404. this.bindingUtils = new WebGPUBindingUtils( this );
  53405. /**
  53406. * A reference to a backend module holding shader pipeline-related
  53407. * utility functions.
  53408. *
  53409. * @type {WebGPUPipelineUtils}
  53410. */
  53411. this.pipelineUtils = new WebGPUPipelineUtils( this );
  53412. /**
  53413. * A reference to a backend module holding shader texture-related
  53414. * utility functions.
  53415. *
  53416. * @type {WebGPUTextureUtils}
  53417. */
  53418. this.textureUtils = new WebGPUTextureUtils( this );
  53419. /**
  53420. * A map that manages the resolve buffers for occlusion queries.
  53421. *
  53422. * @type {Map<number,GPUBuffer>}
  53423. */
  53424. this.occludedResolveCache = new Map();
  53425. }
  53426. /**
  53427. * Initializes the backend so it is ready for usage.
  53428. *
  53429. * @async
  53430. * @param {Renderer} renderer - The renderer.
  53431. * @return {Promise} A Promise that resolves when the backend has been initialized.
  53432. */
  53433. async init( renderer ) {
  53434. await super.init( renderer );
  53435. //
  53436. const parameters = this.parameters;
  53437. // create the device if it is not passed with parameters
  53438. let device;
  53439. if ( parameters.device === undefined ) {
  53440. const adapterOptions = {
  53441. powerPreference: parameters.powerPreference,
  53442. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  53443. };
  53444. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  53445. if ( adapter === null ) {
  53446. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  53447. }
  53448. // feature support
  53449. const features = Object.values( GPUFeatureName );
  53450. const supportedFeatures = [];
  53451. for ( const name of features ) {
  53452. if ( adapter.features.has( name ) ) {
  53453. supportedFeatures.push( name );
  53454. }
  53455. }
  53456. const deviceDescriptor = {
  53457. requiredFeatures: supportedFeatures,
  53458. requiredLimits: parameters.requiredLimits
  53459. };
  53460. device = await adapter.requestDevice( deviceDescriptor );
  53461. } else {
  53462. device = parameters.device;
  53463. }
  53464. device.lost.then( ( info ) => {
  53465. const deviceLossInfo = {
  53466. api: 'WebGPU',
  53467. message: info.message || 'Unknown reason',
  53468. reason: info.reason || null,
  53469. originalEvent: info
  53470. };
  53471. renderer.onDeviceLost( deviceLossInfo );
  53472. } );
  53473. this.device = device;
  53474. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  53475. this.updateSize();
  53476. }
  53477. /**
  53478. * A reference to the context.
  53479. *
  53480. * @type {?GPUCanvasContext}
  53481. * @default null
  53482. */
  53483. get context() {
  53484. const canvasTarget = this.renderer.getCanvasTarget();
  53485. const canvasData = this.get( canvasTarget );
  53486. let context = canvasData.context;
  53487. if ( context === undefined ) {
  53488. const parameters = this.parameters;
  53489. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  53490. context = parameters.context;
  53491. } else {
  53492. context = canvasTarget.domElement.getContext( 'webgpu' );
  53493. }
  53494. // OffscreenCanvas does not have setAttribute, see #22811
  53495. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  53496. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  53497. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  53498. context.configure( {
  53499. device: this.device,
  53500. format: this.utils.getPreferredCanvasFormat(),
  53501. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  53502. alphaMode: alphaMode,
  53503. toneMapping: {
  53504. mode: toneMappingMode
  53505. }
  53506. } );
  53507. canvasData.context = context;
  53508. }
  53509. return context;
  53510. }
  53511. /**
  53512. * The coordinate system of the backend.
  53513. *
  53514. * @type {number}
  53515. * @readonly
  53516. */
  53517. get coordinateSystem() {
  53518. return WebGPUCoordinateSystem;
  53519. }
  53520. /**
  53521. * This method performs a readback operation by moving buffer data from
  53522. * a storage buffer attribute from the GPU to the CPU.
  53523. *
  53524. * @async
  53525. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  53526. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  53527. */
  53528. async getArrayBufferAsync( attribute ) {
  53529. return await this.attributeUtils.getArrayBufferAsync( attribute );
  53530. }
  53531. /**
  53532. * Returns the backend's rendering context.
  53533. *
  53534. * @return {GPUCanvasContext} The rendering context.
  53535. */
  53536. getContext() {
  53537. return this.context;
  53538. }
  53539. /**
  53540. * Returns the default render pass descriptor.
  53541. *
  53542. * In WebGPU, the default framebuffer must be configured
  53543. * like custom framebuffers so the backend needs a render
  53544. * pass descriptor even when rendering directly to screen.
  53545. *
  53546. * @private
  53547. * @return {Object} The render pass descriptor.
  53548. */
  53549. _getDefaultRenderPassDescriptor() {
  53550. const renderer = this.renderer;
  53551. const canvasTarget = renderer.getCanvasTarget();
  53552. const canvasData = this.get( canvasTarget );
  53553. const samples = renderer.currentSamples;
  53554. let descriptor = canvasData.descriptor;
  53555. if ( descriptor === undefined || canvasData.samples !== samples ) {
  53556. descriptor = {
  53557. colorAttachments: [ {
  53558. view: null
  53559. } ]
  53560. };
  53561. if ( renderer.depth === true || renderer.stencil === true ) {
  53562. descriptor.depthStencilAttachment = {
  53563. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  53564. };
  53565. }
  53566. const colorAttachment = descriptor.colorAttachments[ 0 ];
  53567. if ( samples > 0 ) {
  53568. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  53569. } else {
  53570. colorAttachment.resolveTarget = undefined;
  53571. }
  53572. canvasData.descriptor = descriptor;
  53573. canvasData.samples = samples;
  53574. }
  53575. const colorAttachment = descriptor.colorAttachments[ 0 ];
  53576. if ( samples > 0 ) {
  53577. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  53578. } else {
  53579. colorAttachment.view = this.context.getCurrentTexture().createView();
  53580. }
  53581. return descriptor;
  53582. }
  53583. /**
  53584. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  53585. *
  53586. * @param {RenderContext} renderContext - The render context.
  53587. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  53588. *
  53589. * @private
  53590. */
  53591. _isRenderCameraDepthArray( renderContext ) {
  53592. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  53593. }
  53594. /**
  53595. * Returns the render pass descriptor for the given render context.
  53596. *
  53597. * @private
  53598. * @param {RenderContext} renderContext - The render context.
  53599. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  53600. * @return {Object} The render pass descriptor.
  53601. */
  53602. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  53603. const renderTarget = renderContext.renderTarget;
  53604. const renderTargetData = this.get( renderTarget );
  53605. let descriptors = renderTargetData.descriptors;
  53606. if ( descriptors === undefined ||
  53607. renderTargetData.width !== renderTarget.width ||
  53608. renderTargetData.height !== renderTarget.height ||
  53609. renderTargetData.samples !== renderTarget.samples
  53610. ) {
  53611. descriptors = {};
  53612. renderTargetData.descriptors = descriptors;
  53613. }
  53614. const cacheKey = renderContext.getCacheKey();
  53615. let descriptorBase = descriptors[ cacheKey ];
  53616. if ( descriptorBase === undefined ) {
  53617. const textures = renderContext.textures;
  53618. const textureViews = [];
  53619. let sliceIndex;
  53620. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  53621. for ( let i = 0; i < textures.length; i ++ ) {
  53622. const textureData = this.get( textures[ i ] );
  53623. const viewDescriptor = {
  53624. label: `colorAttachment_${ i }`,
  53625. baseMipLevel: renderContext.activeMipmapLevel,
  53626. mipLevelCount: 1,
  53627. baseArrayLayer: renderContext.activeCubeFace,
  53628. arrayLayerCount: 1,
  53629. dimension: GPUTextureViewDimension.TwoD
  53630. };
  53631. if ( renderTarget.isRenderTarget3D ) {
  53632. sliceIndex = renderContext.activeCubeFace;
  53633. viewDescriptor.baseArrayLayer = 0;
  53634. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  53635. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  53636. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  53637. if ( isRenderCameraDepthArray === true ) {
  53638. const cameras = renderContext.camera.cameras;
  53639. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  53640. const layerViewDescriptor = {
  53641. ...viewDescriptor,
  53642. baseArrayLayer: layer,
  53643. arrayLayerCount: 1,
  53644. dimension: GPUTextureViewDimension.TwoD
  53645. };
  53646. const textureView = textureData.texture.createView( layerViewDescriptor );
  53647. textureViews.push( {
  53648. view: textureView,
  53649. resolveTarget: undefined,
  53650. depthSlice: undefined
  53651. } );
  53652. }
  53653. } else {
  53654. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  53655. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  53656. }
  53657. }
  53658. if ( isRenderCameraDepthArray !== true ) {
  53659. const textureView = textureData.texture.createView( viewDescriptor );
  53660. let view, resolveTarget;
  53661. if ( textureData.msaaTexture !== undefined ) {
  53662. view = textureData.msaaTexture.createView();
  53663. resolveTarget = textureView;
  53664. } else {
  53665. view = textureView;
  53666. resolveTarget = undefined;
  53667. }
  53668. textureViews.push( {
  53669. view,
  53670. resolveTarget,
  53671. depthSlice: sliceIndex
  53672. } );
  53673. }
  53674. }
  53675. descriptorBase = { textureViews };
  53676. if ( renderContext.depth ) {
  53677. const depthTextureData = this.get( renderContext.depthTexture );
  53678. const options = {};
  53679. if ( renderContext.depthTexture.isArrayTexture ) {
  53680. options.dimension = GPUTextureViewDimension.TwoD;
  53681. options.arrayLayerCount = 1;
  53682. options.baseArrayLayer = renderContext.activeCubeFace;
  53683. }
  53684. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  53685. }
  53686. descriptors[ cacheKey ] = descriptorBase;
  53687. renderTargetData.width = renderTarget.width;
  53688. renderTargetData.height = renderTarget.height;
  53689. renderTargetData.samples = renderTarget.samples;
  53690. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  53691. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  53692. }
  53693. const descriptor = {
  53694. colorAttachments: []
  53695. };
  53696. // Apply dynamic properties to cached views
  53697. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  53698. const viewInfo = descriptorBase.textureViews[ i ];
  53699. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  53700. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  53701. clearValue = colorAttachmentsConfig.clearValue;
  53702. }
  53703. descriptor.colorAttachments.push( {
  53704. view: viewInfo.view,
  53705. depthSlice: viewInfo.depthSlice,
  53706. resolveTarget: viewInfo.resolveTarget,
  53707. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  53708. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  53709. clearValue: clearValue
  53710. } );
  53711. }
  53712. if ( descriptorBase.depthStencilView ) {
  53713. descriptor.depthStencilAttachment = {
  53714. view: descriptorBase.depthStencilView
  53715. };
  53716. }
  53717. return descriptor;
  53718. }
  53719. /**
  53720. * This method is executed at the beginning of a render call and prepares
  53721. * the WebGPU state for upcoming render calls
  53722. *
  53723. * @param {RenderContext} renderContext - The render context.
  53724. */
  53725. beginRender( renderContext ) {
  53726. const renderContextData = this.get( renderContext );
  53727. //
  53728. const device = this.device;
  53729. const occlusionQueryCount = renderContext.occlusionQueryCount;
  53730. let occlusionQuerySet;
  53731. if ( occlusionQueryCount > 0 ) {
  53732. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  53733. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  53734. // Get a reference to the array of objects with queries. The renderContextData property
  53735. // can be changed by another render pass before the buffer.mapAsyc() completes.
  53736. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  53737. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  53738. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  53739. //
  53740. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  53741. renderContextData.occlusionQuerySet = occlusionQuerySet;
  53742. renderContextData.occlusionQueryIndex = 0;
  53743. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  53744. renderContextData.lastOcclusionObject = null;
  53745. }
  53746. let descriptor;
  53747. if ( renderContext.textures === null ) {
  53748. descriptor = this._getDefaultRenderPassDescriptor();
  53749. } else {
  53750. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  53751. }
  53752. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  53753. descriptor.occlusionQuerySet = occlusionQuerySet;
  53754. const depthStencilAttachment = descriptor.depthStencilAttachment;
  53755. if ( renderContext.textures !== null ) {
  53756. const colorAttachments = descriptor.colorAttachments;
  53757. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  53758. const colorAttachment = colorAttachments[ i ];
  53759. if ( renderContext.clearColor ) {
  53760. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  53761. colorAttachment.loadOp = GPULoadOp.Clear;
  53762. } else {
  53763. colorAttachment.loadOp = GPULoadOp.Load;
  53764. }
  53765. colorAttachment.storeOp = GPUStoreOp.Store;
  53766. }
  53767. } else {
  53768. const colorAttachment = descriptor.colorAttachments[ 0 ];
  53769. if ( renderContext.clearColor ) {
  53770. colorAttachment.clearValue = renderContext.clearColorValue;
  53771. colorAttachment.loadOp = GPULoadOp.Clear;
  53772. } else {
  53773. colorAttachment.loadOp = GPULoadOp.Load;
  53774. }
  53775. colorAttachment.storeOp = GPUStoreOp.Store;
  53776. }
  53777. //
  53778. if ( renderContext.depth ) {
  53779. if ( renderContext.clearDepth ) {
  53780. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  53781. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  53782. } else {
  53783. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  53784. }
  53785. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  53786. }
  53787. if ( renderContext.stencil ) {
  53788. if ( renderContext.clearStencil ) {
  53789. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  53790. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  53791. } else {
  53792. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  53793. }
  53794. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  53795. }
  53796. //
  53797. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  53798. // shadow arrays - prepare bundle encoders for each camera in an array camera
  53799. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  53800. const cameras = renderContext.camera.cameras;
  53801. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  53802. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  53803. } else {
  53804. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  53805. }
  53806. // Create bundle encoders for each layer
  53807. renderContextData.bundleEncoders = [];
  53808. renderContextData.bundleSets = [];
  53809. // Create separate bundle encoders for each camera in the array
  53810. for ( let i = 0; i < cameras.length; i ++ ) {
  53811. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  53812. renderContext,
  53813. 'renderBundleArrayCamera_' + i
  53814. );
  53815. // Initialize state tracking for this bundle
  53816. const bundleSets = {
  53817. attributes: {},
  53818. bindingGroups: [],
  53819. pipeline: null,
  53820. index: null
  53821. };
  53822. renderContextData.bundleEncoders.push( bundleEncoder );
  53823. renderContextData.bundleSets.push( bundleSets );
  53824. }
  53825. // We'll complete the bundles in finishRender
  53826. renderContextData.currentPass = null;
  53827. } else {
  53828. const currentPass = encoder.beginRenderPass( descriptor );
  53829. renderContextData.currentPass = currentPass;
  53830. if ( renderContext.viewport ) {
  53831. this.updateViewport( renderContext );
  53832. }
  53833. if ( renderContext.scissor ) {
  53834. const { x, y, width, height } = renderContext.scissorValue;
  53835. currentPass.setScissorRect( x, y, width, height );
  53836. }
  53837. }
  53838. //
  53839. renderContextData.descriptor = descriptor;
  53840. renderContextData.encoder = encoder;
  53841. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  53842. renderContextData.renderBundles = [];
  53843. }
  53844. /**
  53845. * This method creates layer descriptors for each camera in an array camera
  53846. * to prepare for rendering to a depth array texture.
  53847. *
  53848. * @param {RenderContext} renderContext - The render context.
  53849. * @param {Object} renderContextData - The render context data.
  53850. * @param {Object} descriptor - The render pass descriptor.
  53851. * @param {ArrayCamera} cameras - The array camera.
  53852. *
  53853. * @private
  53854. */
  53855. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  53856. const depthStencilAttachment = descriptor.depthStencilAttachment;
  53857. renderContextData.layerDescriptors = [];
  53858. const depthTextureData = this.get( renderContext.depthTexture );
  53859. if ( ! depthTextureData.viewCache ) {
  53860. depthTextureData.viewCache = [];
  53861. }
  53862. for ( let i = 0; i < cameras.length; i ++ ) {
  53863. const layerDescriptor = {
  53864. ...descriptor,
  53865. colorAttachments: [ {
  53866. ...descriptor.colorAttachments[ 0 ],
  53867. view: descriptor.colorAttachments[ i ].view
  53868. } ]
  53869. };
  53870. if ( descriptor.depthStencilAttachment ) {
  53871. const layerIndex = i;
  53872. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  53873. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  53874. dimension: GPUTextureViewDimension.TwoD,
  53875. baseArrayLayer: i,
  53876. arrayLayerCount: 1
  53877. } );
  53878. }
  53879. layerDescriptor.depthStencilAttachment = {
  53880. view: depthTextureData.viewCache[ layerIndex ],
  53881. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  53882. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  53883. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  53884. };
  53885. if ( renderContext.stencil ) {
  53886. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  53887. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  53888. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  53889. }
  53890. } else {
  53891. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  53892. }
  53893. renderContextData.layerDescriptors.push( layerDescriptor );
  53894. }
  53895. }
  53896. /**
  53897. * This method updates the layer descriptors for each camera in an array camera
  53898. * to prepare for rendering to a depth array texture.
  53899. *
  53900. * @param {RenderContext} renderContext - The render context.
  53901. * @param {Object} renderContextData - The render context data.
  53902. * @param {ArrayCamera} cameras - The array camera.
  53903. *
  53904. */
  53905. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  53906. for ( let i = 0; i < cameras.length; i ++ ) {
  53907. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  53908. if ( layerDescriptor.depthStencilAttachment ) {
  53909. const depthAttachment = layerDescriptor.depthStencilAttachment;
  53910. if ( renderContext.depth ) {
  53911. if ( renderContext.clearDepth ) {
  53912. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  53913. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  53914. } else {
  53915. depthAttachment.depthLoadOp = GPULoadOp.Load;
  53916. }
  53917. }
  53918. if ( renderContext.stencil ) {
  53919. if ( renderContext.clearStencil ) {
  53920. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  53921. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  53922. } else {
  53923. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  53924. }
  53925. }
  53926. }
  53927. }
  53928. }
  53929. /**
  53930. * This method is executed at the end of a render call and finalizes work
  53931. * after draw calls.
  53932. *
  53933. * @param {RenderContext} renderContext - The render context.
  53934. */
  53935. finishRender( renderContext ) {
  53936. const renderContextData = this.get( renderContext );
  53937. const occlusionQueryCount = renderContext.occlusionQueryCount;
  53938. if ( renderContextData.renderBundles.length > 0 ) {
  53939. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  53940. }
  53941. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  53942. renderContextData.currentPass.endOcclusionQuery();
  53943. }
  53944. // shadow arrays - Execute bundles for each layer
  53945. const encoder = renderContextData.encoder;
  53946. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  53947. const bundles = [];
  53948. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  53949. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  53950. bundles.push( bundleEncoder.finish() );
  53951. }
  53952. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  53953. if ( i < bundles.length ) {
  53954. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  53955. const renderPass = encoder.beginRenderPass( layerDescriptor );
  53956. if ( renderContext.viewport ) {
  53957. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  53958. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  53959. }
  53960. if ( renderContext.scissor ) {
  53961. const { x, y, width, height } = renderContext.scissorValue;
  53962. renderPass.setScissorRect( x, y, width, height );
  53963. }
  53964. renderPass.executeBundles( [ bundles[ i ] ] );
  53965. renderPass.end();
  53966. }
  53967. }
  53968. } else if ( renderContextData.currentPass ) {
  53969. renderContextData.currentPass.end();
  53970. }
  53971. if ( occlusionQueryCount > 0 ) {
  53972. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  53973. //
  53974. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  53975. if ( queryResolveBuffer === undefined ) {
  53976. queryResolveBuffer = this.device.createBuffer(
  53977. {
  53978. size: bufferSize,
  53979. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  53980. }
  53981. );
  53982. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  53983. }
  53984. //
  53985. const readBuffer = this.device.createBuffer(
  53986. {
  53987. size: bufferSize,
  53988. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  53989. }
  53990. );
  53991. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  53992. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  53993. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  53994. renderContextData.occlusionQueryBuffer = readBuffer;
  53995. //
  53996. this.resolveOccludedAsync( renderContext );
  53997. }
  53998. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  53999. //
  54000. if ( renderContext.textures !== null ) {
  54001. const textures = renderContext.textures;
  54002. for ( let i = 0; i < textures.length; i ++ ) {
  54003. const texture = textures[ i ];
  54004. if ( texture.generateMipmaps === true ) {
  54005. this.textureUtils.generateMipmaps( texture );
  54006. }
  54007. }
  54008. }
  54009. }
  54010. /**
  54011. * Returns `true` if the given 3D object is fully occluded by other
  54012. * 3D objects in the scene.
  54013. *
  54014. * @param {RenderContext} renderContext - The render context.
  54015. * @param {Object3D} object - The 3D object to test.
  54016. * @return {boolean} Whether the 3D object is fully occluded or not.
  54017. */
  54018. isOccluded( renderContext, object ) {
  54019. const renderContextData = this.get( renderContext );
  54020. return renderContextData.occluded && renderContextData.occluded.has( object );
  54021. }
  54022. /**
  54023. * This method processes the result of occlusion queries and writes it
  54024. * into render context data.
  54025. *
  54026. * @async
  54027. * @param {RenderContext} renderContext - The render context.
  54028. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  54029. */
  54030. async resolveOccludedAsync( renderContext ) {
  54031. const renderContextData = this.get( renderContext );
  54032. // handle occlusion query results
  54033. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  54034. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  54035. const occluded = new WeakSet();
  54036. renderContextData.currentOcclusionQueryObjects = null;
  54037. renderContextData.currentOcclusionQueryBuffer = null;
  54038. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  54039. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  54040. const results = new BigUint64Array( buffer );
  54041. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  54042. if ( results[ i ] === BigInt( 0 ) ) {
  54043. occluded.add( currentOcclusionQueryObjects[ i ] );
  54044. }
  54045. }
  54046. currentOcclusionQueryBuffer.destroy();
  54047. renderContextData.occluded = occluded;
  54048. }
  54049. }
  54050. /**
  54051. * Updates the viewport with the values from the given render context.
  54052. *
  54053. * @param {RenderContext} renderContext - The render context.
  54054. */
  54055. updateViewport( renderContext ) {
  54056. const { currentPass } = this.get( renderContext );
  54057. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  54058. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  54059. }
  54060. /**
  54061. * Returns the clear color and alpha into a single
  54062. * color object.
  54063. *
  54064. * @return {Color4} The clear color.
  54065. */
  54066. getClearColor() {
  54067. const clearColor = super.getClearColor();
  54068. // only premultiply alpha when alphaMode is "premultiplied"
  54069. if ( this.renderer.alpha === true ) {
  54070. clearColor.r *= clearColor.a;
  54071. clearColor.g *= clearColor.a;
  54072. clearColor.b *= clearColor.a;
  54073. }
  54074. return clearColor;
  54075. }
  54076. /**
  54077. * Performs a clear operation.
  54078. *
  54079. * @param {boolean} color - Whether the color buffer should be cleared or not.
  54080. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  54081. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  54082. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  54083. */
  54084. clear( color, depth, stencil, renderTargetContext = null ) {
  54085. const device = this.device;
  54086. const renderer = this.renderer;
  54087. let colorAttachments = [];
  54088. let depthStencilAttachment;
  54089. let clearValue;
  54090. let supportsDepth;
  54091. let supportsStencil;
  54092. if ( color ) {
  54093. const clearColor = this.getClearColor();
  54094. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  54095. }
  54096. if ( renderTargetContext === null ) {
  54097. supportsDepth = renderer.depth;
  54098. supportsStencil = renderer.stencil;
  54099. const descriptor = this._getDefaultRenderPassDescriptor();
  54100. if ( color ) {
  54101. colorAttachments = descriptor.colorAttachments;
  54102. const colorAttachment = colorAttachments[ 0 ];
  54103. colorAttachment.clearValue = clearValue;
  54104. colorAttachment.loadOp = GPULoadOp.Clear;
  54105. colorAttachment.storeOp = GPUStoreOp.Store;
  54106. }
  54107. if ( supportsDepth || supportsStencil ) {
  54108. depthStencilAttachment = descriptor.depthStencilAttachment;
  54109. }
  54110. } else {
  54111. supportsDepth = renderTargetContext.depth;
  54112. supportsStencil = renderTargetContext.stencil;
  54113. const clearConfig = {
  54114. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  54115. clearValue: color ? clearValue : undefined
  54116. };
  54117. if ( supportsDepth ) {
  54118. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  54119. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  54120. clearConfig.depthStoreOp = GPUStoreOp.Store;
  54121. }
  54122. if ( supportsStencil ) {
  54123. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  54124. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  54125. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  54126. }
  54127. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  54128. colorAttachments = descriptor.colorAttachments;
  54129. depthStencilAttachment = descriptor.depthStencilAttachment;
  54130. }
  54131. if ( supportsDepth && depthStencilAttachment ) {
  54132. if ( depth ) {
  54133. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  54134. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  54135. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  54136. } else {
  54137. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  54138. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  54139. }
  54140. }
  54141. //
  54142. if ( supportsStencil && depthStencilAttachment ) {
  54143. if ( stencil ) {
  54144. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  54145. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  54146. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  54147. } else {
  54148. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  54149. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  54150. }
  54151. }
  54152. //
  54153. const encoder = device.createCommandEncoder( { label: 'clear' } );
  54154. const currentPass = encoder.beginRenderPass( {
  54155. colorAttachments,
  54156. depthStencilAttachment
  54157. } );
  54158. currentPass.end();
  54159. device.queue.submit( [ encoder.finish() ] );
  54160. }
  54161. // compute
  54162. /**
  54163. * This method is executed at the beginning of a compute call and
  54164. * prepares the state for upcoming compute tasks.
  54165. *
  54166. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  54167. */
  54168. beginCompute( computeGroup ) {
  54169. const groupGPU = this.get( computeGroup );
  54170. //
  54171. const descriptor = {
  54172. label: 'computeGroup_' + computeGroup.id
  54173. };
  54174. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  54175. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  54176. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  54177. }
  54178. /**
  54179. * Executes a compute command for the given compute node.
  54180. *
  54181. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  54182. * @param {Node} computeNode - The compute node.
  54183. * @param {Array<BindGroup>} bindings - The bindings.
  54184. * @param {ComputePipeline} pipeline - The compute pipeline.
  54185. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  54186. */
  54187. compute( computeGroup, computeNode, bindings, pipeline, dispatchSizeOrCount = null ) {
  54188. const computeNodeData = this.get( computeNode );
  54189. const { passEncoderGPU } = this.get( computeGroup );
  54190. // pipeline
  54191. const pipelineGPU = this.get( pipeline ).pipeline;
  54192. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  54193. // bind groups
  54194. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  54195. const bindGroup = bindings[ i ];
  54196. const bindingsData = this.get( bindGroup );
  54197. passEncoderGPU.setBindGroup( i, bindingsData.group );
  54198. }
  54199. let dispatchSize;
  54200. if ( dispatchSizeOrCount === null ) {
  54201. dispatchSizeOrCount = computeNode.count;
  54202. }
  54203. if ( typeof dispatchSizeOrCount === 'number' ) {
  54204. // If a single number is given, we calculate the dispatch size based on the workgroup size
  54205. const count = dispatchSizeOrCount;
  54206. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  54207. // cache dispatch size to avoid recalculating it every time
  54208. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  54209. computeNodeData.count = count;
  54210. const workgroupSize = computeNode.workgroupSize;
  54211. let size = workgroupSize[ 0 ];
  54212. for ( let i = 1; i < workgroupSize.length; i ++ )
  54213. size *= workgroupSize[ i ];
  54214. const dispatchCount = Math.ceil( count / size );
  54215. //
  54216. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  54217. dispatchSize = [ dispatchCount, 1, 1 ];
  54218. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  54219. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  54220. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  54221. }
  54222. computeNodeData.dispatchSize = dispatchSize;
  54223. }
  54224. dispatchSize = computeNodeData.dispatchSize;
  54225. } else {
  54226. dispatchSize = dispatchSizeOrCount;
  54227. }
  54228. //
  54229. passEncoderGPU.dispatchWorkgroups(
  54230. dispatchSize[ 0 ],
  54231. dispatchSize[ 1 ] || 1,
  54232. dispatchSize[ 2 ] || 1
  54233. );
  54234. }
  54235. /**
  54236. * This method is executed at the end of a compute call and
  54237. * finalizes work after compute tasks.
  54238. *
  54239. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  54240. */
  54241. finishCompute( computeGroup ) {
  54242. const groupData = this.get( computeGroup );
  54243. groupData.passEncoderGPU.end();
  54244. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  54245. }
  54246. // render object
  54247. /**
  54248. * Executes a draw command for the given render object.
  54249. *
  54250. * @param {RenderObject} renderObject - The render object to draw.
  54251. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  54252. */
  54253. draw( renderObject, info ) {
  54254. const { object, material, context, pipeline } = renderObject;
  54255. const bindings = renderObject.getBindings();
  54256. const renderContextData = this.get( context );
  54257. const pipelineGPU = this.get( pipeline ).pipeline;
  54258. const index = renderObject.getIndex();
  54259. const hasIndex = ( index !== null );
  54260. const drawParams = renderObject.getDrawParameters();
  54261. if ( drawParams === null ) return;
  54262. // pipeline
  54263. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  54264. // pipeline
  54265. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  54266. currentSets.pipeline = pipelineGPU;
  54267. // bind groups
  54268. const currentBindingGroups = currentSets.bindingGroups;
  54269. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  54270. const bindGroup = bindings[ i ];
  54271. const bindingsData = this.get( bindGroup );
  54272. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  54273. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  54274. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  54275. }
  54276. }
  54277. // attributes
  54278. // index
  54279. if ( hasIndex === true ) {
  54280. if ( currentSets.index !== index ) {
  54281. const buffer = this.get( index ).buffer;
  54282. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  54283. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  54284. currentSets.index = index;
  54285. }
  54286. }
  54287. // vertex buffers
  54288. const vertexBuffers = renderObject.getVertexBuffers();
  54289. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  54290. const vertexBuffer = vertexBuffers[ i ];
  54291. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  54292. const buffer = this.get( vertexBuffer ).buffer;
  54293. passEncoderGPU.setVertexBuffer( i, buffer );
  54294. currentSets.attributes[ i ] = vertexBuffer;
  54295. }
  54296. }
  54297. // stencil
  54298. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  54299. passEncoderGPU.setStencilReference( material.stencilRef );
  54300. renderContextData.currentStencilRef = material.stencilRef;
  54301. }
  54302. };
  54303. // Define draw function
  54304. const draw = ( passEncoderGPU, currentSets ) => {
  54305. setPipelineAndBindings( passEncoderGPU, currentSets );
  54306. if ( object.isBatchedMesh === true ) {
  54307. const starts = object._multiDrawStarts;
  54308. const counts = object._multiDrawCounts;
  54309. const drawCount = object._multiDrawCount;
  54310. const drawInstances = object._multiDrawInstances;
  54311. if ( drawInstances !== null ) {
  54312. // @deprecated, r174
  54313. warnOnce( 'WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  54314. }
  54315. for ( let i = 0; i < drawCount; i ++ ) {
  54316. const count = drawInstances ? drawInstances[ i ] : 1;
  54317. const firstInstance = count > 1 ? 0 : i;
  54318. if ( hasIndex === true ) {
  54319. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  54320. } else {
  54321. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  54322. }
  54323. info.update( object, counts[ i ], count );
  54324. }
  54325. } else if ( hasIndex === true ) {
  54326. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  54327. const indirect = renderObject.getIndirect();
  54328. if ( indirect !== null ) {
  54329. const buffer = this.get( indirect ).buffer;
  54330. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  54331. } else {
  54332. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  54333. }
  54334. info.update( object, indexCount, instanceCount );
  54335. } else {
  54336. const { vertexCount, instanceCount, firstVertex } = drawParams;
  54337. const indirect = renderObject.getIndirect();
  54338. if ( indirect !== null ) {
  54339. const buffer = this.get( indirect ).buffer;
  54340. passEncoderGPU.drawIndirect( buffer, 0 );
  54341. } else {
  54342. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  54343. }
  54344. info.update( object, vertexCount, instanceCount );
  54345. }
  54346. };
  54347. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  54348. const cameraData = this.get( renderObject.camera );
  54349. const cameras = renderObject.camera.cameras;
  54350. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  54351. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  54352. const bindingsData = this.get( cameraIndex );
  54353. const indexesGPU = [];
  54354. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  54355. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  54356. data[ 0 ] = i;
  54357. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  54358. indexesGPU.push( bindGroupIndex );
  54359. }
  54360. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  54361. }
  54362. const pixelRatio = this.renderer.getPixelRatio();
  54363. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  54364. const subCamera = cameras[ i ];
  54365. if ( object.layers.test( subCamera.layers ) ) {
  54366. const vp = subCamera.viewport;
  54367. let pass = renderContextData.currentPass;
  54368. let sets = renderContextData.currentSets;
  54369. if ( renderContextData.bundleEncoders ) {
  54370. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  54371. const bundleSets = renderContextData.bundleSets[ i ];
  54372. pass = bundleEncoder;
  54373. sets = bundleSets;
  54374. }
  54375. if ( vp ) {
  54376. pass.setViewport(
  54377. Math.floor( vp.x * pixelRatio ),
  54378. Math.floor( vp.y * pixelRatio ),
  54379. Math.floor( vp.width * pixelRatio ),
  54380. Math.floor( vp.height * pixelRatio ),
  54381. context.viewportValue.minDepth,
  54382. context.viewportValue.maxDepth
  54383. );
  54384. }
  54385. // Set camera index binding for this layer
  54386. if ( cameraIndex && cameraData.indexesGPU ) {
  54387. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  54388. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  54389. }
  54390. draw( pass, sets );
  54391. }
  54392. }
  54393. } else {
  54394. // Regular single camera rendering
  54395. if ( renderContextData.currentPass ) {
  54396. // Handle occlusion queries
  54397. if ( renderContextData.occlusionQuerySet !== undefined ) {
  54398. const lastObject = renderContextData.lastOcclusionObject;
  54399. if ( lastObject !== object ) {
  54400. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  54401. renderContextData.currentPass.endOcclusionQuery();
  54402. renderContextData.occlusionQueryIndex ++;
  54403. }
  54404. if ( object.occlusionTest === true ) {
  54405. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  54406. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  54407. }
  54408. renderContextData.lastOcclusionObject = object;
  54409. }
  54410. }
  54411. draw( renderContextData.currentPass, renderContextData.currentSets );
  54412. }
  54413. }
  54414. }
  54415. // cache key
  54416. /**
  54417. * Returns `true` if the render pipeline requires an update.
  54418. *
  54419. * @param {RenderObject} renderObject - The render object.
  54420. * @return {boolean} Whether the render pipeline requires an update or not.
  54421. */
  54422. needsRenderUpdate( renderObject ) {
  54423. const data = this.get( renderObject );
  54424. const { object, material } = renderObject;
  54425. const utils = this.utils;
  54426. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  54427. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  54428. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  54429. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  54430. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  54431. let needsUpdate = false;
  54432. if ( data.material !== material || data.materialVersion !== material.version ||
  54433. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  54434. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  54435. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  54436. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  54437. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  54438. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  54439. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  54440. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  54441. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  54442. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  54443. data.primitiveTopology !== primitiveTopology ||
  54444. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  54445. ) {
  54446. data.material = material; data.materialVersion = material.version;
  54447. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  54448. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  54449. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  54450. data.colorWrite = material.colorWrite;
  54451. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  54452. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  54453. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  54454. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  54455. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  54456. data.sampleCount = sampleCount;
  54457. data.colorSpace = colorSpace;
  54458. data.colorFormat = colorFormat;
  54459. data.depthStencilFormat = depthStencilFormat;
  54460. data.primitiveTopology = primitiveTopology;
  54461. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  54462. needsUpdate = true;
  54463. }
  54464. return needsUpdate;
  54465. }
  54466. /**
  54467. * Returns a cache key that is used to identify render pipelines.
  54468. *
  54469. * @param {RenderObject} renderObject - The render object.
  54470. * @return {string} The cache key.
  54471. */
  54472. getRenderCacheKey( renderObject ) {
  54473. const { object, material } = renderObject;
  54474. const utils = this.utils;
  54475. const renderContext = renderObject.context;
  54476. // meshes with negative scale have a different frontFace render pipeline
  54477. // descriptor value so the following must be honored in the cache key
  54478. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  54479. return [
  54480. material.transparent, material.blending, material.premultipliedAlpha,
  54481. material.blendSrc, material.blendDst, material.blendEquation,
  54482. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  54483. material.colorWrite,
  54484. material.depthWrite, material.depthTest, material.depthFunc,
  54485. material.stencilWrite, material.stencilFunc,
  54486. material.stencilFail, material.stencilZFail, material.stencilZPass,
  54487. material.stencilFuncMask, material.stencilWriteMask,
  54488. material.side,
  54489. frontFaceCW,
  54490. utils.getSampleCountRenderContext( renderContext ),
  54491. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  54492. utils.getPrimitiveTopology( object, material ),
  54493. renderObject.getGeometryCacheKey(),
  54494. renderObject.clippingContextCacheKey
  54495. ].join();
  54496. }
  54497. // textures
  54498. /**
  54499. * Updates a GPU sampler for the given texture.
  54500. *
  54501. * @param {Texture} texture - The texture to update the sampler for.
  54502. * @return {string} The current sampler key.
  54503. */
  54504. updateSampler( texture ) {
  54505. return this.textureUtils.updateSampler( texture );
  54506. }
  54507. /**
  54508. * Creates a default texture for the given texture that can be used
  54509. * as a placeholder until the actual texture is ready for usage.
  54510. *
  54511. * @param {Texture} texture - The texture to create a default texture for.
  54512. * @return {boolean} Whether the sampler has been updated or not.
  54513. */
  54514. createDefaultTexture( texture ) {
  54515. return this.textureUtils.createDefaultTexture( texture );
  54516. }
  54517. /**
  54518. * Defines a texture on the GPU for the given texture object.
  54519. *
  54520. * @param {Texture} texture - The texture.
  54521. * @param {Object} [options={}] - Optional configuration parameter.
  54522. */
  54523. createTexture( texture, options ) {
  54524. this.textureUtils.createTexture( texture, options );
  54525. }
  54526. /**
  54527. * Uploads the updated texture data to the GPU.
  54528. *
  54529. * @param {Texture} texture - The texture.
  54530. * @param {Object} [options={}] - Optional configuration parameter.
  54531. */
  54532. updateTexture( texture, options ) {
  54533. this.textureUtils.updateTexture( texture, options );
  54534. }
  54535. /**
  54536. * Generates mipmaps for the given texture.
  54537. *
  54538. * @param {Texture} texture - The texture.
  54539. */
  54540. generateMipmaps( texture ) {
  54541. this.textureUtils.generateMipmaps( texture );
  54542. }
  54543. /**
  54544. * Destroys the GPU data for the given texture object.
  54545. *
  54546. * @param {Texture} texture - The texture.
  54547. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  54548. */
  54549. destroyTexture( texture, isDefaultTexture = false ) {
  54550. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  54551. }
  54552. /**
  54553. * Returns texture data as a typed array.
  54554. *
  54555. * @async
  54556. * @param {Texture} texture - The texture to copy.
  54557. * @param {number} x - The x coordinate of the copy origin.
  54558. * @param {number} y - The y coordinate of the copy origin.
  54559. * @param {number} width - The width of the copy.
  54560. * @param {number} height - The height of the copy.
  54561. * @param {number} faceIndex - The face index.
  54562. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  54563. */
  54564. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  54565. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  54566. }
  54567. /**
  54568. * Inits a time stamp query for the given render context.
  54569. *
  54570. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  54571. * @param {number} uid - Unique id for the context (e.g. render context id).
  54572. * @param {Object} descriptor - The query descriptor.
  54573. */
  54574. initTimestampQuery( type, uid, descriptor ) {
  54575. if ( ! this.trackTimestamp ) return;
  54576. if ( ! this.timestampQueryPool[ type ] ) {
  54577. // TODO: Variable maxQueries?
  54578. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  54579. }
  54580. const timestampQueryPool = this.timestampQueryPool[ type ];
  54581. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  54582. descriptor.timestampWrites = {
  54583. querySet: timestampQueryPool.querySet,
  54584. beginningOfPassWriteIndex: baseOffset,
  54585. endOfPassWriteIndex: baseOffset + 1,
  54586. };
  54587. }
  54588. // node builder
  54589. /**
  54590. * Returns a node builder for the given render object.
  54591. *
  54592. * @param {RenderObject} object - The render object.
  54593. * @param {Renderer} renderer - The renderer.
  54594. * @return {WGSLNodeBuilder} The node builder.
  54595. */
  54596. createNodeBuilder( object, renderer ) {
  54597. return new WGSLNodeBuilder( object, renderer );
  54598. }
  54599. // program
  54600. /**
  54601. * Creates a shader program from the given programmable stage.
  54602. *
  54603. * @param {ProgrammableStage} program - The programmable stage.
  54604. */
  54605. createProgram( program ) {
  54606. const programGPU = this.get( program );
  54607. programGPU.module = {
  54608. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  54609. entryPoint: 'main'
  54610. };
  54611. }
  54612. /**
  54613. * Destroys the shader program of the given programmable stage.
  54614. *
  54615. * @param {ProgrammableStage} program - The programmable stage.
  54616. */
  54617. destroyProgram( program ) {
  54618. this.delete( program );
  54619. }
  54620. // pipelines
  54621. /**
  54622. * Creates a render pipeline for the given render object.
  54623. *
  54624. * @param {RenderObject} renderObject - The render object.
  54625. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  54626. */
  54627. createRenderPipeline( renderObject, promises ) {
  54628. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  54629. }
  54630. /**
  54631. * Creates a compute pipeline for the given compute node.
  54632. *
  54633. * @param {ComputePipeline} computePipeline - The compute pipeline.
  54634. * @param {Array<BindGroup>} bindings - The bindings.
  54635. */
  54636. createComputePipeline( computePipeline, bindings ) {
  54637. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  54638. }
  54639. /**
  54640. * Prepares the state for encoding render bundles.
  54641. *
  54642. * @param {RenderContext} renderContext - The render context.
  54643. */
  54644. beginBundle( renderContext ) {
  54645. const renderContextData = this.get( renderContext );
  54646. renderContextData._currentPass = renderContextData.currentPass;
  54647. renderContextData._currentSets = renderContextData.currentSets;
  54648. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  54649. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  54650. }
  54651. /**
  54652. * After processing render bundles this method finalizes related work.
  54653. *
  54654. * @param {RenderContext} renderContext - The render context.
  54655. * @param {RenderBundle} bundle - The render bundle.
  54656. */
  54657. finishBundle( renderContext, bundle ) {
  54658. const renderContextData = this.get( renderContext );
  54659. const bundleEncoder = renderContextData.currentPass;
  54660. const bundleGPU = bundleEncoder.finish();
  54661. this.get( bundle ).bundleGPU = bundleGPU;
  54662. // restore render pass state
  54663. renderContextData.currentSets = renderContextData._currentSets;
  54664. renderContextData.currentPass = renderContextData._currentPass;
  54665. }
  54666. /**
  54667. * Adds a render bundle to the render context data.
  54668. *
  54669. * @param {RenderContext} renderContext - The render context.
  54670. * @param {RenderBundle} bundle - The render bundle to add.
  54671. */
  54672. addBundle( renderContext, bundle ) {
  54673. const renderContextData = this.get( renderContext );
  54674. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  54675. }
  54676. // bindings
  54677. /**
  54678. * Creates bindings from the given bind group definition.
  54679. *
  54680. * @param {BindGroup} bindGroup - The bind group.
  54681. * @param {Array<BindGroup>} bindings - Array of bind groups.
  54682. * @param {number} cacheIndex - The cache index.
  54683. * @param {number} version - The version.
  54684. */
  54685. createBindings( bindGroup, bindings, cacheIndex, version ) {
  54686. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  54687. }
  54688. /**
  54689. * Updates the given bind group definition.
  54690. *
  54691. * @param {BindGroup} bindGroup - The bind group.
  54692. * @param {Array<BindGroup>} bindings - Array of bind groups.
  54693. * @param {number} cacheIndex - The cache index.
  54694. * @param {number} version - The version.
  54695. */
  54696. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  54697. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  54698. }
  54699. /**
  54700. * Updates a buffer binding.
  54701. *
  54702. * @param {Buffer} binding - The buffer binding to update.
  54703. */
  54704. updateBinding( binding ) {
  54705. this.bindingUtils.updateBinding( binding );
  54706. }
  54707. // attributes
  54708. /**
  54709. * Creates the buffer of an indexed shader attribute.
  54710. *
  54711. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  54712. */
  54713. createIndexAttribute( attribute ) {
  54714. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  54715. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  54716. usage |= GPUBufferUsage.STORAGE;
  54717. }
  54718. this.attributeUtils.createAttribute( attribute, usage );
  54719. }
  54720. /**
  54721. * Creates the GPU buffer of a shader attribute.
  54722. *
  54723. * @param {BufferAttribute} attribute - The buffer attribute.
  54724. */
  54725. createAttribute( attribute ) {
  54726. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  54727. }
  54728. /**
  54729. * Creates the GPU buffer of a storage attribute.
  54730. *
  54731. * @param {BufferAttribute} attribute - The buffer attribute.
  54732. */
  54733. createStorageAttribute( attribute ) {
  54734. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  54735. }
  54736. /**
  54737. * Creates the GPU buffer of an indirect storage attribute.
  54738. *
  54739. * @param {BufferAttribute} attribute - The buffer attribute.
  54740. */
  54741. createIndirectStorageAttribute( attribute ) {
  54742. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  54743. }
  54744. /**
  54745. * Updates the GPU buffer of a shader attribute.
  54746. *
  54747. * @param {BufferAttribute} attribute - The buffer attribute to update.
  54748. */
  54749. updateAttribute( attribute ) {
  54750. this.attributeUtils.updateAttribute( attribute );
  54751. }
  54752. /**
  54753. * Destroys the GPU buffer of a shader attribute.
  54754. *
  54755. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  54756. */
  54757. destroyAttribute( attribute ) {
  54758. this.attributeUtils.destroyAttribute( attribute );
  54759. }
  54760. // canvas
  54761. /**
  54762. * Triggers an update of the default render pass descriptor.
  54763. */
  54764. updateSize() {
  54765. this.delete( this.renderer.getCanvasTarget() );
  54766. }
  54767. // utils public
  54768. /**
  54769. * Returns the maximum anisotropy texture filtering value.
  54770. *
  54771. * @return {number} The maximum anisotropy texture filtering value.
  54772. */
  54773. getMaxAnisotropy() {
  54774. return 16;
  54775. }
  54776. /**
  54777. * Checks if the given feature is supported by the backend.
  54778. *
  54779. * @param {string} name - The feature's name.
  54780. * @return {boolean} Whether the feature is supported or not.
  54781. */
  54782. hasFeature( name ) {
  54783. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  54784. return this.device.features.has( name );
  54785. }
  54786. /**
  54787. * Copies data of the given source texture to the given destination texture.
  54788. *
  54789. * @param {Texture} srcTexture - The source texture.
  54790. * @param {Texture} dstTexture - The destination texture.
  54791. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  54792. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  54793. * @param {number} [srcLevel=0] - The mipmap level to copy.
  54794. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  54795. */
  54796. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  54797. let dstX = 0;
  54798. let dstY = 0;
  54799. let dstZ = 0;
  54800. let srcX = 0;
  54801. let srcY = 0;
  54802. let srcZ = 0;
  54803. let srcWidth = srcTexture.image.width;
  54804. let srcHeight = srcTexture.image.height;
  54805. let srcDepth = 1;
  54806. if ( srcRegion !== null ) {
  54807. if ( srcRegion.isBox3 === true ) {
  54808. srcX = srcRegion.min.x;
  54809. srcY = srcRegion.min.y;
  54810. srcZ = srcRegion.min.z;
  54811. srcWidth = srcRegion.max.x - srcRegion.min.x;
  54812. srcHeight = srcRegion.max.y - srcRegion.min.y;
  54813. srcDepth = srcRegion.max.z - srcRegion.min.z;
  54814. } else {
  54815. // Assume it's a Box2
  54816. srcX = srcRegion.min.x;
  54817. srcY = srcRegion.min.y;
  54818. srcWidth = srcRegion.max.x - srcRegion.min.x;
  54819. srcHeight = srcRegion.max.y - srcRegion.min.y;
  54820. srcDepth = 1;
  54821. }
  54822. }
  54823. if ( dstPosition !== null ) {
  54824. dstX = dstPosition.x;
  54825. dstY = dstPosition.y;
  54826. dstZ = dstPosition.z || 0;
  54827. }
  54828. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  54829. const sourceGPU = this.get( srcTexture ).texture;
  54830. const destinationGPU = this.get( dstTexture ).texture;
  54831. encoder.copyTextureToTexture(
  54832. {
  54833. texture: sourceGPU,
  54834. mipLevel: srcLevel,
  54835. origin: { x: srcX, y: srcY, z: srcZ }
  54836. },
  54837. {
  54838. texture: destinationGPU,
  54839. mipLevel: dstLevel,
  54840. origin: { x: dstX, y: dstY, z: dstZ }
  54841. },
  54842. [
  54843. srcWidth,
  54844. srcHeight,
  54845. srcDepth
  54846. ]
  54847. );
  54848. this.device.queue.submit( [ encoder.finish() ] );
  54849. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  54850. this.textureUtils.generateMipmaps( dstTexture );
  54851. }
  54852. }
  54853. /**
  54854. * Copies the current bound framebuffer to the given texture.
  54855. *
  54856. * @param {Texture} texture - The destination texture.
  54857. * @param {RenderContext} renderContext - The render context.
  54858. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  54859. */
  54860. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  54861. const renderContextData = this.get( renderContext );
  54862. let sourceGPU = null;
  54863. if ( renderContext.renderTarget ) {
  54864. if ( texture.isDepthTexture ) {
  54865. sourceGPU = this.get( renderContext.depthTexture ).texture;
  54866. } else {
  54867. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  54868. }
  54869. } else {
  54870. if ( texture.isDepthTexture ) {
  54871. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  54872. } else {
  54873. sourceGPU = this.context.getCurrentTexture();
  54874. }
  54875. }
  54876. const destinationGPU = this.get( texture ).texture;
  54877. if ( sourceGPU.format !== destinationGPU.format ) {
  54878. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  54879. return;
  54880. }
  54881. let encoder;
  54882. if ( renderContextData.currentPass ) {
  54883. renderContextData.currentPass.end();
  54884. encoder = renderContextData.encoder;
  54885. } else {
  54886. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  54887. }
  54888. encoder.copyTextureToTexture(
  54889. {
  54890. texture: sourceGPU,
  54891. origin: [ rectangle.x, rectangle.y, 0 ],
  54892. },
  54893. {
  54894. texture: destinationGPU
  54895. },
  54896. [
  54897. rectangle.z,
  54898. rectangle.w
  54899. ]
  54900. );
  54901. if ( renderContextData.currentPass ) {
  54902. const { descriptor } = renderContextData;
  54903. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  54904. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  54905. }
  54906. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  54907. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  54908. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  54909. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  54910. if ( renderContext.viewport ) {
  54911. this.updateViewport( renderContext );
  54912. }
  54913. if ( renderContext.scissor ) {
  54914. const { x, y, width, height } = renderContext.scissorValue;
  54915. renderContextData.currentPass.setScissorRect( x, y, width, height );
  54916. }
  54917. } else {
  54918. this.device.queue.submit( [ encoder.finish() ] );
  54919. }
  54920. if ( texture.generateMipmaps ) {
  54921. this.textureUtils.generateMipmaps( texture );
  54922. }
  54923. }
  54924. dispose() {
  54925. this.textureUtils.dispose();
  54926. }
  54927. }
  54928. /**
  54929. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  54930. *
  54931. * @augments SpotLight
  54932. */
  54933. class IESSpotLight extends SpotLight {
  54934. /**
  54935. * Constructs a new IES spot light.
  54936. *
  54937. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  54938. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  54939. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  54940. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  54941. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  54942. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  54943. */
  54944. constructor( color, intensity, distance, angle, penumbra, decay ) {
  54945. super( color, intensity, distance, angle, penumbra, decay );
  54946. /**
  54947. * TODO
  54948. *
  54949. * @type {?Texture}
  54950. * @default null
  54951. */
  54952. this.iesMap = null;
  54953. }
  54954. copy( source, recursive ) {
  54955. super.copy( source, recursive );
  54956. this.iesMap = source.iesMap;
  54957. return this;
  54958. }
  54959. }
  54960. /**
  54961. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  54962. *
  54963. * @augments SpotLight
  54964. */
  54965. class ProjectorLight extends SpotLight {
  54966. /**
  54967. * Constructs a new projector light.
  54968. *
  54969. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  54970. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  54971. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  54972. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  54973. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  54974. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  54975. */
  54976. constructor( color, intensity, distance, angle, penumbra, decay ) {
  54977. super( color, intensity, distance, angle, penumbra, decay );
  54978. /**
  54979. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  54980. *
  54981. * @type {?number}
  54982. * @default null
  54983. */
  54984. this.aspect = null;
  54985. }
  54986. copy( source, recursive ) {
  54987. super.copy( source, recursive );
  54988. this.aspect = source.aspect;
  54989. return this;
  54990. }
  54991. }
  54992. /**
  54993. * This version of a node library represents the standard version
  54994. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  54995. * techniques and materials to node-based implementations.
  54996. *
  54997. * @private
  54998. * @augments NodeLibrary
  54999. */
  55000. class StandardNodeLibrary extends NodeLibrary {
  55001. /**
  55002. * Constructs a new standard node library.
  55003. */
  55004. constructor() {
  55005. super();
  55006. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  55007. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  55008. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  55009. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  55010. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  55011. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  55012. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  55013. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  55014. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  55015. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  55016. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  55017. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  55018. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  55019. this.addLight( PointLightNode, PointLight );
  55020. this.addLight( DirectionalLightNode, DirectionalLight );
  55021. this.addLight( RectAreaLightNode, RectAreaLight );
  55022. this.addLight( SpotLightNode, SpotLight );
  55023. this.addLight( AmbientLightNode, AmbientLight );
  55024. this.addLight( HemisphereLightNode, HemisphereLight );
  55025. this.addLight( LightProbeNode, LightProbe );
  55026. this.addLight( IESSpotLightNode, IESSpotLight );
  55027. this.addLight( ProjectorLightNode, ProjectorLight );
  55028. this.addToneMapping( linearToneMapping, LinearToneMapping );
  55029. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  55030. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  55031. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  55032. this.addToneMapping( agxToneMapping, AgXToneMapping );
  55033. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  55034. }
  55035. }
  55036. /*
  55037. const debugHandler = {
  55038. get: function ( target, name ) {
  55039. // Add |update
  55040. if ( /^(create|destroy)/.test( name ) ) log( 'WebGPUBackend.' + name );
  55041. return target[ name ];
  55042. }
  55043. };
  55044. */
  55045. /**
  55046. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  55047. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  55048. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  55049. *
  55050. * @augments Renderer
  55051. */
  55052. class WebGPURenderer extends Renderer {
  55053. /**
  55054. * WebGPURenderer options.
  55055. *
  55056. * @typedef {Object} WebGPURenderer~Options
  55057. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  55058. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  55059. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  55060. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  55061. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  55062. * @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.
  55063. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  55064. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  55065. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  55066. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  55067. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  55068. */
  55069. /**
  55070. * Constructs a new WebGPU renderer.
  55071. *
  55072. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  55073. */
  55074. constructor( parameters = {} ) {
  55075. let BackendClass;
  55076. if ( parameters.forceWebGL ) {
  55077. BackendClass = WebGLBackend;
  55078. } else {
  55079. BackendClass = WebGPUBackend;
  55080. parameters.getFallback = () => {
  55081. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  55082. return new WebGLBackend( parameters );
  55083. };
  55084. }
  55085. const backend = new BackendClass( parameters );
  55086. //super( new Proxy( backend, debugHandler ) );
  55087. super( backend, parameters );
  55088. /**
  55089. * The generic default value is overwritten with the
  55090. * standard node library for type mapping.
  55091. *
  55092. * @type {StandardNodeLibrary}
  55093. */
  55094. this.library = new StandardNodeLibrary();
  55095. /**
  55096. * This flag can be used for type testing.
  55097. *
  55098. * @type {boolean}
  55099. * @readonly
  55100. * @default true
  55101. */
  55102. this.isWebGPURenderer = true;
  55103. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  55104. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  55105. }
  55106. }
  55107. }
  55108. /**
  55109. * A specialized group which enables applications access to the
  55110. * Render Bundle API of WebGPU. The group with all its descendant nodes
  55111. * are considered as one render bundle and processed as such by
  55112. * the renderer.
  55113. *
  55114. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  55115. * With a WebGL backend, the group can technically be rendered but without
  55116. * any performance improvements.
  55117. *
  55118. * @augments Group
  55119. */
  55120. class BundleGroup extends Group {
  55121. /**
  55122. * Constructs a new bundle group.
  55123. */
  55124. constructor() {
  55125. super();
  55126. /**
  55127. * This flag can be used for type testing.
  55128. *
  55129. * @type {boolean}
  55130. * @readonly
  55131. * @default true
  55132. */
  55133. this.isBundleGroup = true;
  55134. /**
  55135. * This property is only relevant for detecting types
  55136. * during serialization/deserialization. It should always
  55137. * match the class name.
  55138. *
  55139. * @type {string}
  55140. * @readonly
  55141. * @default 'BundleGroup'
  55142. */
  55143. this.type = 'BundleGroup';
  55144. /**
  55145. * Whether the bundle is static or not. When set to `true`, the structure
  55146. * is assumed to be static and does not change. E.g. no new objects are
  55147. * added to the group
  55148. *
  55149. * If a change is required, an update can still be forced by setting the
  55150. * `needsUpdate` flag to `true`.
  55151. *
  55152. * @type {boolean}
  55153. * @default true
  55154. */
  55155. this.static = true;
  55156. /**
  55157. * The bundle group's version.
  55158. *
  55159. * @type {number}
  55160. * @readonly
  55161. * @default 0
  55162. */
  55163. this.version = 0;
  55164. }
  55165. /**
  55166. * Set this property to `true` when the bundle group has changed.
  55167. *
  55168. * @type {boolean}
  55169. * @default false
  55170. * @param {boolean} value
  55171. */
  55172. set needsUpdate( value ) {
  55173. if ( value === true ) this.version ++;
  55174. }
  55175. }
  55176. /**
  55177. * This module is responsible to manage the post processing setups in apps.
  55178. * You usually create a single instance of this class and use it to define
  55179. * the output of your post processing effect chain.
  55180. * ```js
  55181. * const postProcessing = new PostProcessing( renderer );
  55182. *
  55183. * const scenePass = pass( scene, camera );
  55184. *
  55185. * postProcessing.outputNode = scenePass;
  55186. * ```
  55187. *
  55188. * Note: This module can only be used with `WebGPURenderer`.
  55189. */
  55190. class PostProcessing {
  55191. /**
  55192. * Constructs a new post processing management module.
  55193. *
  55194. * @param {Renderer} renderer - A reference to the renderer.
  55195. * @param {Node<vec4>} outputNode - An optional output node.
  55196. */
  55197. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  55198. /**
  55199. * A reference to the renderer.
  55200. *
  55201. * @type {Renderer}
  55202. */
  55203. this.renderer = renderer;
  55204. /**
  55205. * A node which defines the final output of the post
  55206. * processing. This is usually the last node in a chain
  55207. * of effect nodes.
  55208. *
  55209. * @type {Node<vec4>}
  55210. */
  55211. this.outputNode = outputNode;
  55212. /**
  55213. * Whether the default output tone mapping and color
  55214. * space transformation should be enabled or not.
  55215. *
  55216. * It is enabled by default by it must be disabled when
  55217. * effects must be executed after tone mapping and color
  55218. * space conversion. A typical example is FXAA which
  55219. * requires sRGB input.
  55220. *
  55221. * When set to `false`, the app must control the output
  55222. * transformation with `RenderOutputNode`.
  55223. *
  55224. * ```js
  55225. * const outputPass = renderOutput( scenePass );
  55226. * ```
  55227. *
  55228. * @type {boolean}
  55229. */
  55230. this.outputColorTransform = true;
  55231. /**
  55232. * Must be set to `true` when the output node changes.
  55233. *
  55234. * @type {Node<vec4>}
  55235. */
  55236. this.needsUpdate = true;
  55237. const material = new NodeMaterial();
  55238. material.name = 'PostProcessing';
  55239. /**
  55240. * The full screen quad that is used to render
  55241. * the effects.
  55242. *
  55243. * @private
  55244. * @type {QuadMesh}
  55245. */
  55246. this._quadMesh = new QuadMesh( material );
  55247. this._quadMesh.name = 'Post-Processing';
  55248. /**
  55249. * The context of the post processing stack.
  55250. *
  55251. * @private
  55252. * @type {?Object}
  55253. * @default null
  55254. */
  55255. this._context = null;
  55256. }
  55257. /**
  55258. * When `PostProcessing` is used to apply post processing effects,
  55259. * the application must use this version of `render()` inside
  55260. * its animation loop (not the one from the renderer).
  55261. */
  55262. render() {
  55263. const renderer = this.renderer;
  55264. this._update();
  55265. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  55266. const toneMapping = renderer.toneMapping;
  55267. const outputColorSpace = renderer.outputColorSpace;
  55268. renderer.toneMapping = NoToneMapping;
  55269. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  55270. //
  55271. const currentXR = renderer.xr.enabled;
  55272. renderer.xr.enabled = false;
  55273. this._quadMesh.render( renderer );
  55274. renderer.xr.enabled = currentXR;
  55275. //
  55276. renderer.toneMapping = toneMapping;
  55277. renderer.outputColorSpace = outputColorSpace;
  55278. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  55279. }
  55280. /**
  55281. * Returns the current context of the post processing stack.
  55282. *
  55283. * @readonly
  55284. * @type {?Object}
  55285. */
  55286. get context() {
  55287. return this._context;
  55288. }
  55289. /**
  55290. * Frees internal resources.
  55291. */
  55292. dispose() {
  55293. this._quadMesh.material.dispose();
  55294. }
  55295. /**
  55296. * Updates the state of the module.
  55297. *
  55298. * @private
  55299. */
  55300. _update() {
  55301. if ( this.needsUpdate === true ) {
  55302. const renderer = this.renderer;
  55303. const toneMapping = renderer.toneMapping;
  55304. const outputColorSpace = renderer.outputColorSpace;
  55305. const context = {
  55306. postProcessing: this,
  55307. onBeforePostProcessing: null,
  55308. onAfterPostProcessing: null
  55309. };
  55310. let outputNode = this.outputNode;
  55311. if ( this.outputColorTransform === true ) {
  55312. outputNode = outputNode.context( context );
  55313. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  55314. } else {
  55315. context.toneMapping = toneMapping;
  55316. context.outputColorSpace = outputColorSpace;
  55317. outputNode = outputNode.context( context );
  55318. }
  55319. this._context = context;
  55320. this._quadMesh.material.fragmentNode = outputNode;
  55321. this._quadMesh.material.needsUpdate = true;
  55322. this.needsUpdate = false;
  55323. }
  55324. }
  55325. /**
  55326. * When `PostProcessing` is used to apply post processing effects,
  55327. * the application must use this version of `renderAsync()` inside
  55328. * its animation loop (not the one from the renderer).
  55329. *
  55330. * @async
  55331. * @deprecated
  55332. * @return {Promise} A Promise that resolves when the render has been finished.
  55333. */
  55334. async renderAsync() {
  55335. warnOnce( 'PostProcessing: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  55336. await this.renderer.init();
  55337. this.render();
  55338. }
  55339. }
  55340. /**
  55341. * This special type of texture is intended for compute shaders.
  55342. * It can be used to compute the data of a texture with a compute shader.
  55343. *
  55344. * Note: This type of texture can only be used with `WebGPURenderer`
  55345. * and a WebGPU backend.
  55346. *
  55347. * @augments Texture
  55348. */
  55349. class StorageTexture extends Texture {
  55350. /**
  55351. * Constructs a new storage texture.
  55352. *
  55353. * @param {number} [width=1] - The storage texture's width.
  55354. * @param {number} [height=1] - The storage texture's height.
  55355. */
  55356. constructor( width = 1, height = 1 ) {
  55357. super();
  55358. /**
  55359. * The image object which just represents the texture's dimension.
  55360. *
  55361. * @type {{width: number, height: number}}
  55362. */
  55363. this.image = { width, height };
  55364. /**
  55365. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  55366. *
  55367. * @type {number}
  55368. */
  55369. this.magFilter = LinearFilter;
  55370. /**
  55371. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  55372. *
  55373. * @type {number}
  55374. */
  55375. this.minFilter = LinearFilter;
  55376. /**
  55377. * This flag can be used for type testing.
  55378. *
  55379. * @type {boolean}
  55380. * @readonly
  55381. * @default true
  55382. */
  55383. this.isStorageTexture = true;
  55384. /**
  55385. * When `true`, mipmaps will be auto-generated after compute writes.
  55386. * When `false`, mipmaps must be written manually via compute shaders.
  55387. *
  55388. * @type {boolean}
  55389. * @default true
  55390. */
  55391. this.mipmapsAutoUpdate = true;
  55392. }
  55393. /**
  55394. * Sets the size of the storage texture.
  55395. *
  55396. * @param {number} width - The new width of the storage texture.
  55397. * @param {number} height - The new height of the storage texture.
  55398. */
  55399. setSize( width, height ) {
  55400. if ( this.image.width !== width || this.image.height !== height ) {
  55401. this.image.width = width;
  55402. this.image.height = height;
  55403. this.dispose();
  55404. }
  55405. }
  55406. }
  55407. /**
  55408. * This special type of texture is intended for compute shaders.
  55409. * It can be used to compute the data of a texture with a compute shader.
  55410. *
  55411. * Note: This type of texture can only be used with `WebGPURenderer`
  55412. * and a WebGPU backend.
  55413. *
  55414. * @augments Texture
  55415. */
  55416. class Storage3DTexture extends Texture {
  55417. /**
  55418. * Constructs a new storage texture.
  55419. *
  55420. * @param {number} [width=1] - The storage texture's width.
  55421. * @param {number} [height=1] - The storage texture's height.
  55422. * @param {number} [depth=1] - The storage texture's depth.
  55423. */
  55424. constructor( width = 1, height = 1, depth = 1 ) {
  55425. super();
  55426. //inherited from texture. Must be false for 3DTexture
  55427. this.isArrayTexture = false;
  55428. /**
  55429. * The image object which just represents the texture's dimension.
  55430. *
  55431. * @type {{width: number, height: number, depth: number}}
  55432. */
  55433. this.image = { width, height, depth };
  55434. /**
  55435. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  55436. *
  55437. * @type {number}
  55438. */
  55439. this.magFilter = LinearFilter;
  55440. /**
  55441. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  55442. *
  55443. * @type {number}
  55444. */
  55445. this.minFilter = LinearFilter;
  55446. /**
  55447. * This defines how the texture is wrapped in the depth direction and corresponds to
  55448. * *W* in UVW mapping.
  55449. *
  55450. * @type {number}
  55451. */
  55452. this.wrapR = ClampToEdgeWrapping;
  55453. /**
  55454. * This flag can be used for type testing.
  55455. *
  55456. * @type {boolean}
  55457. * @readonly
  55458. * @default true
  55459. */
  55460. this.isStorageTexture = true;
  55461. /**
  55462. * Indicates whether this texture is a 3D texture.
  55463. *
  55464. * @type {boolean}
  55465. *
  55466. */
  55467. this.is3DTexture = true;
  55468. }
  55469. /**
  55470. * Sets the size of the storage 3d texture.
  55471. *
  55472. * @param {number} width - The new width of the storage texture.
  55473. * @param {number} height - The new height of the storage texture.
  55474. * @param {number} depth - The new depth of the storage texture.
  55475. */
  55476. setSize( width, height, depth ) {
  55477. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  55478. this.image.width = width;
  55479. this.image.height = height;
  55480. this.image.depth = depth;
  55481. this.dispose();
  55482. }
  55483. }
  55484. }
  55485. /**
  55486. * This special type of texture is intended for compute shaders.
  55487. * It can be used to compute the data of a texture with a compute shader.
  55488. *
  55489. * Note: This type of texture can only be used with `WebGPURenderer`
  55490. * and a WebGPU backend.
  55491. *
  55492. * @augments Texture
  55493. */
  55494. class StorageArrayTexture extends Texture {
  55495. /**
  55496. * Constructs a new storage texture.
  55497. *
  55498. * @param {number} [width=1] - The storage texture's width.
  55499. * @param {number} [height=1] - The storage texture's height.
  55500. * @param {number} [depth=1] - The storage texture's depth.
  55501. */
  55502. constructor( width = 1, height = 1, depth = 1 ) {
  55503. super();
  55504. //inherited from texture
  55505. this.isArrayTexture = true;
  55506. /**
  55507. * The image object which just represents the texture's dimension.
  55508. *
  55509. * @type {{width: number, height: number, depth: number}}
  55510. */
  55511. this.image = { width, height, depth };
  55512. /**
  55513. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  55514. *
  55515. * @type {number}
  55516. */
  55517. this.magFilter = LinearFilter;
  55518. /**
  55519. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  55520. *
  55521. * @type {number}
  55522. */
  55523. this.minFilter = LinearFilter;
  55524. /**
  55525. * This flag can be used for type testing.
  55526. *
  55527. * @type {boolean}
  55528. * @readonly
  55529. * @default true
  55530. */
  55531. this.isStorageTexture = true;
  55532. }
  55533. /**
  55534. * Sets the size of the storage array texture.
  55535. *
  55536. * @param {number} width - The new width of the storage texture.
  55537. * @param {number} height - The new height of the storage texture.
  55538. * @param {number} depth - The new depth of the storage texture.
  55539. */
  55540. setSize( width, height, depth ) {
  55541. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  55542. this.image.width = width;
  55543. this.image.height = height;
  55544. this.image.depth = depth;
  55545. this.dispose();
  55546. }
  55547. }
  55548. }
  55549. /**
  55550. * This special type of buffer attribute is intended for compute shaders.
  55551. * It can be used to encode draw parameters for indirect draw calls.
  55552. *
  55553. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  55554. * and a WebGPU backend.
  55555. *
  55556. * @augments StorageBufferAttribute
  55557. */
  55558. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  55559. /**
  55560. * Constructs a new storage buffer attribute.
  55561. *
  55562. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  55563. * The subsequent parameter is then obsolete.
  55564. * @param {number} itemSize - The item size.
  55565. */
  55566. constructor( count, itemSize ) {
  55567. super( count, itemSize, Uint32Array );
  55568. /**
  55569. * This flag can be used for type testing.
  55570. *
  55571. * @type {boolean}
  55572. * @readonly
  55573. * @default true
  55574. */
  55575. this.isIndirectStorageBufferAttribute = true;
  55576. }
  55577. }
  55578. /**
  55579. * A loader for loading node objects in the three.js JSON Object/Scene format.
  55580. *
  55581. * @augments Loader
  55582. */
  55583. class NodeLoader extends Loader {
  55584. /**
  55585. * Constructs a new node loader.
  55586. *
  55587. * @param {LoadingManager} [manager] - A reference to a loading manager.
  55588. */
  55589. constructor( manager ) {
  55590. super( manager );
  55591. /**
  55592. * Represents a dictionary of textures.
  55593. *
  55594. * @type {Object<string,Texture>}
  55595. */
  55596. this.textures = {};
  55597. /**
  55598. * Represents a dictionary of node types.
  55599. *
  55600. * @type {Object<string,Node.constructor>}
  55601. */
  55602. this.nodes = {};
  55603. }
  55604. /**
  55605. * Loads the node definitions from the given URL.
  55606. *
  55607. * @param {string} url - The path/URL of the file to be loaded.
  55608. * @param {Function} onLoad - Will be called when load completes.
  55609. * @param {Function} onProgress - Will be called while load progresses.
  55610. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  55611. */
  55612. load( url, onLoad, onProgress, onError ) {
  55613. const loader = new FileLoader( this.manager );
  55614. loader.setPath( this.path );
  55615. loader.setRequestHeader( this.requestHeader );
  55616. loader.setWithCredentials( this.withCredentials );
  55617. loader.load( url, ( text ) => {
  55618. try {
  55619. onLoad( this.parse( JSON.parse( text ) ) );
  55620. } catch ( e ) {
  55621. if ( onError ) {
  55622. onError( e );
  55623. } else {
  55624. error( e );
  55625. }
  55626. this.manager.itemError( url );
  55627. }
  55628. }, onProgress, onError );
  55629. }
  55630. /**
  55631. * Parse the node dependencies for the loaded node.
  55632. *
  55633. * @param {Array<Object>} [json] - The JSON definition
  55634. * @return {Object<string,Node>} A dictionary with node dependencies.
  55635. */
  55636. parseNodes( json ) {
  55637. const nodes = {};
  55638. if ( json !== undefined ) {
  55639. for ( const nodeJSON of json ) {
  55640. const { uuid, type } = nodeJSON;
  55641. nodes[ uuid ] = this.createNodeFromType( type );
  55642. nodes[ uuid ].uuid = uuid;
  55643. }
  55644. const meta = { nodes, textures: this.textures };
  55645. for ( const nodeJSON of json ) {
  55646. nodeJSON.meta = meta;
  55647. const node = nodes[ nodeJSON.uuid ];
  55648. node.deserialize( nodeJSON );
  55649. delete nodeJSON.meta;
  55650. }
  55651. }
  55652. return nodes;
  55653. }
  55654. /**
  55655. * Parses the node from the given JSON.
  55656. *
  55657. * @param {Object} json - The JSON definition
  55658. * @param {string} json.type - The node type.
  55659. * @param {string} json.uuid - The node UUID.
  55660. * @param {Array<Object>} [json.nodes] - The node dependencies.
  55661. * @param {Object} [json.meta] - The meta data.
  55662. * @return {Node} The parsed node.
  55663. */
  55664. parse( json ) {
  55665. const node = this.createNodeFromType( json.type );
  55666. node.uuid = json.uuid;
  55667. const nodes = this.parseNodes( json.nodes );
  55668. const meta = { nodes, textures: this.textures };
  55669. json.meta = meta;
  55670. node.deserialize( json );
  55671. delete json.meta;
  55672. return node;
  55673. }
  55674. /**
  55675. * Defines the dictionary of textures.
  55676. *
  55677. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  55678. * @return {NodeLoader} A reference to this loader.
  55679. */
  55680. setTextures( value ) {
  55681. this.textures = value;
  55682. return this;
  55683. }
  55684. /**
  55685. * Defines the dictionary of node types.
  55686. *
  55687. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  55688. * @return {NodeLoader} A reference to this loader.
  55689. */
  55690. setNodes( value ) {
  55691. this.nodes = value;
  55692. return this;
  55693. }
  55694. /**
  55695. * Creates a node object from the given type.
  55696. *
  55697. * @param {string} type - The node type.
  55698. * @return {Node} The created node instance.
  55699. */
  55700. createNodeFromType( type ) {
  55701. if ( this.nodes[ type ] === undefined ) {
  55702. error( 'NodeLoader: Node type not found:', type );
  55703. return float();
  55704. }
  55705. return nodeObject( new this.nodes[ type ]() );
  55706. }
  55707. }
  55708. /**
  55709. * A special type of material loader for loading node materials.
  55710. *
  55711. * @augments MaterialLoader
  55712. */
  55713. class NodeMaterialLoader extends MaterialLoader {
  55714. /**
  55715. * Constructs a new node material loader.
  55716. *
  55717. * @param {LoadingManager} [manager] - A reference to a loading manager.
  55718. */
  55719. constructor( manager ) {
  55720. super( manager );
  55721. /**
  55722. * Represents a dictionary of node types.
  55723. *
  55724. * @type {Object<string,Node.constructor>}
  55725. */
  55726. this.nodes = {};
  55727. /**
  55728. * Represents a dictionary of node material types.
  55729. *
  55730. * @type {Object<string,NodeMaterial.constructor>}
  55731. */
  55732. this.nodeMaterials = {};
  55733. }
  55734. /**
  55735. * Parses the node material from the given JSON.
  55736. *
  55737. * @param {Object} json - The JSON definition
  55738. * @return {NodeMaterial}. The parsed material.
  55739. */
  55740. parse( json ) {
  55741. const material = super.parse( json );
  55742. const nodes = this.nodes;
  55743. const inputNodes = json.inputNodes;
  55744. for ( const property in inputNodes ) {
  55745. const uuid = inputNodes[ property ];
  55746. material[ property ] = nodes[ uuid ];
  55747. }
  55748. return material;
  55749. }
  55750. /**
  55751. * Defines the dictionary of node types.
  55752. *
  55753. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  55754. * @return {NodeLoader} A reference to this loader.
  55755. */
  55756. setNodes( value ) {
  55757. this.nodes = value;
  55758. return this;
  55759. }
  55760. /**
  55761. * Defines the dictionary of node material types.
  55762. *
  55763. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  55764. * @return {NodeLoader} A reference to this loader.
  55765. */
  55766. setNodeMaterials( value ) {
  55767. this.nodeMaterials = value;
  55768. return this;
  55769. }
  55770. /**
  55771. * Creates a node material from the given type.
  55772. *
  55773. * @param {string} type - The node material type.
  55774. * @return {Node} The created node material instance.
  55775. */
  55776. createMaterialFromType( type ) {
  55777. const materialClass = this.nodeMaterials[ type ];
  55778. if ( materialClass !== undefined ) {
  55779. return new materialClass();
  55780. }
  55781. return super.createMaterialFromType( type );
  55782. }
  55783. }
  55784. /**
  55785. * A special type of object loader for loading 3D objects using
  55786. * node materials.
  55787. *
  55788. * @augments ObjectLoader
  55789. */
  55790. class NodeObjectLoader extends ObjectLoader {
  55791. /**
  55792. * Constructs a new node object loader.
  55793. *
  55794. * @param {LoadingManager} [manager] - A reference to a loading manager.
  55795. */
  55796. constructor( manager ) {
  55797. super( manager );
  55798. /**
  55799. * Represents a dictionary of node types.
  55800. *
  55801. * @type {Object<string,Node.constructor>}
  55802. */
  55803. this.nodes = {};
  55804. /**
  55805. * Represents a dictionary of node material types.
  55806. *
  55807. * @type {Object<string,NodeMaterial.constructor>}
  55808. */
  55809. this.nodeMaterials = {};
  55810. /**
  55811. * A reference to hold the `nodes` JSON property.
  55812. *
  55813. * @private
  55814. * @type {?Object[]}
  55815. */
  55816. this._nodesJSON = null;
  55817. }
  55818. /**
  55819. * Defines the dictionary of node types.
  55820. *
  55821. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  55822. * @return {NodeObjectLoader} A reference to this loader.
  55823. */
  55824. setNodes( value ) {
  55825. this.nodes = value;
  55826. return this;
  55827. }
  55828. /**
  55829. * Defines the dictionary of node material types.
  55830. *
  55831. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  55832. * @return {NodeObjectLoader} A reference to this loader.
  55833. */
  55834. setNodeMaterials( value ) {
  55835. this.nodeMaterials = value;
  55836. return this;
  55837. }
  55838. /**
  55839. * Parses the node objects from the given JSON.
  55840. *
  55841. * @param {Object} json - The JSON definition
  55842. * @param {Function} onLoad - The onLoad callback function.
  55843. * @return {Object3D}. The parsed 3D object.
  55844. */
  55845. parse( json, onLoad ) {
  55846. this._nodesJSON = json.nodes;
  55847. const data = super.parse( json, onLoad );
  55848. this._nodesJSON = null; // dispose
  55849. return data;
  55850. }
  55851. /**
  55852. * Parses the node objects from the given JSON and textures.
  55853. *
  55854. * @param {Object[]} json - The JSON definition
  55855. * @param {Object<string,Texture>} textures - The texture library.
  55856. * @return {Object<string,Node>}. The parsed nodes.
  55857. */
  55858. parseNodes( json, textures ) {
  55859. if ( json !== undefined ) {
  55860. const loader = new NodeLoader();
  55861. loader.setNodes( this.nodes );
  55862. loader.setTextures( textures );
  55863. return loader.parseNodes( json );
  55864. }
  55865. return {};
  55866. }
  55867. /**
  55868. * Parses the node objects from the given JSON and textures.
  55869. *
  55870. * @param {Object} json - The JSON definition
  55871. * @param {Object<string,Texture>} textures - The texture library.
  55872. * @return {Object<string,NodeMaterial>}. The parsed materials.
  55873. */
  55874. parseMaterials( json, textures ) {
  55875. const materials = {};
  55876. if ( json !== undefined ) {
  55877. const nodes = this.parseNodes( this._nodesJSON, textures );
  55878. const loader = new NodeMaterialLoader();
  55879. loader.setTextures( textures );
  55880. loader.setNodes( nodes );
  55881. loader.setNodeMaterials( this.nodeMaterials );
  55882. for ( let i = 0, l = json.length; i < l; i ++ ) {
  55883. const data = json[ i ];
  55884. materials[ data.uuid ] = loader.parse( data );
  55885. }
  55886. }
  55887. return materials;
  55888. }
  55889. }
  55890. /**
  55891. * In earlier three.js versions, clipping was defined globally
  55892. * on the renderer or on material level. This special version of
  55893. * `THREE.Group` allows to encode the clipping state into the scene
  55894. * graph. Meaning if you create an instance of this group, all
  55895. * descendant 3D objects will be affected by the respective clipping
  55896. * planes.
  55897. *
  55898. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  55899. *
  55900. * @augments Group
  55901. */
  55902. class ClippingGroup extends Group {
  55903. /**
  55904. * Constructs a new clipping group.
  55905. */
  55906. constructor() {
  55907. super();
  55908. /**
  55909. * This flag can be used for type testing.
  55910. *
  55911. * @type {boolean}
  55912. * @readonly
  55913. * @default true
  55914. */
  55915. this.isClippingGroup = true;
  55916. /**
  55917. * An array with clipping planes.
  55918. *
  55919. * @type {Array<Plane>}
  55920. */
  55921. this.clippingPlanes = [];
  55922. /**
  55923. * Whether clipping should be enabled or not.
  55924. *
  55925. * @type {boolean}
  55926. * @default true
  55927. */
  55928. this.enabled = true;
  55929. /**
  55930. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  55931. *
  55932. * @type {boolean}
  55933. * @default false
  55934. */
  55935. this.clipIntersection = false;
  55936. /**
  55937. * Whether shadows should be clipped or not.
  55938. *
  55939. * @type {boolean}
  55940. * @default false
  55941. */
  55942. this.clipShadows = false;
  55943. }
  55944. }
  55945. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BitcastNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, Camera, CanvasTarget, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, EventNode, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InspectorBase, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, IsolateNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoopNode, MRTNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, Storage3DTexture, StorageArrayElementNode, StorageArrayTexture, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, TimestampQuery, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, error, log$1 as log, shaderStages, vectorComponents, warn, warnOnce };
粤ICP备19079148号